home *** CD-ROM | disk | FTP | other *** search
/ Tricks of the Windows Gam…ming Gurus (2nd Edition) / Disc2.iso / msdn_vcb / samples / vc98 / sdk / sdktools / winnt / perfmon / init.c < prev    next >
Text File  |  1995-10-29  |  19KB  |  591 lines

  1. //==========================================================================//
  2. //                                  Includes                                //
  3. //==========================================================================//
  4. #include <string.h>     // strupr
  5. #include <stdio.h>      // for sprintf.
  6.  
  7.  
  8. #include "perfmon.h"
  9. #include "init.h"       // external declarations for this file
  10.  
  11. #include "alert.h"      // for AlertIitializeApplication
  12. #include "command.h"    // for ViewChart
  13. #include "grafdata.h"   // for QuerySaveChart
  14. #include "graph.h"      // for GraphInitializeApplication
  15. #include "legend.h"     // for LegendInitializeApplication
  16. #include "log.h"        // for LogInitializeApplication
  17. #include "intrline.h"   // for ILineInitializeApplication
  18. #include "perfdata.h"   // for PerfDataInitializeInstance
  19. #include "perfmops.h"   // for OpenFileHandler, for now
  20. #include "status.h"     // for StatusInitializeApplication
  21. #include "timeline.h"   // for TLineInitializeApplication
  22. #include "playback.h"   // for PlaybackInitializeInstance
  23. #include "registry.h"   // for Load/SaveMainWindowPlacement
  24. #include "report.h"     // for ReportInitializeApplication
  25. #include "toolbar.h"    // for ToolbarInitializeApplication
  26. #include "utils.h"
  27. #include "fileopen.h"   // for FileOpen
  28. #include "pmemory.h"    // for MemoryFree
  29.  
  30. extern   TCHAR          DefaultLangId[] ;
  31. extern   TCHAR          EnglishLangId[] ;
  32.  
  33. static   LPSTR             lpszCommandLine ;
  34.  
  35. //==========================================================================//
  36. //                                  Constants                               //
  37. //==========================================================================//
  38.  
  39.  
  40. #define szPerfmonMainClass TEXT("PerfmonMainClass")
  41.  
  42. HHOOK   lpMsgFilterProc ;
  43. DWORD FAR PASCAL MessageFilterProc (int nCode, WPARAM wParam,
  44.       LPARAM lParam) ;
  45.  
  46.  
  47. //==========================================================================//
  48. //                              Local Functions                             //
  49. //==========================================================================//
  50.  
  51.  
  52. void GetScalesFonts (void)
  53.    {
  54.    LOGFONT        lf ;
  55.  
  56.    memset (&lf, 0, sizeof (lf)) ;
  57.  
  58.    lstrcpy (lf.lfFaceName, szScalesFontFace) ;
  59.    lf.lfHeight = iScalesFontHeight ;
  60.    lf.lfWeight = FW_REGULAR ;
  61.  
  62.  
  63.    if (PRIMARYLANGID(GetUserDefaultLangID ()) == LANG_JAPANESE)
  64.      lf.lfCharSet = SHIFTJIS_CHARSET;
  65.  
  66.    hFontScales = CreateFontIndirect (&lf) ;
  67.  
  68.    if (PRIMARYLANGID(GetUserDefaultLangID ()) != LANG_JAPANESE)
  69.      lf.lfWeight = FW_BOLD ;
  70.  
  71.    hFontScalesBold = CreateFontIndirect (&lf) ;
  72.    }
  73.  
  74.  
  75. BOOL InitializeSystemValues (void)
  76. /*
  77.    Effect:        Read and store in variables the various system values,
  78.                   such as the width and height of the screen and icons,
  79.                   the width of scroll bars, etc.
  80.  
  81.    Called By:     PerfmonInitialize only.
  82.  
  83.    Returns:       Whether this function was successful in getting all
  84.                   needed system values.
  85. */
  86.    {  // InitializeSystemValues
  87.    xScreenWidth =  GetSystemMetrics (SM_CXSCREEN) ;
  88.    yScreenHeight = GetSystemMetrics (SM_CYSCREEN) ;
  89.  
  90.    xBorderWidth = GetSystemMetrics (SM_CXBORDER) ;
  91.    yBorderHeight = GetSystemMetrics (SM_CYBORDER) ;
  92.  
  93.    xScrollWidth = GetSystemMetrics (SM_CXVSCROLL) ;
  94.    yScrollHeight = GetSystemMetrics (SM_CYHSCROLL) ;
  95.  
  96.    xScrollThumbWidth = GetSystemMetrics (SM_CXHTHUMB) ;
  97.    yScrollThumbHeight = GetSystemMetrics (SM_CYVTHUMB) ;
  98.  
  99.    xDlgBorderWidth = GetSystemMetrics (SM_CXDLGFRAME) ;
  100.    yDlgBorderHeight = GetSystemMetrics (SM_CYDLGFRAME) ;
  101.  
  102.    MinimumSize = yScrollHeight +
  103.                  GetSystemMetrics (SM_CYMENU) +
  104.                  GetSystemMetrics (SM_CYCAPTION) ;
  105.  
  106.    //================================================================//
  107.    // create all the brushes and pens for performance improvement    //
  108.    //================================================================//
  109.    CreatePerfmonSystemObjects () ;
  110.    hWhitePen = CreatePen (PS_SOLID, 3, crWhite) ;
  111.  
  112.    return (TRUE) ;
  113.    }  // InitializeSystemValues
  114.  
  115.  
  116. BOOL InitializeApplication (void)
  117. /*
  118.    Effect:        Perform all initializations required for the FIRST
  119.                   instance of the Perfmon application. In particular,
  120.                   register all of Perfmon's window classes.
  121.  
  122.    Note:          There is no background brush set for the MainWindow
  123.                   class so that the main window is never erased. The
  124.                   client area of MainWindow is always covered by one
  125.                   of the view windows. If we erase it, it would just
  126.                   flicker needlessly.
  127.  
  128.    Called By:     PerfmonInitialize only.
  129.  
  130.    Returns:       Whether this function was successful in initializing.
  131. */
  132.    {  // InitializeApplication
  133.    BOOL           bSuccess ;
  134.    WNDCLASS       wc ;
  135.    TCHAR          LocalHelpFileName [ShortTextLen] ;
  136.    LPTSTR         pFileName ;
  137.  
  138.    hIcon = LoadIcon (hInstance, idIcon) ;
  139.  
  140.    //=============================//
  141.    // Register Main window class  //
  142.    //=============================//
  143.  
  144.    wc.style         = CS_DBLCLKS | CS_BYTEALIGNCLIENT;
  145.    wc.lpfnWndProc   = (WNDPROC) MainWndProc;
  146.    wc.hInstance     = hInstance;
  147.    wc.cbClsExtra    = 0 ;
  148.    wc.cbWndExtra    = 0;
  149.    wc.hIcon         = hIcon ;
  150.    wc.hCursor       = LoadCursor(NULL, IDI_APPLICATION);
  151.    wc.hbrBackground = NULL ;                             // see note above
  152.    wc.lpszMenuName  = idMenuChart ;
  153.    wc.lpszClassName = szPerfmonMainClass ;
  154.  
  155.    bSuccess = RegisterClass (&wc) ;
  156.  
  157.    //=============================//
  158.    // Register Abstract "Systems" //
  159.    //=============================//
  160.    hbLightGray = GetStockObject (LTGRAY_BRUSH) ;
  161.  
  162.    if (bSuccess)
  163.       bSuccess = StatusInitializeApplication () ;
  164.  
  165.    if (bSuccess)
  166.       bSuccess = GraphInitializeApplication () ;
  167.  
  168. #ifdef ADVANCED_PERFMON
  169.    if (bSuccess)
  170.       bSuccess = LogInitializeApplication () ;
  171.  
  172.    if (bSuccess)
  173.       bSuccess = AlertInitializeApplication () ;
  174.  
  175.    if (bSuccess)
  176.       bSuccess = ReportInitializeApplication () ;
  177.  
  178.    if (bSuccess)
  179.       bSuccess = ILineInitializeApplication () ;
  180.  
  181.    if (bSuccess)
  182.       bSuccess = TLineInitializeApplication () ;
  183. #endif
  184.  
  185.    // setup messagehook to handle F1 as help
  186.    lpMsgFilterProc = SetWindowsHookEx (WH_MSGFILTER,
  187.           (HOOKPROC) MessageFilterProc,
  188.           hInstance,
  189.           GetCurrentThreadId()) ;
  190.  
  191.    // get the help file full path name
  192.    LoadString (hInstance, IDS_HELPFILE_NAME,
  193.       (LPTSTR)LocalHelpFileName, ShortTextLen-1);
  194.  
  195.  
  196.    if (LocalHelpFileName[0])
  197.       {
  198.       pszHelpFile = (LPTSTR) MemoryAllocate (FilePathLen * sizeof (TCHAR)) ;
  199.       SearchPath (NULL, LocalHelpFileName, NULL,
  200.             FilePathLen - 1, pszHelpFile, &pFileName) ;
  201.       }
  202.    else
  203.       {
  204.       // no help file
  205.       pszHelpFile = (LPTSTR) MemoryAllocate (sizeof (TCHAR)) ;
  206.       *pszHelpFile = TEXT('\0') ;
  207.       }
  208.  
  209.    return (bSuccess) ;
  210.    }  // InitializeApplication
  211.  
  212.  
  213.  
  214. BOOL InitializeInstance (int nCmdShow, LPCSTR lpszCmdLine)
  215. /*
  216.    Effect:        Perform all initializations required for EACH instance
  217.                   of the Perfmon application. In particular, create all
  218.                   of Perfmon's initial windows, and perform any other
  219.                   initializations except registering classes (done in
  220.                   InitializeApplication).
  221.  
  222.    Called By:     PerfmonInitialize only.
  223.  
  224.    Note:          This function has multiple return points.
  225.  
  226.    Returns:       Whether this function was successful in initalizing.
  227. */
  228.    {  // InitializeInstance
  229.    DWORD          ComputerNameLength;
  230.    TCHAR          szApplication [WindowCaptionLen] ;
  231.  
  232.  
  233.    //=============================//
  234.    // Set Priority high           //
  235.    //=============================//
  236.  
  237.    SetPriorityClass(GetCurrentProcess(), HIGH_PRIORITY_CLASS) ;
  238.    SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_HIGHEST) ;
  239.  
  240.    //=============================//
  241.    // Load Resources              //
  242.    //=============================//
  243.  
  244.    GetScalesFonts () ;
  245.  
  246.    hMenuChart = LoadMenu (hInstance, idMenuChart) ;
  247.  
  248. #ifdef ADVANCED_PERFMON
  249.    hMenuAlert = LoadMenu (hInstance, idMenuAlert) ;
  250.    hMenuLog = LoadMenu (hInstance, idMenuLog) ;
  251.    hMenuReport = LoadMenu (hInstance, idMenuReport) ;
  252. #endif
  253.  
  254.    hAccelerators = LoadAccelerators (hInstance, idAccelerators) ;
  255.  
  256.  
  257.    //=============================//
  258.    // Initialize Systems          //
  259.    //=============================//
  260.  
  261.    iLanguage = GetUserDefaultLangID() ;
  262.    iEnglishLanguage = MAKELANGID (LANG_ENGLISH, LANG_NEUTRAL) ;
  263. //   iEnglishLanguage = MAKELANGID (iLanguage & 0x0ff, LANG_NEUTRAL) ;
  264.    TSPRINTF (DefaultLangId, TEXT("%03x"), iLanguage) ;
  265.    TSPRINTF (EnglishLangId, TEXT("%03x"), iEnglishLanguage) ;
  266.  
  267.    // GetComputerName returns the name without the "\\" prefix. We add
  268.    // the prefix before even calling the routine. This is so that all our
  269.    // computer names have the prefix and are therefore compatible with
  270.    // I_SetSystemFocus (see perfmops.c).
  271.  
  272.    ComputerNameLength = MAX_COMPUTERNAME_LENGTH + 1;
  273.    lstrcpy (LocalComputerName, szComputerPrefix) ;
  274.    GetComputerName (LocalComputerName + lstrlen (szComputerPrefix), 
  275.                     &ComputerNameLength);
  276.  
  277.    PlaybackInitializeInstance () ;
  278.    PerfDataInitializeInstance () ;
  279.  
  280.     //Copy command line into buffer for modification
  281.     lpszCommandLine = (LPSTR)MemoryAllocate (strlen (lpszCmdLine) + sizeof(CHAR)) ;
  282.    if(lpszCommandLine)
  283.        strcpy(lpszCommandLine, lpszCmdLine) ;
  284.     else
  285.         return (FALSE) ;
  286.  
  287.  
  288.    StringLoad (IDS_APPNAME, szApplication) ;
  289.  
  290.     //Insure CmdLineComputerName starts out NULL
  291.     CmdLineComputerName[0] = TEXT('\0') ;
  292.  
  293.     //Check to see if there is a computer name specified on the command
  294.     //line (indicated by /c, or /C).  If there is, get it and
  295.     //null out the command line string so that it is not mistaken for 
  296.     //startup file.  This assumes that specifying a computer and a startup
  297.     //file on the command line are mutually exclusive.  If the /c option
  298.     //is on the command line, anything else on the command line is discarded.
  299.     if (!strempty (lpszCommandLine)) {
  300.         LPSTR                lpszNewCL ;
  301.         
  302.         //Preserve initial command line pointer position
  303.         lpszNewCL = (LPSTR)lpszCommandLine ;
  304.         while (*lpszNewCL != '\0' && *lpszCommandLine) {
  305.             if (*lpszNewCL    == '/' || *lpszNewCL    == '-') {
  306.                 lpszNewCL++ ;
  307.                 if (*lpszNewCL == 'c' || *lpszNewCL == 'C') {
  308.                     int i = 0;
  309.                     
  310.                     lpszNewCL++ ;
  311.                     //ignore leading backslashes * spaces
  312.                     while (*lpszNewCL == '\\' || *lpszNewCL == ' ')
  313.                         lpszNewCL++ ;
  314.                     
  315.                     //Terminate at first blank space if there is one.
  316.                     //We don't allow anything else on the command line
  317.                     //if a computer name is specified.
  318.                     while (lpszNewCL[i] != ' ' && lpszNewCL[i] != '\0')
  319.                         i++ ;
  320.                     lpszNewCL[i] = '\0' ;
  321.  
  322.                     if ((*lpszNewCL != '\0') && (strlen(lpszNewCL) <= MAX_COMPUTERNAME_LENGTH)) {
  323.                         int nSizePrefix ;
  324.                     
  325.                         nSizePrefix = lstrlen (szComputerPrefix) ;
  326.                         lstrcpy( CmdLineComputerName, szComputerPrefix ) ;
  327.                         MultiByteToWideChar (CP_ACP,
  328.                                                     MB_PRECOMPOSED,
  329.                                                     lpszNewCL,
  330.                                                     -1,
  331.                                                     CmdLineComputerName + nSizePrefix,
  332.                                                     sizeof(CmdLineComputerName) - nSizePrefix) ;                    
  333.                         //prevent lpszCommandLine from being used as input file & stop while loop
  334.                         *lpszCommandLine = '\0' ;
  335.                     } else {
  336.                         LPTSTR    lpszErrMsg ;
  337.                         TCHAR        lpszFormat[80] ;
  338.  
  339.                         LoadString(hInstance, ERR_BADCOMPUTERNAME, lpszFormat, sizeof(lpszFormat)/sizeof(TCHAR)) ;
  340.                         lpszErrMsg = (LPTSTR)MemoryAllocate ((strlen (lpszNewCL) + 1)*sizeof(TCHAR) + sizeof(lpszFormat)) ;
  341.                         //If memory allocation failed, don't display error message
  342.                        if (lpszErrMsg) {
  343.                             //lpszFormat uses %S specifier so lpszNewCL can be ansi string
  344.                             wsprintf (lpszErrMsg, lpszFormat, lpszNewCL) ;
  345.                             MessageBox (NULL, lpszErrMsg, szApplication, MB_OK | MB_ICONSTOP | MB_TASKMODAL) ; 
  346.                         }
  347.  
  348.                         //prevent lpszCommandLine from being used as input file & stop while loop
  349.                         *lpszCommandLine = '\0' ;
  350.                     }
  351.                 }
  352.             }
  353.             lpszNewCL++ ;
  354.         }
  355.     }
  356.  
  357.    //=============================//
  358.    // Create Window               //
  359.    //=============================//
  360.  
  361.  
  362.    hWndMain = CreateWindow (szPerfmonMainClass,
  363.                             szApplication,
  364.                                   WS_OVERLAPPEDWINDOW | WS_BORDER,
  365.                               CW_USEDEFAULT, CW_USEDEFAULT, 
  366.                               CW_USEDEFAULT, CW_USEDEFAULT, 
  367.                               NULL,
  368.                             NULL,
  369.                             NULL,
  370.                             NULL);
  371.  
  372.    if (!hWndMain)
  373.       return (FALSE) ;
  374.  
  375.    ViewChart (hWndMain) ;
  376.  
  377.    LoadMainWindowPlacement (hWndMain) ;
  378.  
  379.    //=============================//
  380.    // Setup for event logging     //
  381.    //=============================//
  382.    hEventLog = RegisterEventSource (
  383.       (LPTSTR)NULL,            // Use Local Machine
  384.       TEXT("PerfMon"));        // event log app name to find in registry
  385.  
  386.    return (TRUE) ;
  387.    }  // InitializeInstance
  388.  
  389.  
  390. //==========================================================================//
  391. //                             Exported Functions                           //
  392. //==========================================================================//
  393.  
  394.  
  395. BOOL PerfmonInitialize (HINSTANCE hCurrentInstance,
  396.                         HINSTANCE hPrevInstance,
  397.                         LPCSTR lpszCmdLine,
  398.                         int nCmdShow)
  399. /*
  400.    Effect:        Performa all initializations required when Perfmon is
  401.                   started. In particular, initialize all "systems", register
  402.                   all window classes, create needed windows, read in and
  403.                   process font and Perfmon lists.
  404.  
  405.    Called By:     WinMain only, at the start of the application.
  406.  
  407.    Assert:        There are no other instances of Perfmon currently
  408.                   executing.
  409.  
  410.    Returns:       Whether initialization was successful. If this function
  411.                   returns FALSE, Perfmon should exit immediately.
  412.  
  413.    Internals:     The bSuccess variable is used to conditionalize each
  414.                   successive initialization step.
  415. */
  416.    {  // PerfmonInitialize
  417.    BOOL           bSuccess ;
  418.    TCHAR          szFilePath [FilePathLen + 1] ;
  419.    LPTSTR         pFileNameStart ;
  420.    HANDLE         hFindFile ;
  421.    WIN32_FIND_DATA FindFileInfo ;
  422.    CHAR           QuoteChar ;
  423.    LPSTR          pCmdLine ;
  424.    LPSTR          lpszCmdLineStart = NULL ;
  425.    int            NameOffset ;
  426.    int            StringLen ;
  427.  
  428.  
  429.    hInstance = hCurrentInstance ;
  430.    bSuccess = InitializeSystemValues () ;
  431.  
  432.    if (bSuccess && !hPrevInstance)
  433.       bSuccess = InitializeApplication () ;
  434.  
  435.    if (bSuccess)
  436.       bSuccess = InitializeInstance (nCmdShow, lpszCmdLine) ;
  437.  
  438.    GetDateTimeFormats() ;
  439.  
  440.    lpszCmdLineStart = lpszCommandLine ;
  441.  
  442.  
  443.    if (bSuccess)
  444.       {
  445.  
  446.       if (strempty (lpszCommandLine))
  447.          StringLoad (IDS_DEFAULTPATH, szFilePath) ;
  448.       else
  449.          {
  450.          // check for single or double quote
  451.          QuoteChar = *lpszCommandLine ;
  452.          if (QuoteChar == '\'' || QuoteChar == '\"')
  453.             {
  454.             lpszCommandLine++ ;
  455.  
  456.             // remove the matching QuoteChar if found
  457.             pCmdLine = (LPSTR) lpszCommandLine ;
  458.             while (*pCmdLine != '\0')
  459.                {
  460.                if (*pCmdLine == QuoteChar)
  461.                   {
  462.                   *pCmdLine = '\0' ;
  463.                   break ;
  464.                   }
  465.                else
  466.                   {
  467.                   pCmdLine++ ;
  468.                   }
  469.                }
  470.             }
  471.  
  472.          // convert the LPSTR to LPTSTR
  473.  
  474.          StringLen = strlen(lpszCommandLine) + 1 ;
  475.          if (StringLen > sizeof(szFilePath))
  476.             {
  477.             StringLen = sizeof (szFilePath) - sizeof (TEXT('\0')) ;
  478.             }
  479.          szFilePath[FilePathLen] = TEXT('\0') ;
  480.  
  481.          mbstowcs (szFilePath, lpszCommandLine, StringLen) ;
  482.  
  483.          if (!(QuoteChar == '\'' || QuoteChar == '\"'))
  484.             {
  485.             // if there is no quote, then looking for trailing space
  486.             LPTSTR   lpTempStr = szFilePath ;
  487.  
  488.             while (*lpTempStr != TEXT('\0'))
  489.                {
  490.                if (*lpTempStr == TEXT(' '))
  491.                   {
  492.                   *lpTempStr = TEXT('\0') ;
  493.                   break ;
  494.                   }
  495.                lpTempStr++ ;
  496.                }
  497.             }
  498.  
  499.          pFileNameStart = ExtractFileName (szFilePath) ;
  500.          NameOffset = pFileNameStart - szFilePath ;
  501.  
  502.          // convert short filename to long NTFS filename if necessary
  503.          hFindFile = FindFirstFile (szFilePath, &FindFileInfo) ;
  504.          if (hFindFile && hFindFile != INVALID_HANDLE_VALUE)
  505.             {
  506.             // append the file name back to the path name
  507.             lstrcpy (&szFilePath[NameOffset], FindFileInfo.cFileName) ;
  508.             FindClose (hFindFile) ;
  509.             }
  510.          }
  511.       
  512. //      OpenFileHandler (hWndMain, szFilePath) ;
  513.       FileOpen (hWndMain, (int)0, (LPTSTR)szFilePath) ;
  514.       PrepareMenu (GetMenu (hWndMain));
  515.       }
  516.  
  517.    if (lpszCmdLineStart)
  518.       {
  519.       MemoryFree (lpszCmdLineStart) ;
  520.       lpszCommandLine = NULL ;
  521.       }
  522.  
  523.    return (bSuccess) ;
  524.    }  // PerfmonInitialize
  525.  
  526.  
  527.  
  528. void PerfmonClose (HWND hWndMain)
  529.    {
  530.    // close the log file for now.
  531.    // need to query the user later..!!
  532. #if 0
  533.    if (LogCollecting (hWndLog))
  534.       {
  535.       PLOG pLog = LogData (hWndLog) ;
  536.       
  537.       if (pLog)
  538.          {
  539.          CloseLog (hWndLog, pLog) ;
  540.          }
  541.       }
  542. #endif
  543.       
  544.  
  545.    // reset all views - will free all systems as well
  546.    ResetGraphView (hWndGraph) ;
  547.    ResetAlertView (hWndAlert) ;
  548.    ResetLogView (hWndLog) ;
  549.    ResetReportView (hWndReport) ;
  550.  
  551.    // close the local machine
  552.    if (bCloseLocalMachine)
  553.       {
  554.       RegCloseKey (HKEY_PERFORMANCE_DATA) ;
  555.       }
  556.  
  557.  
  558.    // free all the filenames
  559.    if (pChartFullFileName)
  560.       {
  561.       MemoryFree (pChartFullFileName) ;
  562.       pChartFullFileName = NULL ;
  563.       }
  564.    if (pAlertFullFileName)
  565.       {
  566.       MemoryFree (pAlertFullFileName) ;
  567.       pAlertFullFileName = NULL ;
  568.       }
  569.    if (pLogFullFileName)
  570.       {
  571.       MemoryFree (pLogFullFileName) ;
  572.       pLogFullFileName = NULL ;
  573.       }
  574.    if (pReportFullFileName)
  575.       {
  576.       MemoryFree (pReportFullFileName) ;
  577.       pReportFullFileName = NULL ;
  578.       }
  579.  
  580.    // free all the GDI resources
  581.    DeletePen (hWhitePen) ;
  582.    DeletePerfmonSystemObjects () ;
  583.  
  584.    // close event log
  585.    DeregisterEventSource (hEventLog);
  586.  
  587.    SaveMainWindowPlacement (hWndMain) ;
  588.    DestroyWindow (hWndMain) ;
  589.    }  // PerfmonClose
  590. 
  591.