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