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