handle-as-empty-document shouldn't be dependent on the image blocking
[privoxy.git] / w32log.c
1 const char w32log_rcs[] = "$Id: w32log.c,v 1.34 2009/05/16 13:27:20 fabiankeil Exp $";
2 /*********************************************************************
3  *
4  * File        :  $Source: /cvsroot/ijbswa/current/w32log.c,v $
5  *
6  * Purpose     :  Functions for creating and destroying the log window,
7  *                ouputting strings, processing messages and so on.
8  *
9  * Copyright   :  Written by and Copyright (C) 2001-2009 members of
10  *                the Privoxy team.  http://www.privoxy.org/
11  *
12  *                Written by and Copyright (C) 1999 Adam Lock
13  *                <locka@iol.ie>
14  *
15  *                This program is free software; you can redistribute it 
16  *                and/or modify it under the terms of the GNU General
17  *                Public License as published by the Free Software
18  *                Foundation; either version 2 of the License, or (at
19  *                your option) any later version.
20  *
21  *                This program is distributed in the hope that it will
22  *                be useful, but WITHOUT ANY WARRANTY; without even the
23  *                implied warranty of MERCHANTABILITY or FITNESS FOR A
24  *                PARTICULAR PURPOSE.  See the GNU General Public
25  *                License for more details.
26  *
27  *                The GNU General Public License should be included with
28  *                this file.  If not, you can view it at
29  *                http://www.gnu.org/copyleft/gpl.html
30  *                or write to the Free Software Foundation, Inc., 59
31  *                Temple Place - Suite 330, Boston, MA  02111-1307, USA.
32  *
33  *********************************************************************/
34
35
36 #include "config.h"
37
38 #include <assert.h>
39 #include <stdio.h>
40
41 #ifndef STRICT
42 #define STRICT
43 #endif
44 #include <windows.h>
45 #include <richedit.h>
46
47 #include "project.h"
48 #include "w32log.h"
49 #include "w32taskbar.h"
50 #include "win32.h"
51 #include "w32res.h"
52 #include "jcc.h"
53 #include "miscutil.h"
54 #include "errlog.h"
55 #include "loadcfg.h"
56
57 const char w32res_h_rcs[] = W32RES_H_VERSION;
58
59 #ifdef __MINGW32__
60 #include "cygwin.h"
61 const char cygwin_h_rcs[] = CYGWIN_H_VERSION;
62 #endif
63
64 const char w32log_h_rcs[] = W32LOG_H_VERSION;
65
66 #ifndef _WIN_CONSOLE /* entire file */
67
68 /*
69  * Timers and the various durations
70  */
71 #define TIMER_ANIM_ID               1
72 #define TIMER_ANIM_TIME             100
73 #define TIMER_ANIMSTOP_ID           2
74 #define TIMER_ANIMSTOP_TIME         1000
75 #define TIMER_CLIPBUFFER_ID         3
76 #define TIMER_CLIPBUFFER_TIME       1000
77 #define TIMER_CLIPBUFFER_FORCE_ID   4
78 #define TIMER_CLIPBUFFER_FORCE_TIME 5000
79
80 /*
81  * Styles of text that can be output
82  */
83 #define STYLE_NONE      0
84 #define STYLE_HIGHLIGHT 1
85 #define STYLE_LINK      2
86 #define STYLE_HEADER    3
87
88 /*
89  * Number of frames of animation in tray activity sequence
90  */
91 #define ANIM_FRAMES 8
92
93 #define DEFAULT_MAX_BUFFER_LINES    200
94 #define DEFAULT_LOG_FONT_NAME       "MS Sans Serif"
95 #define DEFAULT_LOG_FONT_SIZE       8
96
97 /*
98  * These values affect the way the log window behaves, they should be read
99  * from a file but for the moment, they are hardcoded here. Some options are
100  * configurable through the UI.
101  */
102
103 /* Indicates whether task bar shows activity animation */
104 BOOL g_bShowActivityAnimation = 1;
105
106 /* Indicates whether the log window is shown */
107 BOOL g_bShowLogWindow = 1;
108
109 /* Indicates if the log window appears on the task bar */
110 BOOL g_bShowOnTaskBar = 0;
111
112 /* Indicates whether closing the log window really just hides it */
113 BOOL g_bCloseHidesWindow = 1;
114
115 /* Indicates if messages are logged at all */
116 BOOL g_bLogMessages = 1;
117
118 /* Indicates whether log messages are highlighted */
119 BOOL g_bHighlightMessages = 1;
120
121 /* Indicates if buffer is limited in size */
122 BOOL g_bLimitBufferSize = 1;
123
124 /* Maximum number of lines allowed in buffer when limited */
125 int g_nMaxBufferLines = DEFAULT_MAX_BUFFER_LINES;
126
127 /* Font to use */
128 char g_szFontFaceName[32] = DEFAULT_LOG_FONT_NAME;
129
130 /* Size of font to use */
131 int g_nFontSize = DEFAULT_LOG_FONT_SIZE;
132
133
134 /* FIXME: this is a kludge */
135
136 const char * g_default_actions_file = NULL;
137 const char * g_user_actions_file = NULL;
138 const char * g_re_filterfile = NULL;
139 #ifdef FEATURE_TRUST
140 const char * g_trustfile = NULL;
141 #endif /* def FEATURE_TRUST */
142
143 /* FIXME: end kludge */
144
145 /* Regular expression for detected URLs */
146 #define RE_URL "http:[^ \n\r]*"
147
148 /*
149  * Regular expressions that are used to perform highlight in the log window
150  */
151 static struct _Pattern
152 {
153    const char *str;
154    int style;
155    regex_t buffer;
156 } patterns_to_highlight[] =
157 {
158    /* url headers */
159    { RE_URL,                STYLE_LINK },
160 /* { "[a-zA-Z0-9]+\\.[a-zA-Z0-9]+\\.[a-zA-Z0-9]+\\.[^ \n\r]*", STYLE_LINK }, */
161    /* interesting text to highlight */
162    /*   see jcc.c crunch_reason for the full list */
163    { "Crunch: Blocked:",            STYLE_HIGHLIGHT },
164    { "Crunch: Untrusted",           STYLE_HIGHLIGHT },
165    { "Crunch: Redirected:",         STYLE_HIGHLIGHT },
166    { "Crunch: DNS failure",         STYLE_HIGHLIGHT },
167    { "Crunch: Forwarding failed",   STYLE_HIGHLIGHT },
168    { "Crunch: Connection failure",  STYLE_HIGHLIGHT },
169    { "Crunch: Out of memory",       STYLE_HIGHLIGHT },
170    { "Connect: Found reusable socket",     STYLE_HIGHLIGHT },
171    { "Connect: Created new connection to", STYLE_HIGHLIGHT },
172    /* what are all the possible error strings?? */
173    { "Error:",                      STYLE_HIGHLIGHT },
174    /* http headers */
175    { "referer:",            STYLE_HEADER },
176    { "proxy-connection:",   STYLE_HEADER },
177    { "proxy-agent:",        STYLE_HEADER },
178    { "user-agent:",         STYLE_HEADER },
179    { "host:",               STYLE_HEADER },
180    { "accept:",             STYLE_HEADER },
181    { "accept-encoding:",    STYLE_HEADER },
182    { "accept-language:",    STYLE_HEADER },
183    { "accept-charset:",     STYLE_HEADER },
184    { "accept-ranges:",      STYLE_HEADER },
185    { "date:",               STYLE_HEADER },
186    { "cache-control:",      STYLE_HEADER },
187    { "cache-last-checked:", STYLE_HEADER },
188    { "connection:",         STYLE_HEADER },
189    { "content-type",        STYLE_HEADER },
190    { "content-length",      STYLE_HEADER },
191    { "cookie",              STYLE_HEADER },
192    { "last-modified:",      STYLE_HEADER },
193    { "pragma:",             STYLE_HEADER },
194    { "server:",             STYLE_HEADER },
195    { "etag:",               STYLE_HEADER },
196    { "expires:",            STYLE_HEADER },
197    { "warning:",            STYLE_HEADER },
198    /* this is the terminator statement - do not delete! */
199    { NULL,                  STYLE_NONE }
200 };
201
202 /*
203  * Public variables
204  */
205 HWND g_hwndLogFrame;
206 HICON g_hiconApp;
207
208 /*
209  * Private variables
210  */
211 static CRITICAL_SECTION g_criticalsection;
212 static HWND g_hwndTray;
213 static HWND g_hwndLogBox;
214 static WNDPROC g_fnLogBox;
215 static HICON g_hiconAnim[ANIM_FRAMES];
216 static HICON g_hiconIdle;
217 static HICON g_hiconOff;
218 static int g_nAnimFrame;
219 static BOOL g_bClipPending = FALSE;
220 static int g_nRichEditVersion = 0;
221
222 /*
223  * Private functions
224  */
225 static HWND CreateLogWindow(HINSTANCE hInstance, int nCmdShow);
226 static HWND CreateHiddenLogOwnerWindow(HINSTANCE hInstance);
227 static LRESULT CALLBACK LogWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
228 static LRESULT CALLBACK LogOwnerWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
229 static LRESULT CALLBACK LogRichEditProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam);
230 static BOOL InitRichEdit(void);
231 static void LogClipBuffer(void);
232 static void LogCreatePatternMatchingBuffers(void);
233 static void LogDestroyPatternMatchingBuffers(void);
234 static int LogPutStringNoMatch(const char *pszText, int style);
235 static void SetIdleIcon(void);
236
237
238 /*********************************************************************
239  *
240  * Function    :  InitLogWindow
241  *
242  * Description :  Initialise the log window.
243  *
244  * Parameters  :  None
245  *
246  * Returns     :  Always TRUE (there should be error checking on the resources).
247  *
248  *********************************************************************/
249 BOOL InitLogWindow(void)
250 {
251    int i;
252
253    /* Load the icons */
254    g_hiconIdle = LoadIcon(g_hInstance, MAKEINTRESOURCE(IDI_IDLE));
255    g_hiconOff  = LoadIcon(g_hInstance, MAKEINTRESOURCE(IDI_OFF));
256    for (i = 0; i < ANIM_FRAMES; i++)
257    {
258       g_hiconAnim[i] = LoadIcon(g_hInstance, MAKEINTRESOURCE(IDI_ANIMATED1 + i));
259    }
260    g_hiconApp = LoadIcon(g_hInstance, MAKEINTRESOURCE(IDI_MAINICON));
261
262    /* Create the user interface */
263    g_hwndLogFrame = CreateLogWindow(g_hInstance, g_nCmdShow);
264    g_hwndTray = CreateTrayWindow(g_hInstance);
265    TrayAddIcon(g_hwndTray, 1, g_hiconApp, "Privoxy");
266
267    /* Create pattern matching buffers (for highlighting */
268    LogCreatePatternMatchingBuffers();
269
270    /* Create a critical section to protect multi-threaded access to certain things */
271    InitializeCriticalSection(&g_criticalsection);
272
273    return TRUE;
274
275 }
276
277
278 /*********************************************************************
279  *
280  * Function    :  TermLogWindow
281  *
282  * Description :  Cleanup the logwindow.
283  *
284  * Parameters  :  None
285  *
286  * Returns     :  N/A
287  *
288  *********************************************************************/
289 void TermLogWindow(void)
290 {
291    int i;
292
293    LogDestroyPatternMatchingBuffers();
294
295    TrayDeleteIcon(g_hwndTray, 1);
296    DeleteObject(g_hiconApp);
297    DeleteObject(g_hiconIdle);
298    DeleteObject(g_hiconOff);
299    for (i = 0; i < ANIM_FRAMES; i++)
300    {
301       DeleteObject(g_hiconAnim[i]);
302    }
303
304 }
305
306
307 /*********************************************************************
308  *
309  * Function    :  LogCreatePatternMatchingBuffers
310  *
311  * Description :  Compile the pattern matching buffers.
312  *
313  * Parameters  :  None
314  *
315  * Returns     :  N/A
316  *
317  *********************************************************************/
318 void LogCreatePatternMatchingBuffers(void)
319 {
320    int i;
321    for (i = 0; patterns_to_highlight[i].str != NULL; i++)
322    {
323       regcomp(&patterns_to_highlight[i].buffer, patterns_to_highlight[i].str, REG_ICASE);
324    }
325 }
326
327
328 /*********************************************************************
329  *
330  * Function    :  LogDestroyPatternMatchingBuffers
331  *
332  * Description :  Free up the pattern matching buffers.
333  *
334  * Parameters  :  None
335  *
336  * Returns     :  N/A
337  *
338  *********************************************************************/
339 void LogDestroyPatternMatchingBuffers(void)
340 {
341    int i;
342    for (i = 0; patterns_to_highlight[i].str != NULL; i++)
343    {
344       regfree(&patterns_to_highlight[i].buffer);
345    }
346 }
347
348
349 /*********************************************************************
350  *
351  * Function    :  LogGetURLUnderCursor
352  *
353  * Description :  Returns the URL from under the cursor (remember to free it!).
354  *
355  * Parameters  :  None
356  *
357  * Returns     :  NULL or a pointer to an URL string.
358  *
359  *********************************************************************/
360 char *LogGetURLUnderCursor(void)
361 {
362    char *szResult = NULL;
363    regex_t re;
364    POINT ptCursor;
365    POINTL ptl;
366    DWORD nPos;
367    DWORD nWordStart = 0;
368    DWORD nWordEnd = 0;
369
370    regcomp(&re, RE_URL, REG_ICASE);
371
372    /* Get the position of the cursor over the text window */
373    GetCursorPos(&ptCursor);
374    ScreenToClient(g_hwndLogBox, &ptCursor);
375    ptl.x = ptCursor.x;
376    ptl.y = ptCursor.y;
377
378    /* Search backwards and fowards to obtain the word that is highlighted */
379    nPos = LOWORD(SendMessage(g_hwndLogBox, EM_CHARFROMPOS, 0, (LPARAM) &ptl));
380    nWordStart = SendMessage(g_hwndLogBox, EM_FINDWORDBREAK, WB_LEFT, nPos);
381    nWordEnd = SendMessage(g_hwndLogBox, EM_FINDWORDBREAK, WB_RIGHTBREAK, nPos);
382
383    /* Compare the string to the pattern */
384    if (nWordEnd > nWordStart)
385    {
386       TEXTRANGE range;
387       regmatch_t match;
388
389       range.chrg.cpMin = nWordStart;
390       range.chrg.cpMax = nWordEnd;
391       range.lpstrText = (LPSTR)zalloc(nWordEnd - nWordStart + 1);
392       SendMessage(g_hwndLogBox, EM_GETTEXTRANGE, 0, (LPARAM) &range);
393
394       if (regexec(&re, range.lpstrText, 1, &match, 0) == 0)
395       {
396          szResult = range.lpstrText;
397       }
398       else
399       {
400          free(range.lpstrText);
401       }
402
403       regfree(&re);
404    }
405    return szResult;
406
407 }
408
409
410 /*********************************************************************
411  *
412  * Function    :  LogPutString
413  *
414  * Description :  Inserts text into the logging window.  This is really
415  *                a regexp aware wrapper function to `LogPutStringNoMatch'.
416  *
417  * Parameters  :
418  *          1  :  pszText = pointer to string going to the log window
419  *
420  * Returns     :  1 => success, else the return code from `LogPutStringNoMatch'.
421  *                FIXME: this is backwards to the rest of IJB and to common
422  *                programming practice.  Please use 0 => success instead.
423  *
424  *********************************************************************/
425 int LogPutString(const char *pszText)
426 {
427    int i;
428    int result = 0;
429
430    if (pszText == NULL || strlen(pszText) == 0)
431    {
432       return 1;
433    }
434
435    if (!g_bLogMessages)
436    {
437       return 1;
438    }
439
440    /* Critical section stops multiple threads doing nasty interactions that
441     * foul up the highlighting and output.
442     */
443    EnterCriticalSection(&g_criticalsection);
444
445    if (g_bHighlightMessages)
446    {
447       regmatch_t match;
448
449       /* First things first, regexp scan for various things that we would like highlighted */
450       for (i = 0; patterns_to_highlight[i].str != NULL; i++)
451       {
452          if (regexec(&patterns_to_highlight[i].buffer, pszText, 1, &match, 0) == 0)
453          {
454             char *pszBefore = NULL;
455             char *pszMatch = NULL;
456             char *pszAfter = NULL;
457             int nMatchSize;
458
459             /* Split the string up into pieces representing the strings, before
460                at and after the matching pattern
461              */
462             if (match.rm_so > 0)
463             {
464                pszBefore = (char *)malloc((match.rm_so + 1) * sizeof(char));
465                memset(pszBefore, 0, (match.rm_so + 1) * sizeof(char));
466                strncpy(pszBefore, pszText, match.rm_so);
467             }
468             if (match.rm_eo < (regoff_t)strlen(pszText))
469             {
470                pszAfter = strdup(&pszText[match.rm_eo]);
471             }
472             nMatchSize = match.rm_eo - match.rm_so;
473             pszMatch = (char *)malloc(nMatchSize + 1);
474             strncpy(pszMatch, &pszText[match.rm_so], nMatchSize);
475             pszMatch[nMatchSize] = '\0';
476
477             /* Recursively call LogPutString */
478             if (pszBefore)
479             {
480                LogPutString(pszBefore);
481                free(pszBefore);
482             }
483             if (pszMatch)
484             {
485                LogPutStringNoMatch(pszMatch, patterns_to_highlight[i].style);
486                free(pszMatch);
487             }
488             if (pszAfter)
489             {
490                LogPutString(pszAfter);
491                free(pszAfter);
492             }
493
494             result = 1;
495             goto end;
496          }
497       }
498    }
499
500    result = LogPutStringNoMatch(pszText, STYLE_NONE);
501
502 end:
503    LeaveCriticalSection(&g_criticalsection);
504
505    return result;
506
507 }
508
509
510 /*********************************************************************
511  *
512  * Function    :  LogPutStringNoMatch
513  *
514  * Description :  Puts a string into the logging window.
515  *
516  * Parameters  :
517  *          1  :  pszText = pointer to string going to the log window
518  *          2  :  style = STYLE_NONE, STYLE_HEADER, STYLE_HIGHLIGHT, or STYLE_LINK
519  *
520  * Returns     :  Always 1 => success.
521  *                FIXME: this is backwards to the rest of IJB and to common
522  *                programming practice.  Please use 0 => success instead.
523  *
524  *********************************************************************/
525 int LogPutStringNoMatch(const char *pszText, int style)
526 {
527    CHARRANGE range;
528    CHARFORMAT format;
529    int nTextLength;
530
531    assert(g_hwndLogBox);
532    if (g_hwndLogBox == NULL)
533    {
534       return 1;
535    }
536
537    /* TODO preserve existing selection */
538
539    /* Go to the end of the text */
540    nTextLength = GetWindowTextLength(g_hwndLogBox);
541    range.cpMin = nTextLength;
542    range.cpMax = nTextLength;
543    SendMessage(g_hwndLogBox, EM_EXSETSEL, 0, (LPARAM) &range);
544
545    /* Apply a formatting style */
546    memset(&format, 0, sizeof(format));
547    format.cbSize = sizeof(format);
548    format.dwMask = CFM_BOLD | CFM_UNDERLINE | CFM_STRIKEOUT |
549       CFM_ITALIC | CFM_COLOR | CFM_FACE | CFM_SIZE | CFM_CHARSET;
550    format.bCharSet = DEFAULT_CHARSET;
551    format.yHeight = (g_nFontSize * 1440) / 72;
552    strlcpy(format.szFaceName, g_szFontFaceName, sizeof(format.szFaceName));
553    if (style == STYLE_NONE)
554    {
555       /* DO NOTHING */
556       format.dwEffects |= CFE_AUTOCOLOR;
557    }
558    else if (style == STYLE_HEADER)
559    {
560       format.dwEffects |= CFE_AUTOCOLOR | CFE_ITALIC;
561    }
562    else if (style == STYLE_HIGHLIGHT)
563    {
564       format.dwEffects |= CFE_AUTOCOLOR | CFE_BOLD;
565    }
566    else if (style == STYLE_LINK)
567    {
568       format.dwEffects |= CFE_UNDERLINE;
569       format.crTextColor = RGB(0, 0, 255);
570    }
571    SendMessage(g_hwndLogBox, EM_SETCHARFORMAT, SCF_SELECTION, (LPARAM) &format);
572
573    /* Append text to the end */
574    SendMessage(g_hwndLogBox, EM_REPLACESEL, FALSE, (LPARAM) pszText);
575
576    /* TODO Restore the old selection */
577
578    /* Purge buffer */
579    if (strchr(pszText, '\n') != NULL)
580    {
581       SetTimer(g_hwndLogFrame, TIMER_CLIPBUFFER_ID, TIMER_CLIPBUFFER_TIME, NULL);
582       if (!g_bClipPending)
583       {
584          /* Set the force clip timer going. This timer ensures clipping is done
585             intermittently even when there is a sustained burst of logging
586          */
587          SetTimer(g_hwndLogFrame, TIMER_CLIPBUFFER_FORCE_ID, TIMER_CLIPBUFFER_FORCE_TIME, NULL);
588       }
589       g_bClipPending = TRUE;
590    }
591
592    return 1;
593
594 }
595
596
597 /*********************************************************************
598  *
599  * Function    :  LogShowActivity
600  *
601  * Description :  Start the spinner.
602  *
603  * Parameters  :  None
604  *
605  * Returns     :  N/A
606  *
607  *********************************************************************/
608 void LogShowActivity(void)
609 {
610    /* Start some activity timers */
611    if (g_bShowActivityAnimation)
612    {
613       SetTimer(g_hwndLogFrame, TIMER_ANIM_ID, TIMER_ANIM_TIME, NULL);
614       SetTimer(g_hwndLogFrame, TIMER_ANIMSTOP_ID, TIMER_ANIMSTOP_TIME, NULL);
615    }
616
617 }
618
619
620 /*********************************************************************
621  *
622  * Function    :  LogClipBuffer
623  *
624  * Description :  Prunes old lines from the log.
625  *
626  * Parameters  :  None
627  *
628  * Returns     :  N/A
629  *
630  *********************************************************************/
631 void LogClipBuffer(void)
632 {
633    int nLines = SendMessage(g_hwndLogBox, EM_GETLINECOUNT, 0, 0);
634    if (g_bLimitBufferSize && nLines > g_nMaxBufferLines)
635    {
636       /* Compute the range representing the lines to be deleted */
637       LONG nLastLineToDelete = nLines - g_nMaxBufferLines;
638       LONG nLastChar = SendMessage(g_hwndLogBox, EM_LINEINDEX, nLastLineToDelete, 0);
639       CHARRANGE range;
640       range.cpMin = 0;
641       range.cpMax = nLastChar;
642
643       /* TODO get current selection */
644
645       /* TODO adjust and clip old selection against range to be deleted */
646
647       /* Select range and erase it (turning off autoscroll to prevent
648          nasty scrolling) */
649       SendMessage(g_hwndLogBox, EM_SETOPTIONS, ECOOP_XOR, ECO_AUTOVSCROLL);
650       SendMessage(g_hwndLogBox, EM_EXSETSEL, 0, (LPARAM) &range);
651       SendMessage(g_hwndLogBox, EM_REPLACESEL, FALSE, (LPARAM) "");
652       SendMessage(g_hwndLogBox, EM_SETOPTIONS, ECOOP_XOR, ECO_AUTOVSCROLL);
653
654       /* reposition (back to) the end of the log content */
655       range.cpMin = SendMessage (g_hwndLogBox, WM_GETTEXTLENGTH, 0, 0);
656       range.cpMax = -1;
657       SendMessage(g_hwndLogBox, EM_EXSETSEL, 0, (LPARAM) &range);
658  
659       /* restore vertical ScrollBar stuff (messed up by AUTOVSCROLL) */
660       SendMessage (g_hwndLogBox, EM_SCROLL, SB_LINEDOWN, 0);
661  
662    }
663
664 }                                        
665
666
667 /*********************************************************************
668  *
669  * Function    :  CreateHiddenLogOwnerWindow
670  *
671  * Description :  Creates a hidden owner window that stops the log
672  *                window appearing in the task bar.
673  *
674  * Parameters  :
675  *          1  :  hInstance = application's instance handle
676  *
677  * Returns     :  Handle to newly created window.
678  *
679  *********************************************************************/
680 HWND CreateHiddenLogOwnerWindow(HINSTANCE hInstance)
681 {
682    static const char *szWndName = "PrivoxyLogOwner";
683    WNDCLASS wc;
684    HWND hwnd;
685
686    wc.style          = 0;
687    wc.lpfnWndProc    = LogOwnerWindowProc;
688    wc.cbClsExtra     = 0;
689    wc.cbWndExtra     = 0;
690    wc.hInstance      = hInstance;
691    wc.hIcon          = g_hiconApp;
692    wc.hCursor        = 0;
693    wc.hbrBackground  = 0;
694    wc.lpszMenuName   = 0;
695    wc.lpszClassName  = szWndName;
696
697    RegisterClass(&wc);
698
699    hwnd = CreateWindow(szWndName, szWndName,
700       WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
701       CW_USEDEFAULT, NULL, NULL, hInstance, NULL );
702
703    return hwnd;
704
705 }
706
707
708 /*********************************************************************
709  *
710  * Function    :  LogOwnerWindowProc
711  *
712  * Description :  Dummy procedure that does nothing special.
713  *
714  * Parameters  :
715  *          1  :  hwnd = window handle
716  *          2  :  uMsg = message number
717  *          3  :  wParam = first param for this message
718  *          4  :  lParam = next param for this message
719  *
720  * Returns     :  Same as `DefWindowProc'.
721  *
722  *********************************************************************/
723 LRESULT CALLBACK LogOwnerWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
724 {
725    return DefWindowProc(hwnd, uMsg, wParam, lParam);
726
727 }
728
729
730 /*********************************************************************
731  *
732  * Function    :  CreateLogWindow
733  *
734  * Description :  Create the logging window.
735  *
736  * Parameters  :
737  *          1  :  hInstance = application's instance handle
738  *          2  :  nCmdShow = window show value (MIN, MAX, NORMAL, etc...)
739  *
740  * Returns     :  Handle to newly created window.
741  *
742  *********************************************************************/
743 HWND CreateLogWindow(HINSTANCE hInstance, int nCmdShow)
744 {
745    static const char *szWndName = "PrivoxyLogWindow";
746    static const char *szWndTitle = "Privoxy";
747
748    HWND hwnd = NULL;
749    HWND hwndOwner = (g_bShowOnTaskBar) ? NULL : CreateHiddenLogOwnerWindow(hInstance);
750    RECT rcClient;
751    WNDCLASSEX wc;
752
753    memset(&wc, 0, sizeof(wc));
754    wc.cbSize         = sizeof(wc);
755    wc.style          = CS_DBLCLKS;
756    wc.lpfnWndProc    = LogWindowProc;
757    wc.cbClsExtra     = 0;
758    wc.cbWndExtra     = 0;
759    wc.hInstance      = hInstance;
760    wc.hIcon          = g_hiconApp;
761    wc.hCursor        = 0;
762    wc.hbrBackground  = 0;
763    wc.lpszMenuName   = MAKEINTRESOURCE(IDR_LOGVIEW);
764    wc.lpszClassName  = szWndName;
765    wc.hbrBackground  = GetStockObject(WHITE_BRUSH);
766    RegisterClassEx(&wc);
767
768    hwnd = CreateWindowEx(WS_EX_APPWINDOW, szWndName, szWndTitle,
769       WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT,
770       CW_USEDEFAULT, hwndOwner, NULL, hInstance, NULL);
771
772    /* Now create a child list box */
773    GetClientRect(hwnd, &rcClient);
774
775    /* Create a rich edit control */
776    InitRichEdit();
777    g_hwndLogBox = CreateWindowEx(0, (g_nRichEditVersion == 0x0100) ? "RichEdit" : RICHEDIT_CLASS, "",
778       ES_AUTOVSCROLL | ES_MULTILINE | ES_READONLY | ES_NOHIDESEL | WS_CHILD | WS_VSCROLL | WS_HSCROLL | WS_VISIBLE,
779       rcClient.left, rcClient.top, rcClient.right, rcClient.bottom,
780       hwnd, NULL, hInstance, NULL);
781 /* SendMessage(g_hwndLogBox, EM_SETWORDWRAPMODE, 0, 0); */
782
783    /* Subclass the control to catch certain messages */
784    g_fnLogBox = (WNDPROC) GetWindowLong(g_hwndLogBox, GWL_WNDPROC);
785    SetWindowLong(g_hwndLogBox, GWL_WNDPROC, (LONG) LogRichEditProc);
786
787    /* Minimizing looks stupid when the log window is not on the task bar, so hide instead */
788    if (!g_bShowOnTaskBar &&
789          (nCmdShow == SW_SHOWMINIMIZED ||
790           nCmdShow == SW_MINIMIZE ||
791           nCmdShow == SW_SHOWMINNOACTIVE))
792    {
793       g_bShowLogWindow = FALSE;
794       nCmdShow = SW_HIDE;
795    }
796
797    ShowWindow(hwnd, nCmdShow);
798    UpdateWindow(hwnd);
799
800
801    GetClientRect(g_hwndLogFrame, &rcClient);
802    SetWindowPos(g_hwndLogBox, NULL, rcClient.left, rcClient.top, rcClient.right - rcClient.left, rcClient.bottom - rcClient.top, SWP_NOZORDER);
803
804    return hwnd;
805
806 }
807
808
809 /*********************************************************************
810  *
811  * Function    :  InitRichEdit
812  *
813  * Description :  Initialise the rich edit control library.
814  *
815  * Parameters  :  None
816  *
817  * Returns     :  TRUE => success, FALSE => failure.
818  *                FIXME: this is backwards to the rest of IJB and to common
819  *                programming practice.  Please use 0 => success instead.
820  *
821  *********************************************************************/
822 BOOL InitRichEdit(void)
823 {
824    static HINSTANCE hInstRichEdit;
825    if (hInstRichEdit == NULL)
826    {
827       g_nRichEditVersion = 0;
828       hInstRichEdit = LoadLibraryA("RICHED20.DLL");
829       if (hInstRichEdit)
830       {
831          g_nRichEditVersion = _RICHEDIT_VER;
832       }
833       else
834       {
835          hInstRichEdit = LoadLibraryA("RICHED32.DLL");
836          if (hInstRichEdit)
837          {
838             g_nRichEditVersion = 0x0100;
839          }
840       }
841    }
842    return (hInstRichEdit != NULL) ? TRUE : FALSE;
843
844 }
845
846
847 /*********************************************************************
848  *
849  * Function    :  ShowLogWindow
850  *
851  * Description :  Shows or hides the log window.  We will also raise the
852  *                window on a show command in case it is buried.
853  *
854  * Parameters  :
855  *          1  :  bShow = TRUE to show, FALSE to mimize/hide
856  *
857  * Returns     :  N/A
858  *
859  *********************************************************************/
860 void ShowLogWindow(BOOL bShow)
861 {
862    if (bShow)
863    {
864       SetForegroundWindow(g_hwndLogFrame);
865       SetWindowPos(g_hwndLogFrame, HWND_TOP, 0, 0, 0, 0, SWP_SHOWWINDOW | SWP_NOSIZE | SWP_NOMOVE);
866       
867    }
868    else if (g_bShowOnTaskBar)
869    {
870       ShowWindow(g_hwndLogFrame, SW_MINIMIZE);
871    }
872    else
873    {
874       ShowWindow(g_hwndLogFrame, SW_HIDE);
875    }
876 }
877
878
879 /*********************************************************************
880  *
881  * Function    :  EditFile
882  *
883  * Description :  Opens the specified setting file for editing.
884  * FIXME: What if the file has no associated application. Check for return values
885 *        from ShellExecute??
886  *
887  * Parameters  :
888  *          1  :  filename = filename from the config (aka config.txt) file.
889  *
890  * Returns     :  N/A
891  *
892  *********************************************************************/
893 void EditFile(const char *filename)
894 {
895    if (filename)
896    {
897       ShellExecute(g_hwndLogFrame, "open", filename, NULL, NULL, SW_SHOWNORMAL);
898    }
899
900 }
901
902
903 /*--------------------------------------------------------------------------*/
904 /* Windows message handlers                                                 */
905 /*--------------------------------------------------------------------------*/
906
907
908 /*********************************************************************
909  *
910  * Function    :  OnLogRButtonUp
911  *
912  * Description :  Handler for WM_RBUTTONUP messages.
913  *
914  * Parameters  :
915  *          1  :  nModifier = wParam from mouse message (unused)
916  *          2  :  x = x coordinate of the mouse event
917  *          3  :  y = y coordinate of the mouse event
918  *
919  * Returns     :  N/A
920  *
921  *********************************************************************/
922 void OnLogRButtonUp(int nModifier, int x, int y)
923 {
924    HMENU hMenu = LoadMenu(g_hInstance, MAKEINTRESOURCE(IDR_POPUP_SELECTION));
925    if (hMenu != NULL)
926    {
927       HMENU hMenuPopup = GetSubMenu(hMenu, 0);
928
929       /* Check if there is a selection */
930       CHARRANGE range;
931       SendMessage(g_hwndLogBox, EM_EXGETSEL, 0, (LPARAM) &range);
932       if (range.cpMin == range.cpMax)
933       {
934          EnableMenuItem(hMenuPopup, ID_EDIT_COPY, MF_BYCOMMAND | MF_GRAYED);
935       }
936       else
937       {
938          EnableMenuItem(hMenuPopup, ID_EDIT_COPY, MF_BYCOMMAND | MF_ENABLED);
939       }
940
941       /* Display the popup */
942       TrackPopupMenu(hMenuPopup, TPM_LEFTALIGN | TPM_TOPALIGN | TPM_RIGHTBUTTON, x, y, 0, g_hwndLogFrame, NULL);
943       DestroyMenu(hMenu);
944    }
945
946 }
947
948
949 /*********************************************************************
950  *
951  * Function    :  OnLogCommand
952  *
953  * Description :  Handler for WM_COMMAND messages.
954  *
955  * Parameters  :
956  *          1  :  nCommand = the command portion of the menu selection event
957  *
958  * Returns     :  N/A
959  *
960  *********************************************************************/
961 void OnLogCommand(int nCommand)
962 {
963    switch (nCommand)
964    {
965       case ID_TOGGLE_SHOWWINDOW:
966          g_bShowLogWindow = !g_bShowLogWindow;
967
968          ShowLogWindow(g_bShowLogWindow);
969          break;
970
971       case ID_FILE_EXIT:
972          PostMessage(g_hwndLogFrame, WM_CLOSE, 0, 0);
973          break;
974
975       case ID_EDIT_COPY:
976          SendMessage(g_hwndLogBox, WM_COPY, 0, 0);
977          break;
978
979       case ID_VIEW_CLEARLOG:
980          SendMessage(g_hwndLogBox, WM_SETTEXT, 0, (LPARAM) "");
981          break;
982
983       case ID_VIEW_LOGMESSAGES:
984          g_bLogMessages = !g_bLogMessages;
985          /* SaveLogSettings(); */
986          break;
987
988       case ID_VIEW_MESSAGEHIGHLIGHTING:
989          g_bHighlightMessages = !g_bHighlightMessages;
990          /* SaveLogSettings(); */
991          break;
992
993       case ID_VIEW_LIMITBUFFERSIZE:
994          g_bLimitBufferSize = !g_bLimitBufferSize;
995          /* SaveLogSettings(); */
996          break;
997
998       case ID_VIEW_ACTIVITYANIMATION:
999          g_bShowActivityAnimation = !g_bShowActivityAnimation;
1000          /* SaveLogSettings(); */
1001          break;
1002
1003 #ifdef FEATURE_TOGGLE
1004       /* by haroon - change toggle to its opposite value */
1005       case ID_TOGGLE_ENABLED:
1006          global_toggle_state = !global_toggle_state;
1007          if (global_toggle_state)
1008          {
1009             log_error(LOG_LEVEL_INFO, "Now toggled ON.");
1010          }
1011          else
1012          {
1013             log_error(LOG_LEVEL_INFO, "Now toggled OFF.");
1014          }
1015          SetIdleIcon();
1016          break;
1017 #endif /* def FEATURE_TOGGLE */
1018
1019       case ID_TOOLS_EDITCONFIG:
1020          EditFile(configfile);
1021          break;
1022
1023       case ID_TOOLS_EDITDEFAULTACTIONS:
1024          EditFile(g_default_actions_file);
1025          break;
1026
1027       case ID_TOOLS_EDITUSERACTIONS:
1028          EditFile(g_user_actions_file);
1029          break;
1030
1031       case ID_TOOLS_EDITFILTERS:
1032          EditFile(g_re_filterfile);
1033          break;
1034
1035 #ifdef FEATURE_TRUST
1036       case ID_TOOLS_EDITTRUST:
1037          EditFile(g_trustfile);
1038          break;
1039 #endif /* def FEATURE_TRUST */
1040
1041       case ID_HELP_GPL:
1042          ShellExecute(g_hwndLogFrame, "open", "LICENSE.txt", NULL, NULL, SW_SHOWNORMAL);
1043          break;
1044
1045       case ID_HELP_FAQ:
1046          ShellExecute(g_hwndLogFrame, "open", "doc\\faq\\index.html", NULL, NULL, SW_SHOWNORMAL);
1047          break;
1048
1049       case ID_HELP_MANUAL:
1050          ShellExecute(g_hwndLogFrame, "open", "doc\\user-manual\\index.html", NULL, NULL, SW_SHOWNORMAL);
1051          break;
1052
1053       case ID_HELP_STATUS:
1054          ShellExecute(g_hwndLogFrame, "open", CGI_PREFIX "show-status", NULL, NULL, SW_SHOWNORMAL);
1055          break;
1056
1057       case ID_HELP_ABOUT:
1058          MessageBox(g_hwndLogFrame, win32_blurb, "About Privoxy", MB_OK);
1059          break;
1060
1061       default:
1062          /* DO NOTHING */
1063          break;
1064    }
1065
1066 }
1067
1068
1069 /*********************************************************************
1070  *
1071  * Function    :  OnLogInitMenu
1072  *
1073  * Description :  Handler for WM_INITMENU messages.  Enable, disable,
1074  *                check, and/or uncheck menu options as apropos.
1075  *
1076  * Parameters  :
1077  *          1  :  hmenu = handle to menu to "make current"
1078  *
1079  * Returns     :  N/A
1080  *
1081  *********************************************************************/
1082 void OnLogInitMenu(HMENU hmenu)
1083 {
1084    /* Only enable editors if there is a file to edit */
1085    EnableMenuItem(hmenu, ID_TOOLS_EDITDEFAULTACTIONS, MF_BYCOMMAND | (g_default_actions_file ? MF_ENABLED : MF_GRAYED));
1086    EnableMenuItem(hmenu, ID_TOOLS_EDITUSERACTIONS, MF_BYCOMMAND | (g_user_actions_file ? MF_ENABLED : MF_GRAYED));
1087    EnableMenuItem(hmenu, ID_TOOLS_EDITFILTERS, MF_BYCOMMAND | (g_re_filterfile ? MF_ENABLED : MF_GRAYED));
1088 #ifdef FEATURE_TRUST
1089    EnableMenuItem(hmenu, ID_TOOLS_EDITTRUST, MF_BYCOMMAND | (g_trustfile ? MF_ENABLED : MF_GRAYED));
1090 #endif /* def FEATURE_TRUST */
1091
1092    /* Check/uncheck options */
1093    CheckMenuItem(hmenu, ID_VIEW_LOGMESSAGES, MF_BYCOMMAND | (g_bLogMessages ? MF_CHECKED : MF_UNCHECKED));
1094    CheckMenuItem(hmenu, ID_VIEW_MESSAGEHIGHLIGHTING, MF_BYCOMMAND | (g_bHighlightMessages ? MF_CHECKED : MF_UNCHECKED));
1095    CheckMenuItem(hmenu, ID_VIEW_LIMITBUFFERSIZE, MF_BYCOMMAND | (g_bLimitBufferSize ? MF_CHECKED : MF_UNCHECKED));
1096    CheckMenuItem(hmenu, ID_VIEW_ACTIVITYANIMATION, MF_BYCOMMAND | (g_bShowActivityAnimation ? MF_CHECKED : MF_UNCHECKED));
1097 #ifdef FEATURE_TOGGLE
1098    /* by haroon - menu item for Enable toggle on/off */
1099    CheckMenuItem(hmenu, ID_TOGGLE_ENABLED, MF_BYCOMMAND | (global_toggle_state ? MF_CHECKED : MF_UNCHECKED));
1100 #endif /* def FEATURE_TOGGLE */
1101    CheckMenuItem(hmenu, ID_TOGGLE_SHOWWINDOW, MF_BYCOMMAND | (g_bShowLogWindow ? MF_CHECKED : MF_UNCHECKED));
1102
1103 }
1104
1105
1106 /*********************************************************************
1107  *
1108  * Function    :  OnLogTimer
1109  *
1110  * Description :  Handler for WM_TIMER messages.
1111  *
1112  * Parameters  :
1113  *          1  :  nTimer = timer id (animation start/stop or clip buffer)
1114  *
1115  * Returns     :  N/A
1116  *
1117  *********************************************************************/
1118 void OnLogTimer(int nTimer)
1119 {
1120    switch (nTimer)
1121    {
1122       case TIMER_ANIM_ID:
1123          TraySetIcon(g_hwndTray, 1, g_hiconAnim[g_nAnimFrame++ % ANIM_FRAMES]);
1124          break;
1125
1126       case TIMER_ANIMSTOP_ID:
1127          g_nAnimFrame = 0;
1128          SetIdleIcon();
1129          KillTimer(g_hwndLogFrame, TIMER_ANIM_ID);
1130          KillTimer(g_hwndLogFrame, TIMER_ANIMSTOP_ID);
1131          break;
1132
1133       case TIMER_CLIPBUFFER_ID:
1134       case TIMER_CLIPBUFFER_FORCE_ID:
1135          LogClipBuffer();
1136          g_bClipPending = FALSE;
1137          KillTimer(g_hwndLogFrame, TIMER_CLIPBUFFER_ID);
1138          KillTimer(g_hwndLogFrame, TIMER_CLIPBUFFER_FORCE_ID);
1139          break;
1140
1141       default:
1142          /* DO NOTHING */
1143          break;
1144    }
1145
1146 }
1147
1148
1149 /*********************************************************************
1150  *
1151  * Function    :  SetIdleIcon
1152  *
1153  * Description :  Sets the tray icon to either idle or off
1154  *
1155  * Parameters  :  none
1156  *
1157  * Returns     :  N/A
1158  *
1159  *********************************************************************/
1160 void SetIdleIcon()
1161 {
1162 #ifdef FEATURE_TOGGLE
1163          if (!global_toggle_state)
1164          {
1165             TraySetIcon(g_hwndTray, 1, g_hiconOff);
1166             /* log_error(LOG_LEVEL_INFO, "Privoxy OFF icon selected."); */
1167          }
1168          else
1169 #endif /* def FEATURE_TOGGLE */
1170          TraySetIcon(g_hwndTray, 1, g_hiconIdle);
1171 }
1172
1173
1174 /*********************************************************************
1175  *
1176  * Function    :  LogRichEditProc
1177  *
1178  * Description :  Window subclass routine handles some events for the rich edit control.
1179  *
1180  * Parameters  :
1181  *          1  :  hwnd = window handle of the rich edit control
1182  *          2  :  uMsg = message number
1183  *          3  :  wParam = first param for this message
1184  *          4  :  lParam = next param for this message
1185  *
1186  * Returns     :  Appropriate M$ window message handler codes.
1187  *
1188  *********************************************************************/
1189 LRESULT CALLBACK LogRichEditProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
1190 {
1191    switch (uMsg)
1192    {
1193       case WM_RBUTTONUP:
1194       {
1195          POINT pt;
1196          pt.x = LOWORD(lParam);
1197          pt.y = HIWORD(lParam);
1198          ClientToScreen(hwnd, &pt);
1199          OnLogRButtonUp(wParam, pt.x, pt.y);
1200          return 0;
1201       }
1202       case WM_CHAR:
1203       {
1204          if ((GetKeyState(VK_CONTROL) != 0) && (wParam == 4)) /* ctrl+d */
1205          {
1206              OnLogCommand(ID_VIEW_CLEARLOG);
1207              return 0;
1208          }
1209       }
1210    }
1211    return CallWindowProc(g_fnLogBox, hwnd, uMsg, wParam, lParam);
1212
1213 }
1214
1215
1216 /*********************************************************************
1217  *
1218  * Function    :  LogWindowProc
1219  *
1220  * Description :  Windows call back routine handles events on the log window.
1221  *
1222  * Parameters  :
1223  *          1  :  hwnd = handle of the logging window
1224  *          2  :  uMsg = message number
1225  *          3  :  wParam = first param for this message
1226  *          4  :  lParam = next param for this message
1227  *
1228  * Returns     :  Appropriate M$ window message handler codes.
1229  *
1230  *********************************************************************/
1231 LRESULT CALLBACK LogWindowProc(HWND hwnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
1232 {
1233    switch (uMsg)
1234    {
1235       case WM_CREATE:
1236          return 0;
1237
1238       case WM_CLOSE:
1239          /* This is the end - beautiful friend - the end */
1240          DestroyWindow(g_hwndLogBox);
1241          DestroyWindow(g_hwndLogFrame);
1242          return 0;
1243
1244       case WM_DESTROY:
1245          PostQuitMessage(0);
1246          return 0;
1247
1248       case WM_SHOWWINDOW:
1249          g_bShowLogWindow = wParam;
1250       case WM_SIZE:
1251          /* Resize the logging window to fit the new frame */
1252          if (g_hwndLogBox)
1253          {
1254             RECT rc;
1255             GetClientRect(g_hwndLogFrame, &rc);
1256             SetWindowPos(g_hwndLogBox, NULL, rc.left, rc.top, rc.right - rc.left, rc.bottom - rc.top, SWP_NOZORDER);
1257          }
1258          return 0;
1259
1260       case WM_INITMENU:
1261          OnLogInitMenu((HMENU) wParam);
1262          return 0;
1263
1264       case WM_TIMER:
1265          OnLogTimer(wParam);
1266          return 0;
1267
1268       case WM_COMMAND:
1269          OnLogCommand(LOWORD(wParam));
1270          return 0;
1271
1272       case WM_SYSCOMMAND:
1273          switch (wParam)
1274          {
1275             case SC_CLOSE:
1276                if (g_bCloseHidesWindow)
1277                {
1278                   ShowLogWindow(FALSE);
1279                   return 0;
1280                }
1281                break;
1282             case SC_MINIMIZE:
1283                ShowLogWindow(FALSE);
1284                return 0;
1285          }
1286          break;
1287
1288       case WM_CHAR:
1289          if ((GetKeyState(VK_CONTROL) != 0) && (wParam == 4)) /* ctrl+d */
1290          {
1291              OnLogCommand(ID_VIEW_CLEARLOG);
1292              return 0;
1293          }
1294          break;
1295    }
1296
1297    return DefWindowProc(hwnd, uMsg, wParam, lParam);
1298
1299 }
1300
1301 #endif /* ndef _WIN_CONSOLE - entire file */
1302
1303 /*
1304   Local Variables:
1305   tab-width: 3
1306   end:
1307 */