Esempio n. 1
0
// Define my frame constructor
MyFrame::MyFrame(wxFrame *frame, const wxString& title)
       : wxFrame(frame, wxID_ANY, title, wxDefaultPosition, wxSize(400, 300))
{
#if wxUSE_STATUSBAR
    CreateStatusBar();
#endif // wxUSE_STATUSBAR

    // Give it an icon
    SetIcon(wxICON(sample));

    // Make a menubar
    wxMenu *file_menu = new wxMenu;

    file_menu->Append(wxID_EXIT, _T("&Quit\tCtrl-Q"));

    wxMenuBar *menu_bar = new wxMenuBar;

    menu_bar->Append(file_menu, _T("&File"));

    // Associate the menu bar with the frame
    SetMenuBar(menu_bar);

    // set a dialog background
    SetBackgroundColour(wxSystemSettings::GetColour(wxSYS_COLOUR_BTNFACE));

    // add the controls to the frame
    wxBoxSizer *item0 = new wxBoxSizer( wxVERTICAL );

    wxBoxSizer *item1 = new wxBoxSizer( wxHORIZONTAL );

    wxFlexGridSizer *item2 = new wxFlexGridSizer( 2, 0, 0 );
    item2->AddGrowableCol( 1 );

    wxButton *item3 = new wxButton( this, ID_START, wxT("Start Server"), wxDefaultPosition, wxDefaultSize, 0 );
    item2->Add( item3, 0, wxGROW|wxALIGN_CENTER_VERTICAL|wxALL, 5 );

    wxString strs4[] =
    {
        IPC_SERVICE, _T("...")
    };
    wxChoice *item4 = new wxChoice( this, ID_SERVERNAME, wxDefaultPosition, wxSize(100,-1), 2, strs4, 0 );
    item2->Add( item4, 0, wxGROW|wxALIGN_CENTER_VERTICAL|wxALL, 5 );

    wxButton *item5 = new wxButton( this, ID_DISCONNECT, wxT("Disconnect Client"), wxDefaultPosition, wxDefaultSize, 0 );
    item2->Add( item5, 0, wxGROW|wxALIGN_CENTER_VERTICAL|wxALL, 5 );

    item2->Add( 20, 20, 0, wxALIGN_CENTER|wxALL, 5 );

    wxButton *item6 = new wxButton( this, ID_ADVISE, wxT("Advise"), wxDefaultPosition, wxDefaultSize, 0 );
    item2->Add( item6, 0, wxGROW|wxALIGN_CENTER_VERTICAL|wxALL, 5 );

    item2->Add( 20, 20, 0, wxALIGN_CENTER|wxALL, 5 );

    item1->Add( item2, 1, wxALIGN_CENTER|wxALL, 5 );

    item0->Add( item1, 0, wxGROW|wxALIGN_CENTER_VERTICAL|wxALL, 5 );

    wxStaticBox *item8 = new wxStaticBox( this, -1, wxT("Server log") );
    wxStaticBoxSizer *item7 = new wxStaticBoxSizer( item8, wxVERTICAL );

    wxTextCtrl *item9 = new wxTextCtrl( this, ID_LOG, wxT(""), wxDefaultPosition, wxSize(500,140), wxTE_MULTILINE );
    item7->Add( item9, 1, wxGROW|wxALIGN_CENTER_VERTICAL|wxALL, 5 );

    item0->Add( item7, 0, wxGROW|wxALIGN_CENTER_VERTICAL|wxALL, 5 );

    SetSizer( item0 );
    item0->SetSizeHints( this );

    // status
    m_server = NULL;
    GetServername()->SetSelection(0);
    wxLogTextCtrl *logWindow = new wxLogTextCtrl(GetLog());
    delete wxLog::SetActiveTarget(logWindow);
    wxLogMessage(_T("Click on Start to start the server"));
    Enable();
}
Esempio n. 2
0
int grib_pi::Init(void)
{
      AddLocaleCatalog( _T("opencpn-grib_pi") );

      // Set some default private member parameters
      m_CtrlBarxy = wxPoint( 0 ,0 );
      m_CursorDataxy = wxPoint( 0, 0 );

      m_pGribCtrlBar = NULL;
      m_pGRIBOverlayFactory = NULL;

      ::wxDisplaySize(&m_display_width, &m_display_height);

      m_DialogStyleChanged = false;

      //    Get a pointer to the opencpn configuration object
      m_pconfig = GetOCPNConfigObject();

      //    And load the configuration items
      LoadConfig();

      // Get a pointer to the opencpn display canvas, to use as a parent for the GRIB dialog
      m_parent_window = GetOCPNCanvasWindow();

//      int m_height = GetChartbarHeight();
      //    This PlugIn needs a CtrlBar icon, so request its insertion if enabled locally
	  if (m_bGRIBShowIcon) {
		  wxString shareLocn = *GetpSharedDataLocation() +
			  _T("plugins") + wxFileName::GetPathSeparator() +
			  _T("grib_pi") + wxFileName::GetPathSeparator()
			  + _T("data") + wxFileName::GetPathSeparator();

		  wxString normalIcon = shareLocn + _T("grib.svg");
		  wxString toggledIcon = shareLocn + _T("grib_toggled.svg");
		  wxString rolloverIcon = shareLocn + _T("grib_rollover.svg");

		  //  For journeyman styles, we prefer the built-in raster icons which match the rest of the toolbar.
		  if (GetActiveStyleName().Lower() != _T("traditional")){
			  normalIcon = _T("");
			  toggledIcon = _T("");
			  rolloverIcon = _T("");
		  }

		  wxLogMessage(normalIcon);
		  m_leftclick_tool_id = InsertPlugInToolSVG(_T(""), normalIcon, rolloverIcon, toggledIcon, wxITEM_CHECK,
			  _("Grib"), _T(""), NULL, GRIB_TOOL_POSITION, 0, this);
	  }

      if( !QualifyCtrlBarPosition( m_CtrlBarxy, m_CtrlBar_Sizexy ) ) {
          m_CtrlBarxy = wxPoint( 20, 60 );   //reset to the default position
          m_CursorDataxy = wxPoint( 20, 170 );
      }

      return (WANTS_OVERLAY_CALLBACK |
              WANTS_OPENGL_OVERLAY_CALLBACK |
              WANTS_CURSOR_LATLON       |
              WANTS_TOOLBAR_CALLBACK    |
              INSTALLS_TOOLBAR_TOOL     |
              WANTS_CONFIG              |
              WANTS_PREFERENCES         |
              WANTS_PLUGIN_MESSAGING    |
              WANTS_ONPAINT_VIEWPORT    |
              WANTS_MOUSE_EVENTS
            );
}
void CDVAPNodeTRXThread::receiveNetwork()
{
    if (m_protocolHandler == NULL)
        return;

    NETWORK_TYPE type;

    for (;;) {
        type = m_protocolHandler->read();

        // Get the data from the network
        if (type == NETWORK_NONE) {					// Nothing received
            break;
        } else if (type == NETWORK_HEADER) {		// A header
            CHeaderData* header = m_protocolHandler->readHeader();
            if (header != NULL) {
                ::memcpy(m_lastData, NULL_FRAME_DATA_BYTES, DV_FRAME_LENGTH_BYTES);

                processNetworkHeader(header);

                m_headerTime.Start();
                m_packetTime.Start();
                m_packetCount   = 0U;
                m_packetSilence = 0U;
            }
        } else if (type == NETWORK_DATA) {			// AMBE data and slow data
            unsigned char data[2U * DV_FRAME_MAX_LENGTH_BYTES];
            ::memset(data, 0x00U, 2U * DV_FRAME_MAX_LENGTH_BYTES);

            unsigned char seqNo;
            unsigned int length = m_protocolHandler->readData(data, DV_FRAME_MAX_LENGTH_BYTES, seqNo);
            if (length != 0U) {
                ::memcpy(m_lastData, data, length);
                m_packetCount += processNetworkFrame(data, length, seqNo);
                m_watchdogTimer.reset();
            }
        } else if (type == NETWORK_TEXT) {			// Slow data text for the Ack
            m_protocolHandler->readText(m_ackText, m_linkStatus, m_reflector);
            m_linkEncoder.setTextData(m_ackText);
            wxLogMessage(wxT("Slow data set to \"%s\""), m_ackText.c_str());
        } else if (type == NETWORK_STATUS1) {			// Slow data text for status 1, unused
            m_protocolHandler->readStatus1();
        } else if (type == NETWORK_STATUS2) {			// Slow data text for status 2, unused
            m_protocolHandler->readStatus2();
        } else if (type == NETWORK_STATUS3) {			// Slow data text for status 3, unused
            m_protocolHandler->readStatus3();
        } else if (type == NETWORK_STATUS4) {			// Slow data text for status 4, unused
            m_protocolHandler->readStatus4();
        } else if (type == NETWORK_STATUS5) {			// Slow data text for status 5, unused
            m_protocolHandler->readStatus5();
        }
    }

    // Have we missed any data frames?
    if (m_state == DSRS_NETWORK && m_packetTime.Time() > 200L) {
        unsigned int packetsNeeded = m_headerTime.Time() / DSTAR_FRAME_TIME_MS;

        // wxLogMessage(wxT("Time: %u ms, need %u packets and received %u packets"), ms - m_headerMS, packetsNeeded, m_packetCount);

        if (packetsNeeded > m_packetCount) {
            unsigned int count = packetsNeeded - m_packetCount;

            if (count > 5U) {
                count -= 2U;

                // wxLogMessage(wxT("Inserting %u silence packets into the network data stream"), count);

                // Create silence frames
                for (unsigned int i = 0U; i < count; i++) {
                    unsigned char data[DV_FRAME_LENGTH_BYTES];
                    ::memcpy(data, NULL_FRAME_DATA_BYTES, DV_FRAME_LENGTH_BYTES);
                    m_packetCount += processNetworkFrame(data, DV_FRAME_LENGTH_BYTES, m_networkSeqNo);
                    m_packetSilence++;
                }
            }
        }

        m_packetTime.Start();
    }
}
Esempio n. 4
0
/// Make wxPdfDocument font metrics file based on UFM file
bool
MakeFont::MakeFontUFM(const wxString& fontFileName,
                      const wxString& ufmFileName,
                      const wxString& type,
                      const wxString& volt)
{
  bool hasVolt = !volt.IsEmpty();
  int paBase = 0xe000;
  bool cff = false;
  GlyphList glyphList(CompareGlyphListEntries);
  static size_t CC2GNSIZE = 131072; // 2*64kB
  wxFileName fileName(ufmFileName);
  bool embeddingAllowed = false;
  bool subsettingAllowed = false;
  int cffOffset = -1;
  int cffLength = 0;
  if (fontFileName.Length() > 0)
  {
    CheckTTF(fontFileName, embeddingAllowed, subsettingAllowed, cffOffset, cffLength);
    cff = cffOffset > 0;
  }
  else
  {
    cff = (type == wxT("OpenType"));
  }

  wxPdfFontData* ufmFont;
  if (cff)
  {
    ufmFont = new wxPdfFontDataOpenTypeUnicode();
  }
  else
  {
    ufmFont = new wxPdfFontDataTrueTypeUnicode();
  }

  // Initialize font description
  wxPdfFontDescription fd;
  fd.SetAscent(1000);
  fd.SetDescent(-200);
  fd.SetItalicAngle(0);
  fd.SetStemV(70);
  fd.SetMissingWidth(600);
  bool hasCapHeight = false;
  bool hasXCapHeight = false;
  bool hasXHeight = false;
  bool hasFontBBox = false;
  bool hasStemV = false;
  bool hasMissingWidth = false;
  int flags = 0;

  wxFileInputStream ufmFile(ufmFileName);
  if (!ufmFile.Ok())
  {
    wxLogMessage(wxT("Error: Unable to read UFM file '") + ufmFileName + wxT("'."));
    return false;
  }
  wxTextInputStream text(ufmFile);

  // Prepare empty CIDToGIDMap
  unsigned char* cc2gn = new unsigned char[131072];
  size_t j;
  for (j = 0; j < CC2GNSIZE; j++)
  {
    cc2gn[j] = '\0';
  }
  
  // Read the UFM font metric file
  wxPdfGlyphWidthMap* widths = new wxPdfGlyphWidthMap();
  wxPdfChar2GlyphMap* glyphs = new wxPdfChar2GlyphMap();

  wxString line;
  wxString charcode, glyphname;
  wxString code, param, dummy, glyph;
  wxString token, tokenBoxHeight;
  long nParam, width, glyphNumber, boxHeight;
  wxString weight;
  while (!ufmFile.Eof())
  {
    line = text.ReadLine();
    line.Trim();

    wxStringTokenizer tkz(line, wxT(" "));
    int count = (int) tkz.CountTokens();
    if (count < 2) continue;
    code  = tkz.GetNextToken(); // 0
    param = tkz.GetNextToken(); // 1
    if (code == wxT("U"))
    {
      long cc;
      param.ToLong(&cc); // Character code
      width = -1;
      glyphNumber = 0;
      boxHeight = 0;
      tokenBoxHeight = wxEmptyString;
      dummy = tkz.GetNextToken(); // Semicolon
      while (tkz.HasMoreTokens())
      {
        token = tkz.GetNextToken();
        if (token == wxT("WX")) // Character width
        {
          param = tkz.GetNextToken(); // Width
          param.ToLong(&width);
          dummy = tkz.GetNextToken(); // Semicolon
        }
        else if (token == wxT("N")) // Glyph name
        {
          glyphname = tkz.GetNextToken(); // Glyph name
          dummy = tkz.GetNextToken(); // Semicolon
        }
        else if (token == wxT("G")) // Glyph number
        {
          param = tkz.GetNextToken(); // Number
          param.ToLong(&glyphNumber);
          dummy = tkz.GetNextToken(); // Semicolon
        }
        else if (token == wxT("B")) // Character bounding box
        {
          dummy = tkz.GetNextToken(); // x left
          dummy = tkz.GetNextToken(); // y bottom
          dummy = tkz.GetNextToken(); // x right
          tokenBoxHeight = tkz.GetNextToken(); // y top
          tokenBoxHeight.ToLong(&boxHeight);
          dummy = tkz.GetNextToken(); // Semicolon
        }
        else
        {
          while (tkz.HasMoreTokens() && tkz.GetNextToken() != wxT(";"));
        }
      }
      if (cc != -1 || (hasVolt && glyphNumber > 0))
      {
        if (!hasCapHeight && !hasXCapHeight && cc == 'X' && tokenBoxHeight != wxEmptyString)
        {
          hasXCapHeight = true;
          fd.SetCapHeight(boxHeight);
        }
        if (!hasXHeight && cc == 'x' && tokenBoxHeight != wxEmptyString)
        {
          hasXHeight = true;
          fd.SetXHeight(boxHeight);
        }

        if (cc == -1)
        {
          cc = paBase++;
        }
        (*widths)[cc] = width;
        (*glyphs)[cc] = glyphNumber;
        // Set GID
        if (cc >= 0 && cc < 0xFFFF)
        {
          cc2gn[2*cc]   = (glyphNumber >> 8) & 0xFF;
          cc2gn[2*cc+1] =  glyphNumber       & 0xFF;
        }
        if (cff)
        {
          GlyphListEntry* glEntry = new GlyphListEntry();
          glEntry->m_gid = glyphNumber;
          glEntry->m_uid = cc;
          glyphList.Add(glEntry);
        }
      }
      if (!hasMissingWidth && glyphname == wxT(".notdef"))
      {
        hasMissingWidth = true;
        fd.SetMissingWidth(width);
      }
    }
Esempio n. 5
0
/// Make wxPdfDocument font metrics file based on AFM file
bool
MakeFont::MakeFontAFM(const wxString& fontFileName, const wxString& afmFileName,
                      const wxString& encoding, const wxString& type, const wxString& patch)
{
  bool valid = false;
  wxString fontType = type;
  wxFileName fileName(fontFileName);
  // Find font type
  if (fontFileName.Length() > 0)
  {
    wxString ext = fileName.GetExt();
    if (ext == wxT("ttf"))
    {
      fontType = wxT("TrueType");
    }
    else if (ext == wxT("pfb"))
    {
      fontType = wxT("Type1");
    }
    else
    {
      wxLogMessage(wxT("Warning: Unrecognized font file extension (") + ext + wxT("), ") + fontType + wxT(" font assumed."));
    }
  }

  bool embeddingAllowed = true;
  bool subsettingAllowed = true;
  if (fontFileName.Length() > 0)
  {
    int cffOffset, cffLength;
    if (fontType == wxT("TrueType"))
    {
      CheckTTF(fontFileName, embeddingAllowed, subsettingAllowed, cffOffset, cffLength);
    }
  }

  wxPdfFontData* afmFont;
  if (fontType == wxT("TrueType"))
  {
    afmFont = new wxPdfFontDataTrueType();
  }
  else
  {
    afmFont = new wxPdfFontDataType1();
  }
  // Initialize font description
  wxPdfFontDescription fd;
  fd.SetAscent(1000);
  fd.SetDescent(-200);
  fd.SetItalicAngle(0);
  fd.SetStemV(70);
  fd.SetMissingWidth(600);
  fd.SetUnderlinePosition(-100);
  fd.SetUnderlineThickness(50);
  
  bool hasCapHeight = false;
  bool hasXCapHeight = false;
  bool hasXHeight = false;
  bool hasFontBBox = false;
  bool hasStemV = false;
  bool hasMissingWidth = false;
  int flags = 0;

  CTGMap cc2gn;
  CTGMap cc2gnPatch;
  if (encoding.Length() > 0)
  {
    afmFont->SetEncoding(encoding);
    valid = ReadMap(encoding, cc2gn);
    if (!valid)
    {
      delete afmFont;
      return false;
    }
    if (patch.Length() > 0)
    {
      valid = ReadMap(patch, cc2gnPatch);
      if (valid)
      {
        CTGMap::iterator patchIter;
        for (patchIter = cc2gnPatch.begin(); patchIter != cc2gnPatch.end(); patchIter++)
        {
          cc2gn[patchIter->first] = patchIter->second;
        }
      }
      else
      {
        wxLogMessage(wxT("Warning: Unable to read patch file '") + patch + wxT("'."));
      }
    }
  }

  // Read a font metric file
  wxFileInputStream afmFile(afmFileName);
  if (!afmFile.Ok())
  {
    wxLogMessage(wxT("Error: Unable to read AFM file '") + afmFileName + wxT("'."));
    delete afmFont;
    return false;
  }
  wxTextInputStream text(afmFile);

  FixGlyphMap fix;

  fix[wxT("Edot")] = wxT("Edotaccent");
  fix[wxT("edot")] = wxT("edotaccent");
  fix[wxT("Idot")] = wxT("Idotaccent");
  fix[wxT("Zdot")] = wxT("Zdotaccent");
  fix[wxT("zdot")] = wxT("zdotaccent");
  fix[wxT("Odblacute")] = wxT("Ohungarumlaut");
  fix[wxT("odblacute")] = wxT("ohungarumlaut");
  fix[wxT("Udblacute")] = wxT("Uhungarumlaut");
  fix[wxT("udblacute")] = wxT("uhungarumlaut");
  fix[wxT("Gcedilla")] = wxT("Gcommaaccent");
  fix[wxT("gcedilla")] = wxT("gcommaaccent");
  fix[wxT("Kcedilla")] = wxT("Kcommaaccent");
  fix[wxT("kcedilla")] = wxT("kcommaaccent");
  fix[wxT("Lcedilla")] = wxT("Lcommaaccent");
  fix[wxT("lcedilla")] = wxT("lcommaaccent");
  fix[wxT("Ncedilla")] = wxT("Ncommaaccent");
  fix[wxT("ncedilla")] = wxT("ncommaaccent");
  fix[wxT("Rcedilla")] = wxT("Rcommaaccent");
  fix[wxT("rcedilla")] = wxT("rcommaaccent");
  fix[wxT("Scedilla")] = wxT("Scommaaccent");
  fix[wxT("scedilla")] = wxT("scommaaccent");
  fix[wxT("Tcedilla")] = wxT("Tcommaaccent");
  fix[wxT("tcedilla")] = wxT("tcommaaccent");
  fix[wxT("Dslash")] = wxT("Dcroat");
  fix[wxT("dslash")] = wxT("dcroat");
  fix[wxT("Dmacron")] = wxT("Dcroat");
  fix[wxT("dmacron")] = wxT("dcroat");
  fix[wxT("combininggraveaccent")] = wxT("gravecomb");
  fix[wxT("combininghookabove")] = wxT("hookabovecomb");
  fix[wxT("combiningtildeaccent")] = wxT("tildecomb");
  fix[wxT("combiningacuteaccent")] = wxT("acutecomb");
  fix[wxT("combiningdotbelow")] = wxT("dotbelowcomb");
  fix[wxT("dongsign")] = wxT("dong");

  // Read the AFM font metric file
  wxPdfGlyphWidthMap* widths = new wxPdfGlyphWidthMap();
  wxPdfChar2GlyphMap* glyphs = new wxPdfChar2GlyphMap();
  long cc;
  if (!cc2gn.empty())
  {
    for (cc = 0; cc <= 255; cc++)
    {
      (*widths)[cc] = 0xFFFF;
      (*glyphs)[cc] = 0;
    }
  }

  wxString line;
  wxString charcode, glyphname;
  wxString code, param, dummy, glyph;
  wxString token, tokenBoxHeight;
  long nParam, incWidth = -1, incGlyph = 0;
  long width, boxHeight, glyphNumber;
  wxString weight;
  bool hasGlyphNumbers = false;
  while (!afmFile.Eof())
  {
    line = text.ReadLine();
    line.Trim();

    wxStringTokenizer tkz(line, wxT(" "));
    int count = (int) tkz.CountTokens();
    if (count < 2) continue;
    code  = tkz.GetNextToken(); // 0
    param = tkz.GetNextToken(); // 1
    if (code == wxT("C"))
    {
      width = -1;
      glyphNumber = 0;
      boxHeight = 0;
      tokenBoxHeight = wxEmptyString;
      // Character metrics
      param.ToLong(&cc);
      dummy = tkz.GetNextToken(); // 2
      while (tkz.HasMoreTokens())
      {
        token = tkz.GetNextToken();
        if (token == wxT("WX")) // Character width
        {
          param = tkz.GetNextToken(); // Width
          param.ToLong(&width);
          dummy = tkz.GetNextToken(); // Semicolon
        }
        else if (token == wxT("N")) // Glyph name
        {
          glyphname = tkz.GetNextToken(); // Glyph name
          dummy = tkz.GetNextToken(); // Semicolon
        }
        else if (token == wxT("G")) // Glyph number
        {
          hasGlyphNumbers = true;
          param = tkz.GetNextToken(); // Number
          param.ToLong(&glyphNumber);
          dummy = tkz.GetNextToken(); // Semicolon
        }
        else if (token == wxT("B")) // Character bounding box
        {
          dummy = tkz.GetNextToken(); // x left
          dummy = tkz.GetNextToken(); // y bottom
          dummy = tkz.GetNextToken(); // x right
          tokenBoxHeight = tkz.GetNextToken(); // y top
          tokenBoxHeight.ToLong(&boxHeight);
          dummy = tkz.GetNextToken(); // Semicolon
        }
        else
        {
          while (tkz.HasMoreTokens() && tkz.GetNextToken() != wxT(";"));
        }
      }

      if (glyphname.Right(4) == wxT("20AC"))
      {
        glyphname = wxT("Euro");
      }
      if (glyphname == wxT("increment"))
      {
        incWidth = width;
        if (hasGlyphNumbers)
        {
          incGlyph = glyphNumber;
        }
      }
      if (fix.find(glyphname) != fix.end())
      {
        //Fix incorrect glyph name
        for (int i = 0; i <= 255; i++)
        {
          if (cc2gn[i] == fix[glyphname])
          {
            cc2gn[i] = glyphname;
          }
        }
      }
      if (cc2gn.empty())
      {
        // Symbolic font: use built-in encoding
        (*widths)[cc] = width;
        if (hasGlyphNumbers)
        {
          (*glyphs)[cc] = glyphNumber;
        }
        if (!hasCapHeight && !hasXCapHeight && cc == 'X' && tokenBoxHeight != wxEmptyString)
        {
          hasXCapHeight = true;
          fd.SetCapHeight(boxHeight);
        }
        if (!hasXHeight && cc == 'x' && tokenBoxHeight != wxEmptyString)
        {
          hasXHeight = true;
          fd.SetXHeight(boxHeight);
        }
      }
      else
      {
        // Search glyphname in cc2gn
        bool found = false;
        for (int i = 0; i <= 255; i++)
        {
          if (cc2gn[i] == glyphname)
          {
            found = true;
            (*widths)[i] = width;
            if (hasGlyphNumbers)
            {
              (*glyphs)[i] = glyphNumber;
            }
          }
        }
        if (!found)
        {
          wxLogMessage(wxT("Warning: character '") + glyphname + wxT("' is undefined."));
        }
        if (!hasCapHeight && !hasXCapHeight && glyphname == wxT("X") && tokenBoxHeight != wxEmptyString)
        {
          hasXCapHeight = true;
          fd.SetCapHeight(boxHeight);
        }
        if (!hasXHeight && glyphname == wxT("x") && tokenBoxHeight != wxEmptyString)
        {
          hasXHeight = true;
          fd.SetXHeight(boxHeight);
        }
      }
      if (!hasMissingWidth && glyphname == wxT(".notdef"))
      {
        hasMissingWidth = true;
        fd.SetMissingWidth(width);
      }
    }
    else if (code == wxT("FontName"))
    {
      afmFont->SetName(param);
    }
    else if (code == wxT("Weight"))
    {
      wxString weight = param.Lower();
      if (!hasStemV && (weight == wxT("black") || weight == wxT("bold")))
      {
        fd.SetStemV(120);
      }
    }
    else if (code == wxT("ItalicAngle"))
    {
      double italic;
      param.ToDouble(&italic);
      int italicAngle = int(italic);
      fd.SetItalicAngle(italicAngle);
      if (italicAngle > 0)
      {
        flags += 1 << 6;
      }
    }
    else if (code == wxT("Ascender"))
    {
      long ascent;
      param.ToLong(&ascent);
      fd.SetAscent(ascent);
    }
    else if (code == wxT("Descender"))
    {
      param.ToLong(&nParam);
      fd.SetDescent(nParam);
    }
    else if (code == wxT("UnderlineThickness"))
    {
      param.ToLong(&nParam);
      fd.SetUnderlineThickness(nParam);
    }
    else if (code == wxT("UnderlinePosition"))
    {
      param.ToLong(&nParam);
      fd.SetUnderlinePosition(nParam);
    }
    else if (code == wxT("IsFixedPitch"))
    {
      if (param == wxT("true"))
      {
        flags += 1 << 0;
      }
    }
    else if (code == wxT("FontBBox"))
    {
      hasFontBBox = true;
      wxString bbox2 = tkz.GetNextToken();
      wxString bbox3 = tkz.GetNextToken();
      wxString bbox4 = tkz.GetNextToken();
      wxString bBox = wxT("[") + param + wxT(" ") + bbox2 + wxT(" ") + bbox3 + wxT(" ") + bbox4 + wxT("]");
      fd.SetFontBBox(bBox);
    }
    else if (code == wxT("CapHeight"))
    {
      hasCapHeight = true;
      long capHeight;
      param.ToLong(&capHeight);
      fd.SetCapHeight(capHeight);
    }
    else if (code == wxT("StdVW"))
    {
      hasStemV = true;
      long stemV;
      param.ToLong(&stemV);
      fd.SetStemV(stemV);
    }
  }

  for (cc = 0; cc <= 255; cc++)
  {
    if ((*widths)[cc] == 0xFFFF)
    {
      if (cc2gn[cc] == wxT("Delta") && incWidth >= 0)
      {
        (*widths)[cc] = incWidth;
        if (hasGlyphNumbers)
        {
          (*glyphs)[cc] = incGlyph;
        }
      }
      else
      {
        (*widths)[cc] = fd.GetMissingWidth();
        if (hasGlyphNumbers)
        {
          (*glyphs)[cc] = 0;
        }
        wxLogMessage(wxT("Warning: character '") + cc2gn[cc] + wxT("' is missing."));
      }
    }
  }

  wxString diffs;
  if (encoding.Length() > 0)
  {
    // Build differences from reference encoding
    CTGMap cc2gnRef;
    valid = ReadMap(wxT("cp1252"), cc2gnRef);
    diffs = wxT("");
    int last = 0;
    for (int i = 32; i <= 255; i++)
    {
      if (cc2gn[i] != cc2gnRef[i])
      {
        if (i != last+1)
        {
          diffs += wxString::Format(wxT("%d "), i);
        }
        last = i;
        diffs = diffs + wxT("/") + cc2gn[i] + wxT(" ");
      }
    }
  }
  afmFont->SetDiffs(diffs);  
  
  if (cc2gn.empty())
  {
    flags += 1 << 2;
  }
  else
  {
    flags += 1 << 5;
  }
  fd.SetFlags(flags);
  if (!hasCapHeight && !hasXCapHeight)
  {
    fd.SetCapHeight(fd.GetAscent());
  }
  if (!hasFontBBox)
  {
    wxString fbb = wxString::Format(wxT("[0 %d 1000 %d]"), fd.GetDescent()-100, fd.GetAscent()+100);
    fd.SetFontBBox(fbb);
  }

  afmFont->SetGlyphWidthMap(widths);
  afmFont->SetChar2GlyphMap(glyphs);

  afmFont->SetDescription(fd);

  wxString baseName = fileName.GetName();
  if (embeddingAllowed)
  {
    if (fontType == wxT("TrueType"))
    {
      wxFileInputStream ttfFile(fontFileName);
      if (!ttfFile.Ok())
      {
        wxLogMessage(wxT("Error: Unable to read font file '") + fontFileName + wxT("'."));
        delete afmFont;
        return false;
      }
      size_t len = ttfFile.GetLength();
      wxFileOutputStream outFontFile(baseName + wxT(".z"));
      wxZlibOutputStream zOutFontFile(outFontFile);
      zOutFontFile.Write(ttfFile);
      zOutFontFile.Close();
      afmFont->SetFontFile(baseName + wxT(".z"));
      afmFont->SetSize1(len);
      wxLogMessage(wxT("Font file compressed (") + baseName + wxT(".z)."));
    }
    else
    {
      wxFileInputStream pfbFile(fontFileName);
      if (!pfbFile.Ok())
      {
        wxLogMessage(wxT("Error: Unable to read font file '") + fontFileName + wxT("'."));
        delete afmFont;
        return false;
      }
      size_t len = pfbFile.GetLength();
      // Find first two sections and discard third one
      unsigned char* buffer = new unsigned char[len];
      unsigned char* buf1 = buffer;
      unsigned char* buf2;
      pfbFile.Read(buffer, len);
      unsigned char first = buffer[0];
      if (first == 128)
      {
        // Strip first binary header
        buf1 += 6;
        len -= 6;
      }
      int* f = makeFail("eexec",5);
      int size1 = (int) findString((char*) buf1, len, "eexec", 5, f);
      delete [] f;

      int size2 = -1;
      if (size1 >= 0)
      {
        size1 += 6;
        unsigned char second = buf1[size1];
        buf2 = buf1 + size1;
        len -= size1;
        if (first == 128 && second == 128)
        {
          // Strip second binary header
          buf2 += 6;
          len -= 6;
        }
        f = makeFail("00000000",8);
        size2 = (int) findString((char*) buf2, len, "00000000", 8, f);
        delete [] f;
        if (size2 >= 0)
        {
          wxFileOutputStream outFontFile(baseName + wxT(".z"));
          wxZlibOutputStream zOutFontFile(outFontFile);
          zOutFontFile.Write(buf1, size1);
          zOutFontFile.Write(buf2, size2);
          afmFont->SetFontFile(baseName + wxT(".z"));
          afmFont->SetSize1(size1);
          afmFont->SetSize2(size2);
        }
      }
      delete [] buffer;
      if (size1 < 0 || size2 < 0)
      {
        wxLogMessage(wxT("Warning: Font file does not seem to be valid Type1, font embedding not possible."));
      }
    }
  }
  else
  {
    if (fontFileName.Length() > 0)
    {
      wxLogMessage(wxT("Warning: Font license does not allow embedding."));
    }
    else
    {
      wxLogMessage(wxT("Warning: Font file name missing, font embedding not possible."));
    }
  }

  // Create XML file
  CreateFontMetricsFile(baseName + wxT(".xml"), *afmFont, hasGlyphNumbers);
  wxLogMessage(wxT("Font definition file generated (") + baseName + wxT(".xml)."));

  //delete widths;
  delete afmFont;
  return true;
}
Esempio n. 6
0
int IfaceCheckApp::CompareClasses(const wxClass* iface, const wxClass* api)
{
    const wxMethod *real;
    int count = 0;

    wxASSERT(iface && api);

    // shorten the name of the header so the log file is more readable
    wxString header = wxFileName(iface->GetHeader()).GetFullName();

#if defined(__INTEL_COMPILER) && 1 /* VDM auto patch */
#   pragma ivdep
#   pragma swp
#   pragma unroll
#   pragma prefetch
#   if 0
#       pragma simd noassert
#   endif
#endif /* VDM auto patch */
    for (unsigned int i=0; i<iface->GetMethodCount(); i++)
    {
        const wxMethod& m = iface->GetMethod(i);

        // only compare the methods which are available for the port
        // for which the gcc XML was produced
        if (m.GetAvailability() != wxPORT_UNKNOWN &&
            (m.GetAvailability() & m_gccInterface.GetInterfacePort()) == 0) {

            if (g_verbose)
            {
                wxLogMessage("skipping method '%s' since it's not available for the %s port.",
                           m.GetAsString(), m_gccInterface.GetInterfacePortName());
            }

            continue;       // skip this method
        }

        // search in the methods of the api classes provided
        real = api->RecursiveUpwardFindMethod(m, &m_gccInterface);

        // avoid some false positives:
        if (!real && m.ActsAsDefaultCtor())
        {
            // build an artificial default ctor for this class:
            wxMethod temp(m);
            temp.GetArgumentTypes().Clear();

            // repeat search:
            real = api->RecursiveUpwardFindMethod(temp, &m_gccInterface);
        }

        // no matches?
        if (!real)
        {
            bool proceed = true;
            wxMethodPtrArray overloads =
                api->RecursiveUpwardFindMethodsNamed(m.GetName(), &m_gccInterface);

            // avoid false positives:
#if defined(__INTEL_COMPILER) && 1 /* VDM auto patch */
#   pragma ivdep
#   pragma swp
#   pragma unroll
#   pragma prefetch
#   if 0
#       pragma simd noassert
#   endif
#endif /* VDM auto patch */
            for (unsigned int k=0; k<overloads.GetCount(); k++)
                if (overloads[k]->MatchesExceptForAttributes(m) &&
                    m.IsDeprecated() && !overloads[k]->IsDeprecated())
                {
                    // maybe the iface method is marked as deprecated but the
                    // real method is not?
                    wxMethod tmp(*overloads[k]);
                    tmp.SetDeprecated(true);

                    if (tmp == m)
                    {
                        // in this case, we can disregard this warning... the real
                        // method probably is included in WXWIN_COMPAT sections!
                        proceed = false;    // skip this method
                    }
                }

#define HACK_TO_AUTO_CORRECT_ONLY_METHOD_ATTRIBUTES        0
#if HACK_TO_AUTO_CORRECT_ONLY_METHOD_ATTRIBUTES
#if defined(__INTEL_COMPILER) && 1 /* VDM auto patch */
#   pragma ivdep
#   pragma swp
#   pragma unroll
#   pragma prefetch
#   if 0
#       pragma simd noassert
#   endif
#endif /* VDM auto patch */
            for (unsigned int k=0; k<overloads.GetCount(); k++)
                if (overloads[k]->MatchesExceptForAttributes(m))
                {
                    // fix default values of results[k]:
                    wxMethod tmp(*overloads[k]);
                    tmp.SetArgumentTypes(m.GetArgumentTypes());

                    // modify interface header
                    if (FixMethod(iface->GetHeader(), &m, &tmp))
                    {
                        wxLogMessage("Adjusted attributes of '%s' method", m.GetAsString());
                    }

                    proceed = false;
                    break;
                }
#endif // HACK_TO_AUTO_CORRECT_ONLY_METHOD_ATTRIBUTES

            if (proceed)
            {
                if (overloads.GetCount()==0)
                {
                    wxLogMessage("%s: real '%s' class and their parents have no method '%s'",
                                header, api->GetName(), m.GetAsString());
                    // we've found no overloads
                }
                else
                {
                    // first, output a warning
                    wxString warning = header;
                    if (overloads.GetCount()>1)
                        warning += wxString::Format(": in the real headers there are %d overloads of '%s' for "
                                                    "'%s' all with different signatures:\n",
                                                    overloads.GetCount(), m.GetName(), api->GetName());
                    else {
                        warning += wxString::Format(": in the real headers there is a method '%s' for '%s'"
                                                    " but has different signature:\n",
                                                    m.GetName(), api->GetName());
                    }

                    // get a list of the prototypes with _all_ possible attributes:
                    warning += "\tdoxy header: " + m.GetAsString(true, true, true, true);
#if defined(__INTEL_COMPILER) && 1 /* VDM auto patch */
#   pragma ivdep
#   pragma swp
#   pragma unroll
#   pragma prefetch
#   if 0
#       pragma simd noassert
#   endif
#endif /* VDM auto patch */
                    for (unsigned int j=0; j<overloads.GetCount(); j++)
                        warning += "\n\treal header: " + overloads[j]->GetAsString(true, true, true, true);

                    wxLogWarning("%s", warning);
                    count++;

                    if (overloads.GetCount()>1)
                    {
                        // TODO: decide which of these overloads is the most "similar" to m
                        //       and eventually modify it
                        if (m_modify)
                        {
                            wxLogWarning("\tmanual fix is required");
                        }
                    }
                    else
                    {
                        wxASSERT(overloads.GetCount() == 1);

                        if (m_modify || m.IsCtor())
                        {
                            wxLogWarning("\tfixing it...");

                            // try to modify it!
                            FixMethod(iface->GetHeader(), &m, overloads[0]);
                        }
                    }
                }

                count++;
            }       // if (proceed)
        }
    }

    return count;
}
Esempio n. 7
0
bool wxvbamApp::OnCmdLineParsed(wxCmdLineParser &cl)
{
	if (!wxApp::OnCmdLineParsed(cl))
		return false;

	wxString s;

	if (cl.Found(wxT("save-xrc"), &s))
	{
		// This was most likely done on a command line, so use
		// stderr instead of gui for messages
		wxLog::SetActiveTarget(new wxLogStderr);
		wxFileSystem fs;
		wxFSFile* f = fs.OpenFile(wxT("memory:wxvbam.xrs#zip:wxvbam.xrs$wxvbam.xrc"));

		if (!f)
		{
			wxLogError(_("Configuration/build error: can't find built-in xrc"));
			return false;
		}

		wxFileOutputStream os(s);
		os.Write(*f->GetStream());
		delete f;
		wxString lm;
		lm.Printf(_("Wrote built-in configuration to %s.\n"
		            "To override, remove all but changed root node(s).  "
		            "First found root node of correct name in any .xrc or "
		            ".xrs files in following search path overrides built-in:"),
		          s.c_str());
		tack_full_path(lm);
		wxLogMessage(lm);
		return false;
	}

	if (cl.Found(wxT("print-cfg-path")))
	{
		// This was most likely done on a command line, so use
		// stderr instead of gui for messages
		wxLog::SetActiveTarget(new wxLogStderr);
		wxString lm(_("Configuration is read from, in order:"));
		tack_full_path(lm);
		wxLogMessage(lm);
		return false;
	}

	if (cl.Found(wxT("save-over"), &s))
	{
		// This was most likely done on a command line, so use
		// stderr instead of gui for messages
		wxLog::SetActiveTarget(new wxLogStderr);
		wxFileOutputStream os(s);
		os.Write(builtin_over, sizeof(builtin_over));
		wxString lm;
		lm.Printf(_("Wrote built-in override file to %s\n"
		            "To override, delete all but changed section.  First found section is used from search path:"), s.c_str());
		wxString oi = wxFileName::GetPathSeparator();
		oi += wxT("vba-over.ini");
		tack_full_path(lm, oi);
		lm.append(_("\n\tbuilt-in"));
		wxLogMessage(lm);
		return false;
	}

	if (cl.Found(wxT("f")))
	{
		pending_fullscreen = true;
	}

	if (cl.Found(wxT("o")))
	{
		wxPrintf(_("Options set from the command line are saved if any"
		           " configuration changes are made in the user interface.\n\n"
		           "For flag options, true and false are specified as 1 and 0, respectively.\n\n"));

		for (int i = 0; i < num_opts; i++)
		{
			wxPrintf(wxT("%s (%s"), opts[i].opt,
			         opts[i].boolopt ? (const wxChar*)wxT("flag") :
			         opts[i].stropt ? (const wxChar*)wxT("string") :
			         opts[i].enumvals ? opts[i].enumvals :
			         opts[i].intopt ? (const wxChar*)wxT("int") :
			         (const wxChar*)wxT("string"));

			if (opts[i].enumvals)
			{
				const wxChar* evx = wxGetTranslation(opts[i].enumvals);

				if (wxStrcmp(evx, opts[i].enumvals))
					wxPrintf(wxT(" = %s"), evx);
			}

			wxPrintf(wxT(")\n\t%s\n\n"), opts[i].desc);

			if (opts[i].enumvals)
				opts[i].enumvals = wxGetTranslation(opts[i].enumvals);
		}

		wxPrintf(_("The commands available for the Keyboard/* option are:\n\n"));

		for (int i = 0; i < ncmds; i++)
			wxPrintf(wxT("%s (%s)\n"), cmdtab[i].cmd, cmdtab[i].name);

		return false;
	}

#if !defined(NO_LINK) && !defined(__WXMSW__)

	if (cl.Found(wxT("s")))
	{
		CleanLocalLink();
	}

#endif
	int nparm = cl.GetParamCount();
	bool complained = false, gotfile = false;

	for (int i = 0; i < nparm; i++)
	{
		wxString p = cl.GetParam(i);
		size_t eqat = p.find(wxT('='));

		if (eqat != wxString::npos)
		{
			p[eqat] = 0;

			if (!opt_set(p.c_str(), p.c_str() + eqat + 1))
			{
				p[eqat] = wxT('=');
				eqat = wxString::npos;
			}
			else
				p[eqat] = wxT('=');

			pending_optset.push_back(p);
		}

		if (eqat == wxString::npos)
		{
			if (!gotfile)
			{
				pending_load = p;
				gotfile = true;
			}
			else
			{
				if (!complained)
				{
					wxFprintf(stderr, _("Bad configuration option or multiple ROM files given:\n"));
					wxFprintf(stderr, wxT("%s\n"), pending_load.c_str());
					complained = true;
				}

				wxFprintf(stderr, wxT("%s\n"), p.c_str());
			}
		}
	}

	home = strdup((const char*)wxApp::argv[0]);
	SetHome(home);
	LoadConfig(); // Parse command line arguments (overrides ini)
	ReadOpts(argc, (char**)argv);
	return true;
}
Esempio n. 8
0
/* Tokenizer::readToken
 * Reads the next 'token' from the text & moves past it
 *******************************************************************/
void Tokenizer::readToken()
{
	token_current.clear();
	bool ready = false;
	qstring = false;

	// Increment pointer to next token
	while (!ready)
	{
		ready = true;

		// Increment pointer until non-whitespace is found
		while (isWhitespace(current[0]))
		{
			// Return if end of text found
			if (!incrementCurrent())
				return;
		}

		// Skip C-style comments
		if (comments & CCOMMENTS)
		{
			// Check if we have a line comment
			if (current + 1 < end && current[0] == '/' && current[1] == '/')
			{
				ready = false;

				// DECORATE //$ handling
				if (!decorate)
					skipLineComment();
				else if (current + 2 < end && current[2] != '$')
					skipLineComment();
				else
					ready = true;
			}

			// Check if we have a multiline comment
			if (current + 1 != end && current[0] == '/' && current[1] == '*')
			{
				skipMultilineComment(); // Skip it
				ready = false;
			}
		}

		// Skip '##' comments
		if (comments & HCOMMENTS)
		{
			if (current + 1 != end && current[0] == '#' && current[1] == '#')
			{
				skipLineComment(); // Skip it
				ready = false;
			}
		}

		// Skip ';' comments
		if (comments & SCOMMENTS)
		{
			if (current[0] == ';')
			{
				skipLineComment(); // Skip it
				ready = false;
			}
		}

		// Check for end of text
		if (position == size)
			return;
	}

	// Init token delimiters
	t_start = position;
	t_end = position;

	// If we're at a special character, it's our token
	if (isSpecialCharacter(current[0]))
	{
		token_current += current[0];
		t_end = position + 1;
		incrementCurrent();
		return;
	}

	// Now read the token
	if (current[0] == '\"')   // If we have a literal string (enclosed with "")
	{
		qstring = true;

		// Skip opening "
		incrementCurrent();

		// Read literal string (include whitespace)
		while (current[0] != '\"')
		{
			token_current += current[0];

			if (!incrementCurrent())
				return;
		}

		// Skip closing "
		incrementCurrent();
	}
	else
	{
		// Read token (don't include whitespace)
		while (!isWhitespace(current[0]))
		{
			// Return if special character found
			if (isSpecialCharacter(current[0]))
				return;

			// Add current character to the token
			token_current += current[0];

			// Return if end of text found
			if (!incrementCurrent())
				return;
		}
	}

	// Write token to log if debug mode enabled
	if (debug)
		wxLogMessage(token_current);

	// Return the token
	return;
}
void CStarNetHandler::linkUp(DSTAR_PROTOCOL protocol, const wxString& callsign)
{
	wxLogMessage(wxT("DCS link to %s established"), callsign.c_str());

	m_linkStatus = LS_LINKED_DCS;
}
Esempio n. 10
0
bool Spring::RunReplay ( const wxString& filename )
{
  wxLogMessage( _T("launching spring with replay: ") + filename );

  return LaunchSpring( _T("\"") + filename + _T("\"") );
}
Esempio n. 11
0
void* CDSPControl::Entry()
{
	// Open for business
	m_running = true;

	m_rxWriter->enable();

	while (!TestDestroy()) {
		wxSemaError ret = m_waiting.WaitTimeout(500UL);

		if (ret == wxSEMA_NO_ERROR) {
			if (m_transmit == TXSTATE_INT || m_transmit == TXSTATE_EXT) {
				unsigned int nSamples = m_txRingBuffer.getData(m_txBuffer, m_blockSize);
				if (nSamples != m_blockSize) {
					// Copy the last buffer of good data to the output
					::memcpy(m_txBuffer, m_txLastBuffer, m_blockSize * sizeof(float) * 2U);
					m_txFills++;
				} else {
					// Save the last full buffer in case it's needed
					::memcpy(m_txLastBuffer, m_txBuffer, m_blockSize * sizeof(float) * 2U);
				}

				if (nSamples > 0U)
					m_txWriter->write(m_txBuffer, nSamples);
			}

			unsigned int nSamples = m_rxRingBuffer.getData(m_rxBuffer, m_blockSize);

			// Create silence on transmit if no sidetone is being transmitted
			if (nSamples == 0U && (m_transmit == TXSTATE_INT || m_transmit == TXSTATE_EXT)) {
				::memset(m_rxBuffer, 0x00U, m_blockSize * 2U * sizeof(float));
				nSamples = m_blockSize;
			}

			// Only send audio to the external protocol handler when not transmitting
			if (m_extHandler != NULL && m_transmit != TXSTATE_EXT)
				m_extHandler->writeAudio(m_rxBuffer, nSamples);

			if (nSamples != m_blockSize) {
				// Copy the last buffer of good data to the output
				::memcpy(m_rxBuffer, m_rxLastBuffer, m_blockSize * sizeof(float) * 2U);
				m_rxFills++;
			} else {
				// Save the last full buffer in case it's needed
				::memcpy(m_rxLastBuffer, m_rxBuffer, m_blockSize * sizeof(float) * 2U);
			}

			// Don't record when transmitting
			if (m_record != NULL && (m_recordType == RECORD_MONO_AUDIO || m_recordType == RECORD_STEREO_AUDIO) && m_transmit == TXSTATE_RX)
				m_record->write(m_rxBuffer, nSamples);

			// Scale the audio by the AF Gain setting
			for (unsigned int i = 0U; i < (nSamples * 2U); i++)
				m_rxBuffer[i] *= m_afGain;

			m_rxWriter->write(m_rxBuffer, nSamples);
		}
	}

	m_running = false;

	m_rxWriter->disable();
	m_txWriter->disable();

	wxLogMessage(wxT("DSPControl: RX Overruns=%u, RX Fills=%u"), m_rxOverruns, m_rxFills);
	wxLogMessage(wxT("DSPControl: TX Overruns=%u, TX Fills=%u"), m_txOverruns, m_txFills);

	closeIO();

	return (void*)0;
}
Esempio n. 12
0
wxString Spring::WriteScriptTxt( IBattle& battle ) const
{
    wxLogMessage(_T("0 WriteScriptTxt called "));

    wxString ret;

    TDFWriter tdf(ret);

    // Start generating the script.
    tdf.EnterSection( _T("GAME") );

		tdf.Append( _T("HostIP"), battle.GetHostIp() );
			if ( battle.IsFounderMe() )
			{
					if ( battle.GetNatType() == NAT_Hole_punching ) tdf.Append( _T("HostPort"), battle.GetMyInternalUdpSourcePort() );
					else tdf.Append(_T("HostPort"), battle.GetHostPort() );
			}
			else
			{
					tdf.Append( _T("HostPort"), battle.GetHostPort() );
					if ( battle.GetNatType() == NAT_Hole_punching )
					{
						tdf.Append( _T("SourcePort"), battle.GetMyInternalUdpSourcePort() );
					}
					else if ( sett().GetClientPort() != 0)
					{
						tdf.Append( _T("SourcePort"), sett().GetClientPort() ); /// this allows to play with broken router by setting SourcePort to some forwarded port.
					}
			}
			tdf.Append( _T("IsHost"), battle.IsFounderMe() );

			tdf.Append(_T("MyPlayerName"), battle.GetMe().GetNick() );

			if ( !battle.IsFounderMe() )
			{
					tdf.LeaveSection();
					return ret;
			}

			/**********************************************************************************
																		Host-only section
			**********************************************************************************/

			tdf.AppendLineBreak();

			tdf.Append(_T("ModHash"), battle.LoadMod().hash );
			tdf.Append(_T("MapHash"), battle.LoadMap().hash );

			tdf.Append( _T("Mapname"), battle.GetHostMapName() );
			tdf.Append( _T("GameType"), battle.GetHostModName() );

			tdf.AppendLineBreak();

			switch ( battle.GetBattleType() )
			{
				case BT_Played: break;
				case BT_Replay:
				{
					wxString path = battle.GetPlayBackFilePath();
					if ( path.Find(_T("/")) != wxNOT_FOUND ) path.BeforeLast(_T('/'));
					tdf.Append( _T("DemoFile"), path );
					tdf.AppendLineBreak();
					break;
				}
				case BT_Savegame:
				{
					wxString path = battle.GetPlayBackFilePath();
					if ( path.Find(_T("/")) != wxNOT_FOUND ) path.BeforeLast(_T('/'));
					tdf.Append( _T("Savefile"), path );
					tdf.AppendLineBreak();
					break;
				}
				default:
                    wxLogDebugFunc( _T("") ); break;
			}

			long startpostype;
			battle.CustomBattleOptions().getSingleValue( _T("startpostype"), OptionsWrapper::EngineOption ).ToLong( &startpostype );

			std::vector<StartPos> remap_positions;
			if ( battle.IsProxy() && ( startpostype != IBattle::ST_Pick ) && ( startpostype != IBattle::ST_Choose ) )
			{
				std::set<int> parsedteams;
				unsigned int NumUsers = battle.GetNumUsers();
				unsigned int NumTeams = 0;
				for ( unsigned int i = 0; i < NumUsers; i++ )
				{
						User& usr = battle.GetUser( i );
						UserBattleStatus& status = usr.BattleStatus();
						if ( status.spectator ) continue;
						if ( parsedteams.find( status.team ) != parsedteams.end() ) continue; // skip duplicates
						parsedteams.insert( status.team );
						NumTeams++;
				}

				MapInfo infos = battle.LoadMap().info;
				unsigned int nummapstartpositions = infos.positions.size();
				unsigned int copysize = std::min( nummapstartpositions, NumTeams );
				remap_positions = std::vector<StartPos> ( infos.positions.begin(), infos.positions.begin() + copysize ); // only add the first x positions

				if ( startpostype == IBattle::ST_Random )
				{
					random_shuffle( remap_positions.begin(), remap_positions.end() ); // shuffle the positions
				}

			}
			if ( battle.IsProxy() )
			{
				if ( ( startpostype == IBattle::ST_Random ) || ( startpostype == IBattle::ST_Fixed ) )
				{
					tdf.Append( _T("startpostype"), IBattle::ST_Pick );
				}
				else tdf.Append( _T("startpostype"), startpostype );
			}
			else tdf.Append( _T("startpostype"), startpostype );

			tdf.EnterSection( _T("mapoptions") );
				OptionsWrapper::wxStringTripleVec optlistMap = battle.CustomBattleOptions().getOptions( OptionsWrapper::MapOption );
				for (OptionsWrapper::wxStringTripleVec::const_iterator it = optlistMap.begin(); it != optlistMap.end(); ++it)
				{
						tdf.Append(it->first,it->second.second);
				}
			tdf.LeaveSection();


			tdf.EnterSection(_T("modoptions"));
				OptionsWrapper::wxStringTripleVec optlistMod = battle.CustomBattleOptions().getOptions( OptionsWrapper::ModOption );
				for (OptionsWrapper::wxStringTripleVec::const_iterator it = optlistMod.begin(); it != optlistMod.end(); ++it)
				{
						tdf.Append(it->first,it->second.second);
				}
			tdf.LeaveSection();

			std::map<wxString,int> units = battle.RestrictedUnits();
			tdf.Append( _T("NumRestrictions"), units.size());
			tdf.EnterSection( _T("RESTRICT") );
				int restrictcount = 0;
				for ( std::map<wxString, int>::iterator itor = units.begin(); itor != units.end(); itor++ )
				{
						tdf.Append(_T("Unit") + TowxString( restrictcount ), itor->first );
						tdf.Append(_T("Limit") + TowxString( restrictcount ), itor->second );
						restrictcount++;
				}
			tdf.LeaveSection();


			tdf.AppendLineBreak();

			if ( battle.IsProxy() )
			{
				tdf.Append( _T("NumPlayers"), battle.GetNumPlayers() -1 );
				tdf.Append( _T("NumUsers"), battle.GetNumUsers() -1 );
			}
			else
			{
				tdf.Append( _T("NumPlayers"), battle.GetNumPlayers() );
				tdf.Append( _T("NumUsers"), battle.GetNumUsers() );
			}

			tdf.AppendLineBreak();

			unsigned int NumUsers = battle.GetNumUsers();

			typedef std::map<int, int> ProgressiveTeamsVec;
			typedef ProgressiveTeamsVec::iterator ProgressiveTeamsVecIter;
			ProgressiveTeamsVec teams_to_sorted_teams; // original team -> progressive team
			int free_team = 0;
			std::map<User*, int> player_to_number; // player -> ordernumber
			srand ( time(NULL) );
			for ( unsigned int i = 0; i < NumUsers; i++ )
			{
					User& user = battle.GetUser( i );
					UserBattleStatus& status = user.BattleStatus();
					if ( !status.spectator )
					{
						ProgressiveTeamsVecIter itor = teams_to_sorted_teams.find ( status.team );
						if ( itor == teams_to_sorted_teams.end() )
						{
							teams_to_sorted_teams[status.team] = free_team;
							free_team++;
						}
					}
				  if ( battle.IsProxy() && ( user.GetNick() == battle.GetFounder().GetNick() ) ) continue;
					if ( status.IsBot() ) continue;
					tdf.EnterSection( _T("PLAYER") + TowxString( i ) );
							tdf.Append( _T("Name"), user.GetNick() );
							tdf.Append( _T("CountryCode"), user.GetCountry().Lower());
							tdf.Append( _T("Spectator"), status.spectator );
							tdf.Append( _T("Rank"), (int)user.GetRank() );
							tdf.Append( _T("IsFromDemo"), int(status.isfromdemo) );
							if ( !status.spectator )
							{
								tdf.Append( _T("Team"), teams_to_sorted_teams[status.team] );
							}
							else
							{
								int speccteam = 0;
								if ( teams_to_sorted_teams.size() != 0 ) speccteam = rand() % teams_to_sorted_teams.size();
								tdf.Append( _T("Team"), speccteam );
							}
					tdf.LeaveSection();
					player_to_number[&user] = i;
			}
			if ( usync().VersionSupports( IUnitSync::USYNC_GetSkirmishAI ) )
			{
				for ( unsigned int i = 0; i < NumUsers; i++ )
				{
						User& user = battle.GetUser( i );
						UserBattleStatus& status = user.BattleStatus();
						if ( !status.IsBot() ) continue;
						tdf.EnterSection( _T("AI") + TowxString( i ) );
								tdf.Append( _T("Name"), user.GetNick() ); // AI's nick;
								tdf.Append( _T("ShortName"), status.aishortname ); // AI libtype
								tdf.Append( _T("Version"), status.aiversion ); // AI libtype version
								tdf.Append( _T("Team"), teams_to_sorted_teams[status.team] );
								tdf.Append( _T("IsFromDemo"), int(status.isfromdemo) );
								tdf.Append( _T("Host"), player_to_number[&battle.GetUser( status.owner )] );
								tdf.EnterSection( _T("Options") );
									int optionmapindex = battle.CustomBattleOptions().GetAIOptionIndex( user.GetNick() );
									if ( optionmapindex > 0 )
									{
										OptionsWrapper::wxStringTripleVec optlistMod_ = battle.CustomBattleOptions().getOptions( (OptionsWrapper::GameOption)optionmapindex );
										for (OptionsWrapper::wxStringTripleVec::const_iterator it = optlistMod_.begin(); it != optlistMod_.end(); ++it)
										{
												tdf.Append(it->first,it->second.second);
										}
									}
								tdf.LeaveSection();
						tdf.LeaveSection();
						player_to_number[&user] = i;
				}
			}

			tdf.AppendLineBreak();

			std::set<int> parsedteams;
			wxArrayString sides = usync().GetSides( battle.GetHostModName() );
			for ( unsigned int i = 0; i < NumUsers; i++ )
			{
					User& usr = battle.GetUser( i );
					UserBattleStatus& status = usr.BattleStatus();
					if ( status.spectator ) continue;
					if ( parsedteams.find( status.team ) != parsedteams.end() ) continue; // skip duplicates
					parsedteams.insert( status.team );

					tdf.EnterSection( _T("TEAM") + TowxString( teams_to_sorted_teams[status.team] ) );
						if ( !usync().VersionSupports( IUnitSync::USYNC_GetSkirmishAI ) && status.IsBot() )
						{
								tdf.Append( _T("AIDLL"), status.aishortname );
								tdf.Append( _T("TeamLeader"), player_to_number[&battle.GetUser( status.owner )] ); // bot owner is the team leader
						}
						else
						{
								if ( status.IsBot() )
								{
										tdf.Append( _T("TeamLeader"), player_to_number[&battle.GetUser( status.owner )] );
								}
								else
								{
										tdf.Append( _T("TeamLeader"), player_to_number[&usr] );
								}
						}
						if ( battle.IsProxy() )
						{
							if ( startpostype == IBattle::ST_Pick )
							{
									tdf.Append(_T("StartPosX"), status.pos.x );
									tdf.Append(_T("StartPosZ"), status.pos.y );
							}
							else if ( ( startpostype == IBattle::ST_Fixed ) || ( startpostype == IBattle::ST_Random ) )
							{
									int teamnumber = teams_to_sorted_teams[status.team];
									if ( teamnumber < int(remap_positions.size()) ) // don't overflow
									{
										StartPos position = remap_positions[teamnumber];
										tdf.Append(_T("StartPosX"), position.x );
										tdf.Append(_T("StartPosZ"), position.y );
									}
							}
						}
						else
						{
							if ( startpostype == IBattle::ST_Pick )
							{
									tdf.Append(_T("StartPosX"), status.pos.x );
									tdf.Append(_T("StartPosZ"), status.pos.y );
							}
						}

						tdf.Append( _T("AllyTeam"),status.ally );

						wxString colourstring =
								TowxString( status.colour.Red()/255.0 ) + _T(' ') +
								TowxString( status.colour.Green()/255.0 ) + _T(' ') +
								TowxString( status.colour.Blue()/255.0 );
						tdf.Append( _T("RGBColor"), colourstring);

						unsigned int side = status.side;
						if ( side < sides.GetCount() ) tdf.Append( _T("Side"), sides[side] );
						tdf.Append( _T("Handicap"), status.handicap );
					tdf.LeaveSection();
			}

			tdf.AppendLineBreak();


			unsigned int maxiter = std::max( NumUsers, battle.GetLastRectIdx() + 1 );
			std::set<int> parsedallys;
			for ( unsigned int i = 0; i < maxiter; i++ )
			{

					User& usr = battle.GetUser( i );
					UserBattleStatus& status = usr.BattleStatus();
					BattleStartRect sr = battle.GetStartRect( i );
					if ( status.spectator && !sr.IsOk() ) continue;
					int ally = status.ally;
					if ( status.spectator ) ally = i;
					if ( parsedallys.find( ally ) != parsedallys.end() ) continue; // skip duplicates
					sr = battle.GetStartRect( ally );
					parsedallys.insert( ally );

					tdf.EnterSection( _T("ALLYTEAM") + TowxString( ally ) );
						tdf.Append( _T("NumAllies"), 0 );
						if ( sr.IsOk() )
						{
								const char* old_locale = std::setlocale(LC_NUMERIC, "C");

								tdf.Append( _T("StartRectLeft"), wxString::Format( _T("%.3f"), sr.left / 200.0 ) );
								tdf.Append( _T("StartRectTop"), wxString::Format( _T("%.3f"), sr.top / 200.0 ) );
								tdf.Append( _T("StartRectRight"), wxString::Format( _T("%.3f"), sr.right / 200.0 ) );
								tdf.Append( _T("StartRectBottom"), wxString::Format( _T("%.3f"), sr.bottom / 200.0 ) );

								std::setlocale(LC_NUMERIC, old_locale);
						}
					tdf.LeaveSection();
			}

    tdf.LeaveSection();

    return ret;

}
//! @brief Initializes the application.
//!
//! It will open the main window and connect default to server or open the connect window.
bool SpringLobbyApp::OnInit()
{

	wxSetEnv(_T("UBUNTU_MENUPROXY"), _T("0"));
	//this triggers the Cli Parser amongst other stuff
	if (!wxApp::OnInit())
		return false;
	SetAppName(m_appname);
#if wxUSE_ON_FATAL_EXCEPTION
	wxHandleFatalExceptions(!m_crash_handle_disable);
#else
	try {
#endif

	const wxString m_log_file_path = SlPaths::GetLobbyWriteDir() + "springlobby.log";

	//initialize all loggers, we'll use the returned pointer to set correct parent window later
	wxLogWindow* loggerwin = Logger::InitializeLoggingTargets(0, m_log_console, m_log_file_path, m_log_window_show, m_log_verbosity);

	wxLogMessage(_T("%s started"), TowxString(GetSpringlobbyAgent()).c_str());

	//this needs to called _before_ mainwindow instance is created
	wxInitAllImageHandlers();
	wxFileSystem::AddHandler(new wxZipFSHandler);
	wxSocketBase::Initialize();


	m_translationhelper = new wxTranslationHelper(GetAppName().Lower(), getLocalePath());

	const std::string configdir = SlPaths::GetConfigfileDir();
	wxLogMessage("Config dir: %s", configdir.c_str());
	SlPaths::mkDir(configdir);

	if (cfg().ReadBool(_T("/ResetLayout"))) {
		wxLogMessage("Resetting Layout...");
		//we do this early on and reset the config var a little later so we can save a def. perps once mw is created
		sett().RemoveLayouts();
		cfg().Write(_T( "/ResetLayout" ), false);
		ui().mw().SavePerspectives(_T("SpringLobby-default"));
	}

	if (SlPaths::IsPortableMode()) {
		// change write path for downloader if in portable mode
		fileSystem->setWritePath(SlPaths::GetExecutableFolder());
	} else {
		// only search if not in portable mode
		SlPaths::SetSpringBinary(SlPaths::GetCurrentUsedSpringIndex(), SlPaths::GetSpringBinary());
		SlPaths::SetUnitSync(SlPaths::GetCurrentUsedSpringIndex(), SlPaths::GetUnitSync());
	}
	wxLogMessage("Configuring Unitsync...");
	// configure unitsync paths before trying to load
	SlPaths::ReconfigureUnitsync();

	sett().Setup(m_translationhelper);

	notificationManager(); //needs to be initialized too

	wxLogMessage("Showing Main Window");
	ui().ShowMainWindow();
	SetTopWindow(&ui().mw());
	ui().mw().SetLogWin(loggerwin);

	//unitsync first load, FIXME move to a thread!
	wxLogMessage("Refreshing Spring Version List...");
	SlPaths::RefreshSpringVersionList();
	if (LSL::usync().ReloadUnitSyncLib()) {
		GlobalEventManager::Instance()->Send(GlobalEventManager::OnUnitsyncReloaded);
	} else {
		wxLogWarning("Couldn't load unitsync");
	}

	wxLogWarning("%s", TowxString(GetSpringlobbyInfo()).c_str());

	ui().OnInit();

#if !wxUSE_ON_FATAL_EXCEPTION
}
catch (std::exception& ex)
{
	wxLogError(_T("Error had happened: " + wxString(ex.what())));
}
#endif

return true;
}
Esempio n. 14
0
//----------------------------------------------------------------------------------------
int  DBGrid::OnTableView(wxString Table)
{
    wxStopWatch sw;
    //---------------------------------------------------------------------------------------
    int  x,y,z;
    wxString Temp0;
    wxBeginBusyCursor();
    SetDefaultCellFont(* pDoc->ft_Doc);
    //---------------------------------------------------------------------------------------
    ct_BrowserDB = (db_Br+i_Which)->ct_BrowserDB;                       // Get the DSN Pointer
    //---------------------------------------------------------------------------------------
    if (ct_BrowserDB)                                                   // Valid pointer (!= NULL) ?
    {      // Pointer is Valid, use the wxDatabase Information
        for (x=0;x<ct_BrowserDB->numTables;x++)                            // go through the Tables
        {
            if (!wxStrcmp((ct_BrowserDB->pTableInf+x)->tableName,Table))      // is this our Table ?
            {    // Yes, the Data of this Table shall be put into the Grid
                int ValidTable = x;                                              // Save the Tablenumber
                (db_Br+i_Which)->OnSelect(Table,false);                          // Select * from "table"
                // Set the local Pointer to the Column Information we are going to use
                (db_Br+i_Which)->cl_BrowserDB = (ct_BrowserDB->pTableInf+x)->pColInf;
                if ((ct_BrowserDB->pTableInf+x)->pColInf)                        // Valid pointer (!= NULL) ?
                {   // Pointer is Valid, Column Informationen sind Vorhanden
                    int i = (db_Br+i_Which)->i_Records;                             // How many Records are there
                    (db_Br+i_Which)->i_Which = ValidTable;                          // Still used ???? mj10777
                    if (i == 0)     // If the Table is empty, then show one empty row
                        i++;
                    // wxLogMessage(_("\n-I-> DBGrid::OnTableView() : Vor CreateGrid"));
                    CreateGrid(i,(ct_BrowserDB->pTableInf+x)->numCols);             // Records , Columns
                    for (y=0;y<(ct_BrowserDB->pTableInf+x)->numCols;y++)            // Loop through the Fields
                    {  // The Field / Column name is used here as Row Titel
                        SetColLabelValue(y,((ct_BrowserDB->pTableInf+x)->pColInf+y)->colName);
                        SetColSize(y,95);
                    }  // for (y=0;y<(ct_BrowserDB->pTableInf+x)->numCols;y++)
                    SetColSize(((ct_BrowserDB->pTableInf+x)->numCols-1),120);       // Make the last Column Wider
                    // The Grid has been created, now fill it
                    for (z=0;z<(db_Br+i_Which)->i_Records;z++)                      // Loop through the Records
                    {
                        Temp0.Printf(_T("%06d"),z+1);  SetRowLabelValue(z,Temp0);          // Set Row Lable Value
                        (db_Br+i_Which)->OnGetNext((ct_BrowserDB->pTableInf+ValidTable)->numCols,false);
                        for (y=0;y<(ct_BrowserDB->pTableInf+ValidTable)->numCols;y++) // Loop through the Fields
                        { // BrowserDB::OnGetNext Formats the field Value into tablename
                            SetCellValue(z, y,((db_Br+i_Which)->cl_BrowserDB+y)->tableName);
                        }
#if wxUSE_STATUSBAR
                        if (z % 50 == 0)
                        {
                            Temp0.Printf(_("-I-> DBGrid::OnTableView(%s) - Record %6d (from %d) has been read."),Table.c_str(),z,(db_Br+i_Which)->i_Records);
                            pDoc->p_MainFrame->SetStatusText(Temp0, 0);
                        }
#endif // wxUSE_STATUSBAR
                    }  // for (z=0;z<(db_Br+i_Which)->i_Records;z++)
                    Temp0.Printf(_("-I-> DBGrid::OnTableView(%s) - %6d Records have been read. - Time needed : %ld ms"),Table.c_str(),z,sw.Time());
                    wxLogMessage(Temp0);
#if wxUSE_STATUSBAR
                    pDoc->p_MainFrame->SetStatusText(Temp0, 0);
#endif // wxUSE_STATUSBAR
                    // The Grid has been filled, now leave
                    goto Weiter;
                }   // if ((ct_BrowserDB->pTableInf+x)->pColInf)
                else
                    wxLogMessage(_("\n-E-> DBGrid::OnTableView() : Invalid Column Pointer : Failed"));
            }    // if ((ct_BrowserDB->pTableInf+x)->tableType == "TABLE")
        }     // for (x=0;x<ct_BrowserDB->numTables;x++)
    }      // if (ct_BrowserDB)
    else
        wxLogMessage(_("\n-E-> DBGrid::OnTableView() : Invalid DSN Pointer : Failed"));
    //---------------------------------------------------------------------------------------
Weiter:
    EnableEditing(b_EditModus);     // Deactivate in-place Editing
    wxEndBusyCursor();
    //---------------------------------------------------------------------------------------
    wxLogMessage(_("-I-> DBGrid::OnTableView() - End"));
    return 0;
}
Esempio n. 15
0
int IfaceCheckApp::OnRun()
{
    long startTime = wxGetLocalTime();      // for timing purpose

    wxCmdLineParser parser(g_cmdLineDesc, argc, argv);
    parser.SetLogo(
        wxString::Format("wxWidgets Interface checker utility (built %s against %s)",
                         __DATE__, wxVERSION_STRING));

    // make the output more readable:
    wxLog::SetActiveTarget(new IfaceCheckLog);
    wxLog::DisableTimestamp();

    // parse the command line...
    bool ok = true;
    wxString preprocFile;
    switch (parser.Parse())
    {
        case 0:
            if (parser.Found(VERBOSE_SWITCH))
                g_verbose = true;

            // IMPORTANT: parsing #define values must be done _before_ actually
            //            parsing the GCC/doxygen XML files
            if (parser.Found(USE_PREPROCESSOR_OPTION, &preprocFile))
            {
                if (!ParsePreprocessorOutput(preprocFile))
                    return 1;
            }

            // in any case set basic std preprocessor #defines:
            m_doxyInterface.AddPreprocessorValue("NULL", "0");

            // parse the two XML files which contain the real and the doxygen interfaces
            // for wxWidgets API:
            if (!m_gccInterface.Parse(parser.GetParam(0)) ||
                !m_doxyInterface.Parse(parser.GetParam(1)))
                return 1;

            if (parser.Found(DUMP_SWITCH))
            {
                wxLogMessage("Dumping real API to '%s'...", API_DUMP_FILE);
                m_gccInterface.Dump(API_DUMP_FILE);

                wxLogMessage("Dumping interface API to '%s'...", INTERFACE_DUMP_FILE);
                m_doxyInterface.Dump(INTERFACE_DUMP_FILE);
            }
            else
            {
                if (parser.Found(MODIFY_SWITCH))
                    m_modify = true;

                if (parser.Found(PROCESS_ONLY_OPTION, &m_strToMatch))
                {
                    size_t len = m_strToMatch.Len();
                    if (m_strToMatch.StartsWith("\"") &&
                        m_strToMatch.EndsWith("\"") &&
                        len > 2)
                        m_strToMatch = m_strToMatch.Mid(1, len-2);
                }


                ok = Compare();
            }

            PrintStatistics(wxGetLocalTime() - startTime);
            return ok ? 0 : 1;

        default:
            wxPrintf("\nThis utility checks that the interface XML files created by Doxygen are in\n");
            wxPrintf("synch with the real headers (whose contents are extracted by the gcc XML file).\n\n");
            wxPrintf("The 'gccXML' parameter should be the wxapi.xml file created by the 'rungccxml.sh'\n");
            wxPrintf("script which resides in 'utils/ifacecheck'.\n");
            wxPrintf("The 'doxygenXML' parameter should be the index.xml file created by Doxygen\n");
            wxPrintf("for the wxWidgets 'interface' folder.\n\n");
            wxPrintf("Since the gcc XML file does not contain info about #defines, if you use\n");
            wxPrintf("the -%s option, you'll get a smaller number of false warnings.\n",
                     USE_PREPROCESSOR_OPTION);

            // HELP_SWITCH was passed or a syntax error occurred
            return 0;
    }
}
bool CStarNetHandler::logoff(const wxString &callsign)
{
	if (callsign.IsSameAs(wxT("ALL     "))) {
		for (CStarNetUsersHashMap::iterator it = m_users.begin(); it != m_users.end(); ++it)
			delete it->second;
		for (CStarNetIdsHashMap::iterator it = m_ids.begin(); it != m_ids.end(); ++it)
			delete it->second;
		for (CStarNetRepeatersHashMap::iterator it = m_repeaters.begin(); it != m_repeaters.end(); ++it)
			delete it->second;

		m_users.clear();
		m_ids.clear();
		m_repeaters.end();

		m_groupTimer.stop();
		m_id = 0x00U;

		return true;
	} else {
		CStarNetUser* user = m_users[callsign];
		if (user == NULL) {
			wxLogMessage(wxT("Invalid callsign asked to logoff"));
			return false;
		}

		// Find any associated id structure associated with this use, and the logged off user is the
		// currently relayed one, remove his id.
		for (CStarNetIdsHashMap::iterator it = m_ids.begin(); it != m_ids.end(); ++it) {
			CStarNetId* id = it->second;
			if (id != NULL && id->getUser() == user) {
				if (id->getId() == m_id)
					m_id = 0x00U;

				m_ids.erase(it);
				delete id;
				break;
			}
		}

		m_users.erase(callsign);
		delete user;

		// Check to see if we have any users left
		unsigned int count = 0U;
		for (CStarNetUsersHashMap::iterator it = m_users.begin(); it != m_users.end(); ++it) {
			if (it->second != NULL)
				count++;
		}

		// If none then clear all the data structures
		if (count == 0U) {
			for (CStarNetUsersHashMap::iterator it = m_users.begin(); it != m_users.end(); ++it)
				delete it->second;
			for (CStarNetIdsHashMap::iterator it = m_ids.begin(); it != m_ids.end(); ++it)
				delete it->second;
			for (CStarNetRepeatersHashMap::iterator it = m_repeaters.begin(); it != m_repeaters.end(); ++it)
				delete it->second;

			m_users.clear();
			m_ids.clear();
			m_repeaters.end();

			m_groupTimer.stop();
			m_id = 0x00U;
		}

		return true;
	}
}
Esempio n. 17
0
bool IfaceCheckApp::Compare()
{
    const wxClassArray& interfaces = m_doxyInterface.GetClasses();
    const wxClass* c;
    int mcount = 0, ccount = 0;

    wxLogMessage("Comparing the interface API to the real API (%d classes to compare)...",
                 interfaces.GetCount());

    if (!m_strToMatch.IsEmpty())
    {
        wxLogMessage("Processing only header files matching '%s' expression.", m_strToMatch);
    }

#if defined(__INTEL_COMPILER) && 1 /* VDM auto patch */
#   pragma ivdep
#   pragma swp
#   pragma unroll
#   pragma prefetch
#   if 0
#       pragma simd noassert
#   endif
#endif /* VDM auto patch */
    for (unsigned int i=0; i<interfaces.GetCount(); i++)
    {
        // only compare the methods which are available for the port
        // for which the gcc XML was produced
        if (interfaces[i].GetAvailability() != wxPORT_UNKNOWN &&
            (interfaces[i].GetAvailability() & m_gccInterface.GetInterfacePort()) == 0) {

            if (g_verbose)
            {
                wxLogMessage("skipping class '%s' since it's not available for the %s port.",
                           interfaces[i].GetName(), m_gccInterface.GetInterfacePortName());
            }

            continue;       // skip this method
        }

        // shorten the name of the header so the log file is more readable
        // and also for calling IsToProcess() against it
        wxString header = wxFileName(interfaces[i].GetHeader()).GetFullName();

        if (!IsToProcess(header))
            continue;       // skip this one

        wxString cname = interfaces[i].GetName();

        // search in the real headers for i-th interface class; we search for
        // both class cname and cnameBase since in wxWidgets world tipically
        // class cname is platform-specific while the real public interface of
        // that class is part of the cnameBase class.
        /*c = m_gccInterface.FindClass(cname + "Base");
        if (c) api.Add(c);*/

        c = m_gccInterface.FindClass(cname);
        if (!c)
        {
            // sometimes the platform-specific class is named "wxGeneric" + cname
            // or similar:
            c = m_gccInterface.FindClass("wxGeneric" + cname.Mid(2));
            if (!c)
            {
                c = m_gccInterface.FindClass("wxGtk" + cname.Mid(2));
            }
        }

        if (c) {

            // there is a class with the same (logic) name!
            mcount += CompareClasses(&interfaces[i], c);

        } else {

            wxLogMessage("%s: couldn't find the real interface for the '%s' class",
                       header, cname);
            ccount++;
        }
    }

    wxLogMessage("%d on a total of %d methods (%.1f%%) of the interface headers do not exist in the real headers",
               mcount, m_doxyInterface.GetMethodCount(), (float)(100.0 * mcount/m_doxyInterface.GetMethodCount()));
    wxLogMessage("%d on a total of %d classes (%.1f%%) of the interface headers do not exist in the real headers",
               ccount, m_doxyInterface.GetClassesCount(), (float)(100.0 * ccount/m_doxyInterface.GetClassesCount()));

    return true;
}
Esempio n. 18
0
/* GZipArchive::open
 * Reads gzip format data from a MemChunk
 * Returns true if successful, false otherwise
 *******************************************************************/
bool GZipArchive::open(MemChunk& mc)
{
	// Minimal metadata size is 18: 10 for header, 8 for footer
	size_t mds = 18;
	size_t size = mc.getSize();
	if (mds > size)
		return false;

	// Read header
	uint8_t header[4];
	mc.read(header, 4);

	// Check for GZip header; we'll only accept deflated gzip files
	// and reject any field using unknown flags
	if ((!(header[0] == GZIP_ID1 && header[1] == GZIP_ID2 && header[2] == GZIP_DEFLATE))
	        || (header[3] & GZIP_FLG_FUNKN))
		return false;

	bool ftext, fhcrc, fxtra, fname, fcmnt;
	ftext = (header[3] & GZIP_FLG_FTEXT) ? true : false;
	fhcrc = (header[3] & GZIP_FLG_FHCRC) ? true : false;
	fxtra = (header[3] & GZIP_FLG_FXTRA) ? true : false;
	fname = (header[3] & GZIP_FLG_FNAME) ? true : false;
	fcmnt = (header[3] & GZIP_FLG_FCMNT) ? true : false;
	flags = header[3];

	mc.read(&mtime, 4);
	mtime = wxUINT32_SWAP_ON_BE(mtime);

	mc.read(&xfl, 1);
	mc.read(&os, 1);

	// Skip extra fields which may be there
	if (fxtra)
	{
		uint16_t xlen;
		mc.read(&xlen, 2);
		xlen = wxUINT16_SWAP_ON_BE(xlen);
		mds += xlen + 2;
		if (mds > size)
			return false;
		mc.exportMemChunk(xtra, mc.currentPos(), xlen);
		mc.seek(xlen, SEEK_CUR);
	}

	// Skip past name, if any
	string name;
	if (fname)
	{
		char c;
		do
		{
			mc.read(&c, 1);
			if (c) name += c;
			++mds;
		}
		while (c != 0 && size > mds);
	}
	else
	{
		// Build name from filename
		name = getFilename(false);
		wxFileName fn(name);
		if (!fn.GetExt().CmpNoCase("tgz"))
			fn.SetExt("tar");
		else if (!fn.GetExt().CmpNoCase("gz"))
			fn.ClearExt();
		name = fn.GetFullName();
	}

	// Skip past comment
	if (fcmnt)
	{
		char c;
		do
		{
			mc.read(&c, 1);
			if (c) comment += c;
			++mds;
		}
		while (c != 0 && size > mds);
		wxLogMessage("Archive %s says:\n %s", getFilename(true), comment);
	}

	// Skip past CRC 16 check
	if (fhcrc)
	{
		uint8_t* crcbuffer = new uint8_t[mc.currentPos()];
		memcpy(crcbuffer, mc.getData(), mc.currentPos());
		uint32_t fullcrc = Misc::crc(crcbuffer, mc.currentPos());
		delete[] crcbuffer;
		uint16_t hcrc;
		mc.read(&hcrc, 2);
		hcrc = wxUINT16_SWAP_ON_BE(hcrc);
		mds += 2;
		if (hcrc  != (fullcrc & 0x0000FFFF))
		{
			wxLogMessage("CRC-16 mismatch for GZip header");
		}
	}

	// Header is over
	if (mds > size || mc.currentPos() + 8 > size)
		return false;

	// Let's create the entry
	setMuted(true);
	ArchiveEntry* entry = new ArchiveEntry(name, size - mds);
	MemChunk  xdata;
	if (Compression::GZipInflate(mc, xdata))
	{
		entry->importMemChunk(xdata);
	}
	else
	{
		delete entry;
		setMuted(false);
		return false;
	}
	getRoot()->addEntry(entry);
	EntryType::detectEntryType(entry);
	entry->setState(0);

	setMuted(false);
	setModified(false);
	announce("opened");

	// Finish
	return true;
}
Esempio n. 19
0
bool IfaceCheckApp::FixMethod(const wxString& header, const wxMethod* iface, const wxMethod* api)
{
    unsigned int i,j;
    wxASSERT(iface && api);

    wxTextFile file;
    if (!file.Open(header)) {
        wxLogError("\tcan't open the '%s' header file.", header);
        return false;
    }

    // GetLocation() returns the line where the last part of the prototype is placed;
    // i.e. the line containing the semicolon at the end of the declaration.
    int end = iface->GetLocation()-1;
    if (end <= 0 || end >= (int)file.GetLineCount()) {
        wxLogWarning("\tinvalid location info for method '%s': %d.",
                   iface->GetAsString(), iface->GetLocation());
        return false;
    }

    if (!file.GetLine(end).Contains(";")) {
        wxLogWarning("\tinvalid location info for method '%s': %d.",
                   iface->GetAsString(), iface->GetLocation());
        return false;
    }

    // is this a one-line prototype declaration?
    bool founddecl = false;
    int start;
    if (StringContainsMethodName(file.GetLine(end), iface))
    {
        // yes, this prototype is all on this line:
        start = end;
        founddecl = true;
    }
    else
    {
        start = end;    // will be decremented inside the while{} loop below

        // find the start point of this prototype declaration; i.e. the line
        // containing the function name, which is also the line following
        // the marker '*/' for the closure of the doxygen comment
#if defined(__INTEL_COMPILER) && 1 /* VDM auto patch */
#   pragma ivdep
#   pragma swp
#   pragma unroll
#   pragma prefetch
#   if 0
#       pragma simd noassert
#   endif
#endif /* VDM auto patch */
        do
        {
            start--;        // go up one line

            if (StringContainsMethodName(file.GetLine(start), iface))
                founddecl = true;
        }
#if defined(__INTEL_COMPILER) && 0 /* VDM auto patch */
#   pragma ivdep
#   pragma swp
#   pragma unroll
#   pragma prefetch
#   if 0
#       pragma simd noassert
#   endif
#endif /* VDM auto patch */
        while (start > 0 && !founddecl &&
               !file.GetLine(start).Contains(";") &&
               !file.GetLine(start).Contains("*/"));
    }

    if (start <= 0 || !founddecl)
    {
        wxLogError("\tcan't find the beginning of the declaration of '%s' method in '%s' header looking backwards from line %d; I arrived at %d and gave up",
                 iface->GetAsString(), header, end+1 /* zero-based => 1-based */, start);
        return false;
    }

    // remove the old prototype
#if defined(__INTEL_COMPILER) && 1 /* VDM auto patch */
#   pragma ivdep
#   pragma swp
#   pragma unroll
#   pragma prefetch
#   if 0
#       pragma simd noassert
#   endif
#endif /* VDM auto patch */
    for (int k=start; k<=end; k++)
        file.RemoveLine(start);     // remove (end-start)-nth times the start-th line

#define INDENTATION_STR  wxString("    ")

    // if possible, add also the @deprecated tag in the doxygen comment if it's missing
    int deprecationOffset = 0;
    if (file.GetLine(start-1).Contains("*/") &&
        (api->IsDeprecated() && !iface->IsDeprecated()))
    {
        file.RemoveLine(start-1);
        file.InsertLine(INDENTATION_STR + INDENTATION_STR +
                        "@deprecated @todo provide deprecation description", start-1);
        file.InsertLine(INDENTATION_STR + "*/", start++);

        // we have added a new line in the final balance
        deprecationOffset=1;
    }

    wxMethod tmp(*api);

    // discard gcc XML argument names and replace them with those parsed from doxygen XML;
    // in this way we should avoid introducing doxygen warnings about cases where the argument
    // 'xx' of the prototype is called 'yy' in the function's docs.
    const wxArgumentTypeArray& doxygenargs = iface->GetArgumentTypes();
    const wxArgumentTypeArray& realargs = api->GetArgumentTypes();
    if (realargs.GetCount() == doxygenargs.GetCount())
    {
#if defined(__INTEL_COMPILER) && 1 /* VDM auto patch */
#   pragma ivdep
#   pragma swp
#   pragma unroll
#   pragma prefetch
#   if 0
#       pragma simd noassert
#   endif
#endif /* VDM auto patch */
        for (j=0; j<doxygenargs.GetCount(); j++)
            if (doxygenargs[j]==realargs[j])
            {
                realargs[j].SetArgumentName(doxygenargs[j].GetArgumentName());

                if (realargs[j].GetDefaultValue().IsNumber() &&
                    doxygenargs[j].GetDefaultValue().StartsWith("wx"))
                    realargs[j].SetDefaultValue(doxygenargs[j].GetDefaultValue());
            }

        tmp.SetArgumentTypes(realargs);
    }

#define WRAP_COLUMN     80

    wxArrayString toinsert;
    toinsert.Add(INDENTATION_STR + tmp.GetAsString() + ";");

    int nStartColumn = toinsert[0].Find('(');
    wxASSERT(nStartColumn != wxNOT_FOUND);

    // wrap lines too long at comma boundaries
#if defined(__INTEL_COMPILER) && 1 /* VDM auto patch */
#   pragma ivdep
#   pragma swp
#   pragma unroll
#   pragma prefetch
#   if 0
#       pragma simd noassert
#   endif
#endif /* VDM auto patch */
    for (i=0; i<toinsert.GetCount(); i++)
    {
        size_t len = toinsert[i].Len();
        if (len > WRAP_COLUMN)
        {
            wxASSERT(i == toinsert.GetCount()-1);

            // break this line
            wxString tmpleft = toinsert[i].Left(WRAP_COLUMN);
            int comma = tmpleft.Find(',', true /* from end */);
            if (comma == wxNOT_FOUND)
                break;     // break out of the for cycle...

            toinsert.Add(wxString(' ', nStartColumn+1) +
                         toinsert[i].Right(len-comma-2));   // exclude the comma and the space after it
            toinsert[i] = tmpleft.Left(comma+1);            // include the comma
        }
    }

    // insert the new lines
#if defined(__INTEL_COMPILER) && 1 /* VDM auto patch */
#   pragma ivdep
#   pragma swp
#   pragma unroll
#   pragma prefetch
#   if 0
#       pragma simd noassert
#   endif
#endif /* VDM auto patch */
    for (i=0; i<toinsert.GetCount(); i++)
        file.InsertLine(toinsert[i], start+i);

    // now save the modification
    if (!file.Write()) {
        wxLogError("\tcan't save the '%s' header file.", header);
        return false;
    }

    // how many lines did we add/remove in total?
    int nOffset = toinsert.GetCount() + deprecationOffset - (end-start+1);
    if (nOffset == 0)
        return false;

    if (g_verbose)
    {
        wxLogMessage("\tthe final row offset for following methods is %d lines.", nOffset);
    }

    // update the other method's locations for those methods which belong to the modified header
    // and are placed _below_ the modified method
    wxClassPtrArray cToUpdate = m_doxyInterface.FindClassesDefinedIn(header);
#if defined(__INTEL_COMPILER) && 1 /* VDM auto patch */
#   pragma ivdep
#   pragma swp
#   pragma unroll
#   pragma prefetch
#   if 0
#       pragma simd noassert
#   endif
#endif /* VDM auto patch */
    for (i=0; i < cToUpdate.GetCount(); i++)
    {
#if defined(__INTEL_COMPILER) && 1 /* VDM auto patch */
#   pragma ivdep
#   pragma swp
#   pragma unroll
#   pragma prefetch
#   if 0
#       pragma simd noassert
#   endif
#endif /* VDM auto patch */
        for (j=0; j < cToUpdate[i]->GetMethodCount(); j++)
        {
            wxMethod& m = cToUpdate[i]->GetMethod(j);
            if (m.GetLocation() > iface->GetLocation())
            {
                // update the location of this method
                m.SetLocation(m.GetLocation()+nOffset);
            }
        }
    }

    return true;
}
Esempio n. 20
0
/**
 * Évènement/Non implémenté - Modifie le mode d'affichage des titres : titre du fichier ou données incorporées (TAG)
 */
void PreferenceDefaut::Defaut_CheckBoxTAG(wxCommandEvent &WXUNUSED(event))
{
    wxLogMessage(_("Non implémenté - Tag"));
    //AutoSave();
}
Esempio n. 21
0
// 'Main program' equivalent: the program execution "starts" here
bool wxEmulatorApp::OnInit()
{
#if wxUSE_LOG
    wxLog::SetTimestamp(NULL);
#endif // wxUSE_LOG
    wxInitAllImageHandlers();

    wxString currentDir = wxGetCwd();

    // Use argv to get current app directory
    m_appDir = wxFindAppPath(argv[0], currentDir, wxT("WXEMUDIR"));

    // If the development version, go up a directory.
#ifdef __WXMSW__
    if ((m_appDir.Right(5).CmpNoCase(_T("DEBUG")) == 0) ||
        (m_appDir.Right(11).CmpNoCase(_T("DEBUGSTABLE")) == 0) ||
        (m_appDir.Right(7).CmpNoCase(_T("RELEASE")) == 0) ||
        (m_appDir.Right(13).CmpNoCase(_T("RELEASESTABLE")) == 0)
        )
        m_appDir = wxPathOnly(m_appDir);
#endif

    // Parse the command-line parameters and options
    wxCmdLineParser parser(sg_cmdLineDesc, argc, argv);
    int res;
    {
        wxLogNull log;
        res = parser.Parse();
    }
    if (res == -1 || res > 0 || parser.Found(wxT("h")))
    {
#ifdef __X__
        wxLog::SetActiveTarget(new wxLogStderr);
#endif
        parser.Usage();
        return false;
    }
    if (parser.Found(wxT("v")))
    {
#ifdef __X__
        wxLog::SetActiveTarget(new wxLogStderr);
#endif
        wxString msg;
        msg.Printf(wxT("wxWidgets PDA Emulator (c) Julian Smart, 2002 Version %.2f, %s"), wxEMULATOR_VERSION, __DATE__);
        wxLogMessage(msg);
        return false;
    }
    if (parser.Found(wxT("u"), & m_displayNumber))
    {
        // Should only be number, so strip out anything before
        // and including a : character
        if (m_displayNumber.Find(wxT(':')) != -1)
        {
            m_displayNumber = m_displayNumber.AfterFirst(wxT(':'));
        }
    }
    if (parser.GetParamCount() == 0)
    {
        m_emulatorInfo.m_emulatorFilename = wxT("default.wxe");
    }
    else if (parser.GetParamCount() > 0)
    {
        m_emulatorInfo.m_emulatorFilename = parser.GetParam(0);
    }

    // Load the emulation info
    if (!LoadEmulator(m_appDir))
    {
        //wxMessageBox(wxT("Sorry, could not load this emulator. Please check bitmaps are valid."));
        return false;
    }

    // create the main application window
    wxEmulatorFrame *frame = new wxEmulatorFrame(_T("wxEmulator"),
                                 wxPoint(50, 50), wxSize(450, 340));

#if wxUSE_STATUSBAR
    frame->SetStatusText(m_emulatorInfo.m_emulatorTitle, 0);

    wxString sizeStr;
    sizeStr.Printf(wxT("Screen: %dx%d"), (int) m_emulatorInfo.m_emulatorScreenSize.x,
            (int) m_emulatorInfo.m_emulatorScreenSize.y);
    frame->SetStatusText(sizeStr, 1);
#endif // wxUSE_STATUSBAR

    m_containerWindow = new wxEmulatorContainer(frame, wxID_ANY);

    frame->SetClientSize(m_emulatorInfo.m_emulatorDeviceSize.x,
                         m_emulatorInfo.m_emulatorDeviceSize.y);

    // and show it (the frames, unlike simple controls, are not shown when
    // created initially)
    frame->Show(true);

#ifdef __WXX11__
    m_xnestWindow = new wxAdoptedWindow;

    wxString cmd;
    cmd.Printf(wxT("Xnest :%s -geometry %dx%d"),
        m_displayNumber.c_str(),
        (int) m_emulatorInfo.m_emulatorScreenSize.x,
        (int) m_emulatorInfo.m_emulatorScreenSize.y);

    // Asynchronously executes Xnest
    m_xnestPID = wxExecute(cmd);
    if (0 == m_xnestPID)
    {
        frame->Destroy();
        wxMessageBox(wxT("Sorry, could not run Xnest. Please check your PATH."));
        return false;
    }

    wxReparenter reparenter;
    if (!reparenter.WaitAndReparent(m_containerWindow, m_xnestWindow, wxT("Xnest")))
    {
        wxMessageBox(wxT("Sorry, could not reparent Xnest.."));
        frame->Destroy();
        return false;
    }

#endif
    m_containerWindow->DoResize();

    // success: wxApp::OnRun() will be called which will enter the main message
    // loop and the application will run. If we returned false here, the
    // application would exit immediately.
    return true;
}
Esempio n. 22
0
/**
 * Évènement/Non implémenté - Modifie la Base de Registre (BDR de Windows) pour mettre Fu(X) en application par défaut
 */
void PreferenceDefaut::Defaut_CheckBoxDefautBDR(wxCommandEvent &WXUNUSED(event))
{
    wxLogMessage(_("Non implémenté - Application par défaut"));
    //AutoSave();
}
Esempio n. 23
0
/// Check TrueType font file whether font license allows embedding
void
MakeFont::CheckTTF(const wxString& fileName, bool& embeddingAllowed, bool& subsettingAllowed, int& cffOffset, int& cffLength)
{
  embeddingAllowed = false;
  subsettingAllowed = false;
  cffOffset = -1;
  cffLength = 0;
  if (fileName.Length() == 0)
  {
    return;
  }
  wxFileInputStream ttfFile(fileName);
  if (!ttfFile.Ok())
  {
    // Can't open file
    wxLogMessage(wxT("Error: Unable to read font file '") + fileName + wxT("'."));
    return;
  }
  // Extract number of tables
  ttfFile.SeekI(0, wxFromCurrent);
  int id = ReadInt(&ttfFile);
  if (id != 0x00010000 && id != 0x4f54544f)
  {
    wxLogError(wxT("Error: File '") + fileName + wxT("' is not a valid font file."));
    return;
  }
  short nb = ReadShort(&ttfFile);
  ttfFile.SeekI(6, wxFromCurrent);
  // Seek OS/2 table
  bool found = false;
  int offset = 0;
  int i;
  for (i = 0; i < nb; i++)
  {
    char buffer[4];
    ttfFile.Read(buffer,4);
    if (strncmp(buffer,"OS/2",4) == 0)
    {
      found = true;
      ttfFile.SeekI(4, wxFromCurrent);
      offset = ReadInt(&ttfFile);
      ttfFile.SeekI(4, wxFromCurrent);
    }
    else if (strncmp(buffer,"CFF ",4) == 0)
    {
      ttfFile.SeekI(4, wxFromCurrent);
      cffOffset = ReadInt(&ttfFile);
      cffLength = ReadInt(&ttfFile);
    }
    else
    {
      ttfFile.SeekI(12, wxFromCurrent);
    }
  }
  if (!found)
  {
    return;
  }
  ttfFile.SeekI(offset, wxFromStart);
  // Extract fsType flags
  ttfFile.SeekI(8, wxFromCurrent);
  short fsType = ReadShort(&ttfFile);
  bool rl = (fsType & 0x02) != 0;
  bool pp = (fsType & 0x04) != 0;
  bool e  = (fsType & 0x08) != 0;
  bool ns = (fsType & 0x0100) != 0;
  bool eb = (fsType & 0x0200) != 0;
  embeddingAllowed = !(rl && !pp && !e) && !eb;
  subsettingAllowed = !ns;
}
Esempio n. 24
0
/**
 * Évènement/Non implémenté - Lance l'ouverture d'une fenêtre pour sélectionner le répertoire devant être ouvert lors d'une recherche
 */
void PreferenceDefaut::Defaut_Bouton_CheminDefaut(wxCommandEvent &WXUNUSED(event))
{
    wxLogMessage(_("Non implémenté - Répertoire par défaut"));
    //AutoSave();
}
Esempio n. 25
0
bool ChatPanel::Say( const wxString& message )
{
	static const unsigned int flood_threshold = 5;
	wxLogDebugFunc( message );
	wxStringTokenizer lines( message, _T( '\n' ) );
	if ( lines.CountTokens() > flood_threshold ) {
		PasteDialog dl ( this, wxString::Format(
			_( "Are you sure you want to paste %d lines?" ), lines.CountTokens() ) );
		switch ( dl.ShowModal() ) {
			case wxID_NO :
				return true;
			case PasteDialog::pasteButtonReturnCode : {
				wxString url = Paste2Pastebin( message );
				if ( url != wxEmptyString && wxStringTokenizer( url, _T( '\n' )).CountTokens() <= flood_threshold ) {
					Say( url );
					return true;
				}
				else {
					customMessageBoxNoModal( SL_MAIN_ICON, _("Failed to post to pastebin.com.") );
					return false;
				}
			}
			default:
				break;
		}
	}
	while ( lines.HasMoreTokens() ) {
		wxString line = lines.GetNextToken();
		wxLogMessage( _T( "line: %s" ), line.c_str() );

		if ( line.Find( '/' ) == 0 ) {
			if ( ui().ExecuteSayCommand( line ) ) return true;
		}

		if ( line == _T( "/ver" ) ) {
			//!this instance is not replaced with GetAppname for sake of help/debug online
			OutputLine( _( " You have SpringLobby v" ) + GetSpringLobbyVersion(), sett().GetChatColorNormal() , sett().GetChatFont() );
			return true;
		}

		if ( line == _T( "/clear" ) ) {
            m_chatlog_text->SetValue( _T("") );
			return true;
		}

		if ( m_type == CPT_Channel ) {

			if ( m_channel == 0 ) {
				OutputLine( _( " You are not in channel or channel does not exist." ), sett().GetChatColorError(), sett().GetChatFont() );
				return true;
			}
			if ( line.StartsWith( _T( "/" ) ) ) {
				if ( m_channel->ExecuteSayCommand( line ) ) return true;
				if ( m_channel->GetServer().ExecuteSayCommand( line ) ) return true;
				OutputLine( wxString::Format( _( " Error: Command (%s) does not exist, use /help for a list of available commands." ), line.c_str() ), sett().GetChatColorError(), sett().GetChatFont() );
				return true;
			}
			m_channel->Say( line );

		} else if ( m_type == CPT_Battle ) {

			if ( m_battle == 0 ) {
				OutputLine( _( " You are not in battle or battle does not exist, use /help for a list of available commands." ), sett().GetChatColorError(), sett().GetChatFont() );
				return true;
			}
			if ( line.StartsWith( _T( "/" ) ) ) {
				if ( m_battle->ExecuteSayCommand( line ) ) return true;
				if ( m_battle->GetServer().ExecuteSayCommand( line ) ) return true;
				OutputLine( wxString::Format( _( " Error: Command (%s) does not exist, use /help for a list of available commands." ), line.c_str() ), sett().GetChatColorError(), sett().GetChatFont() );
				return true;
			}
			m_battle->Say( line );

		} else if ( m_type == CPT_User ) {

			if ( m_user == 0 ) {
				OutputLine( _( " User is offline." ), sett().GetChatColorError(), sett().GetChatFont() );
				return true;
			}
			if ( line.StartsWith( _T( "/" ) ) ) {
				if ( m_user->ExecuteSayCommand( line ) ) return true;
				if ( m_user->GetServer().ExecuteSayCommand( line ) ) return true;
				OutputLine( wxString::Format( _( " Error: Command (%s) does not exist, use /help for a list of available commands." ), line.c_str() ), sett().GetChatColorError(), sett().GetChatFont() );
				return true;
			}
			m_user->Say( line );

		} else if ( m_type == CPT_Server ) {
			if ( m_server == 0 ) return true;

			if ( line.StartsWith( _T( "/" ) ) ) {
				if ( m_server->ExecuteSayCommand( line ) ) return true;
				OutputLine( wxString::Format( _( " Error: Command (%s) does not exist, use /help for a list of available commands." ), line.c_str() ), sett().GetChatColorError(), sett().GetChatFont() );
				return true;
			}

            //we need to disable the channel tab if leaving manually
            if (line.Upper().StartsWith( _T( "LEAVE" ) ) )
            {
                wxString channame = line.AfterFirst(' ').BeforeFirst(' ');
                try
                {
									Channel& chan = m_server->GetChannel( channame );
									chan.Leave();
									chan.uidata.panel = 0;
								}
								catch( assert_exception ) {}
            }

			m_server->SendRaw( line );
			OutputLine( _( " Sent: \"" ) + line + _( "\"" ), sett().GetChatColorNormal(), sett().GetChatFont() );
		}
	}
	return true;
}
Esempio n. 26
0
void MODULE::Copy( MODULE* aModule )
{
    m_Pos           = aModule->m_Pos;
    m_Layer         = aModule->m_Layer;
    m_fpid          = aModule->m_fpid;
    m_Attributs     = aModule->m_Attributs;
    m_ModuleStatus  = aModule->m_ModuleStatus;
    m_Orient        = aModule->m_Orient;
    m_BoundaryBox   = aModule->m_BoundaryBox;
    m_CntRot90      = aModule->m_CntRot90;
    m_CntRot180     = aModule->m_CntRot180;
    m_LastEditTime  = aModule->m_LastEditTime;
    m_Link          = aModule->m_Link;
    m_Path          = aModule->m_Path; //is this correct behavior?
    SetTimeStamp( GetNewTimeStamp() );

    m_LocalClearance                = aModule->m_LocalClearance;
    m_LocalSolderMaskMargin         = aModule->m_LocalSolderMaskMargin;
    m_LocalSolderPasteMargin        = aModule->m_LocalSolderPasteMargin;
    m_LocalSolderPasteMarginRatio   = aModule->m_LocalSolderPasteMarginRatio;
    m_ZoneConnection                = aModule->m_ZoneConnection;
    m_ThermalWidth                  = aModule->m_ThermalWidth;
    m_ThermalGap                    = aModule->m_ThermalGap;

    // Copy reference and value.
    m_Reference->Copy( aModule->m_Reference );
    m_Value->Copy( aModule->m_Value );

    // Copy auxiliary data: Pads
    m_Pads.DeleteAll();

    for( D_PAD* pad = aModule->m_Pads;  pad;  pad = pad->Next() )
    {
        D_PAD* newpad = new D_PAD( this );
        newpad->Copy( pad );
        m_Pads.PushBack( newpad );
    }

    // Copy auxiliary data: Drawings
    m_Drawings.DeleteAll();

    for( BOARD_ITEM* item = aModule->m_Drawings;  item;  item = item->Next() )
    {
        switch( item->Type() )
        {
        case PCB_MODULE_TEXT_T:
        {
            TEXTE_MODULE* textm = new TEXTE_MODULE( this );
            textm->Copy( static_cast<TEXTE_MODULE*>( item ) );
            m_Drawings.PushBack( textm );
            break;
        }

        case PCB_MODULE_EDGE_T:
        {
            EDGE_MODULE * edge;
            edge = new EDGE_MODULE( this );
            edge->Copy( (EDGE_MODULE*) item );
            m_Drawings.PushBack( edge );
            break;
        }

        default:
            wxLogMessage( wxT( "MODULE::Copy() Internal Err:  unknown type" ) );
            break;
        }
    }

    // Copy auxiliary data: 3D_Drawings info
    m_3D_Drawings.DeleteAll();

    // Ensure there is one (or more) item in m_3D_Drawings
    m_3D_Drawings.PushBack( new S3D_MASTER( this ) ); // push a void item

    for( S3D_MASTER* item = aModule->m_3D_Drawings;  item;  item = item->Next() )
    {
        if( item->GetShape3DName().IsEmpty() )           // do not copy empty shapes.
            continue;

        S3D_MASTER* t3d = m_3D_Drawings;

        if( t3d && t3d->GetShape3DName().IsEmpty() )    // The first entry can
        {                                               // exist, but is empty : use it.
            t3d->Copy( item );
        }
        else
        {
            t3d = new S3D_MASTER( this );
            t3d->Copy( item );
            m_3D_Drawings.PushBack( t3d );
        }
    }

    m_Doc     = aModule->m_Doc;
    m_KeyWord = aModule->m_KeyWord;

    // Ensure auxiliary data is up to date
    CalculateBoundingBox();
}
void CDVAPNodeTRXThread::run()
{
    // Wait here until we have the essentials to run
    while (!m_killed && (m_dvap == NULL || m_rptCallsign.IsEmpty() || m_rptCallsign.IsSameAs(wxT("        "))))
        ::wxMilliSleep(500UL);		// 1/2 sec

    if (m_killed)
        return;

    m_stopped = false;

    m_beaconTimer.start();
    m_dvapPollTimer.start();

    if (m_protocolHandler != NULL)
        m_pollTimer.start();

    wxLogMessage(wxT("Starting the DVAP node thread"));

    wxStopWatch stopWatch;

    while (!m_killed) {
        stopWatch.Start();

        switch (m_state) {
        case DSRS_LISTENING:
            receiveRadioHeader();
            break;
        case DSRS_NETWORK:
            break;
        case DSRS_VALID:
        case DSRS_INVALID:
        case DSRS_TIMEOUT:
            receiveRadioData();
            break;
        default:		// All the DSRS_*_WAIT values
            break;
        }

        // Listen all the time on the network for status packets at least
        receiveNetwork();

        repeaterStateMachine();

        m_tx      = m_dvap->getPTT();
        m_squelch = m_dvap->getSquelch();
        m_signal  = m_dvap->getSignal();

        // Send the network poll if needed and restart the timer
        if (m_pollTimer.hasExpired()) {
#if defined(__WINDOWS__)
            m_protocolHandler->writePoll(wxT("win_dvap-") + VERSION);
#else
            m_protocolHandler->writePoll(wxT("linux_dvap-") + VERSION);
#endif
            m_pollTimer.reset();
        }

        if (m_dvapPollTimer.hasExpired()) {
            m_dvap->writePoll();
            m_dvapPollTimer.reset();
        }

        // Send the beacon and restart the timer
        if (m_beaconTimer.isRunning() && m_beaconTimer.hasExpired()) {
            m_beacon->sendBeacon();
            m_beaconTimer.reset();
        }

        if (m_localQueue.dataReady())
            transmitLocalData();
        else if (m_networkQueue[m_readNum]->dataReady())
            transmitNetworkData();
        else if (m_localQueue.headerReady())
            transmitLocalHeader();
        else if (m_networkQueue[m_readNum]->headerReady())
            transmitNetworkHeader();

        unsigned long ms = stopWatch.Time();
        if (ms < CYCLE_TIME) {
            ::wxMilliSleep(CYCLE_TIME - ms);
            clock(CYCLE_TIME);
        } else {
            clock(ms);
        }
    }

    wxLogMessage(wxT("Stopping the DVAP node thread"));

    m_dvap->close();

    if (m_protocolHandler != NULL) {
        m_protocolHandler->close();
        delete m_protocolHandler;
    }
}
Esempio n. 28
0
MODULE::MODULE( const MODULE& aModule ) :
    BOARD_ITEM( aModule )
{
    m_Pos = aModule.m_Pos;
    m_fpid = aModule.m_fpid;
    m_Layer  = aModule.m_Layer;
    m_Attributs = aModule.m_Attributs;
    m_ModuleStatus = aModule.m_ModuleStatus;
    m_Orient = aModule.m_Orient;
    m_BoundaryBox = aModule.m_BoundaryBox;
    m_CntRot90 = aModule.m_CntRot90;
    m_CntRot180 = aModule.m_CntRot180;
    m_LastEditTime = aModule.m_LastEditTime;
    m_Link = aModule.m_Link;
    m_Path = aModule.m_Path;              //is this correct behavior?

    m_LocalClearance = aModule.m_LocalClearance;
    m_LocalSolderMaskMargin = aModule.m_LocalSolderMaskMargin;
    m_LocalSolderPasteMargin = aModule.m_LocalSolderPasteMargin;
    m_LocalSolderPasteMarginRatio = aModule.m_LocalSolderPasteMarginRatio;
    m_ZoneConnection = aModule.m_ZoneConnection;
    m_ThermalWidth = aModule.m_ThermalWidth;
    m_ThermalGap = aModule.m_ThermalGap;

    // Copy reference and value.
    m_Reference = new TEXTE_MODULE( *aModule.m_Reference );
    m_Reference->SetParent( this );

    m_Value = new TEXTE_MODULE( *aModule.m_Value );
    m_Value->SetParent( this );

    // Copy auxiliary data: Pads
    for( D_PAD* pad = aModule.m_Pads;  pad;  pad = pad->Next() )
    {
        D_PAD* newpad = new D_PAD( *pad );
        assert( newpad->GetNet() == pad->GetNet() );
        newpad->SetParent( this );
        m_Pads.PushBack( newpad );
    }

    // Copy auxiliary data: Drawings
    for( BOARD_ITEM* item = aModule.m_Drawings;  item;  item = item->Next() )
    {
        BOARD_ITEM* newItem;

        switch( item->Type() )
        {
        case PCB_MODULE_TEXT_T:
        case PCB_MODULE_EDGE_T:
            newItem = static_cast<BOARD_ITEM*>( item->Clone() );
            newItem->SetParent( this );
            m_Drawings.PushBack( newItem );
            break;

        default:
            wxLogMessage( wxT( "MODULE::Copy() Internal Err:  unknown type" ) );
            break;
        }
    }

    // Copy auxiliary data: 3D_Drawings info
    for( S3D_MASTER* item = aModule.m_3D_Drawings;  item;  item = item->Next() )
    {
        if( item->GetShape3DName().IsEmpty() )           // do not copy empty shapes.
            continue;

        S3D_MASTER* t3d = new S3D_MASTER( this );
        t3d->Copy( item );
        m_3D_Drawings.PushBack( t3d );
    }

    // Ensure there is at least one item in m_3D_Drawings.
    if( m_3D_Drawings.GetCount() == 0 )
        m_3D_Drawings.PushBack( new S3D_MASTER( this ) ); // push a void item

    m_Doc     = aModule.m_Doc;
    m_KeyWord = aModule.m_KeyWord;

    m_arflag = 0;

    // Ensure auxiliary data is up to date
    CalculateBoundingBox();

    m_initial_comments = aModule.m_initial_comments ?
                            new wxArrayString( *aModule.m_initial_comments ) : 0;
}
bool CDVAPNodeTRXThread::processRadioHeader(CHeaderData* header)
{
    wxASSERT(header != NULL);

    // We don't handle DD data packets
    if (header->isDataPacket()) {
        wxLogMessage(wxT("Received a DD packet, ignoring"));
        delete header;
        return false;
    }

    if (m_whiteList != NULL) {
        bool res = m_whiteList->isInList(header->getMyCall1());
        if (!res) {
            wxLogMessage(wxT("%s rejected due to not being in the white list"), header->getMyCall1().c_str());
            delete header;
            return true;
        }
    }

    if (m_blackList != NULL) {
        bool res = m_blackList->isInList(header->getMyCall1());
        if (res) {
            wxLogMessage(wxT("%s rejected due to being in the black list"), header->getMyCall1().c_str());
            delete header;
            return true;
        }
    }

    TRISTATE valid = checkHeader(*header);
    switch (valid) {
    case STATE_FALSE: {
        bool res = setRepeaterState(DSRS_INVALID);
        if (res) {
            delete m_rxHeader;
            m_rxHeader = header;
        } else {
            delete header;
        }
    }
    return true;

    case STATE_UNKNOWN:
        delete header;
        return true;

    case STATE_TRUE:
        break;
    }

    setRepeaterState(DSRS_VALID);

    // Send the valid header to the gateway if we are accepted
    if (m_state == DSRS_VALID) {
        delete m_rxHeader;
        m_rxHeader = header;

        if (m_logging != NULL)
            m_logging->open(*m_rxHeader);

        // Only send on the network if we have one and RPT2 is not blank or the repeater callsign
        if (m_protocolHandler != NULL && !m_rxHeader->getRptCall2().IsSameAs(wxT("        ")) && !m_rxHeader->getRptCall2().IsSameAs(m_rptCallsign)) {
            CHeaderData netHeader(*m_rxHeader);
            netHeader.setRptCall1(m_rxHeader->getRptCall2());
            netHeader.setRptCall2(m_rxHeader->getRptCall1());
            netHeader.setFlag1(m_rxHeader->getFlag1() & ~REPEATER_MASK);
            m_protocolHandler->writeHeader(netHeader);
        }
    } else {
        delete header;
    }

    return true;
}
Esempio n. 30
0
bool MyConnection::OnDisconnect()
{
    wxLogMessage(_T("OnDisconnect()"));
    wxGetApp().GetFrame()->Disconnect();
    return true;
}