Example #1
0
bool opt_set(const wxString& name, const wxString& val)
{
    const opt_desc dummy = new_opt_desc(name);
    const opt_desc* opt = std::lower_bound(&opts[0], &opts[num_opts], dummy, opt_lt);

    if (!wxStrcmp(name, opt->opt)) {
        if (opt->stropt)
            *opt->stropt = wxString(val);
        else if (opt->boolopt) {
            if (!(val == wxT('0') || val == wxT('1')))
                wxLogWarning(_("Invalid flag option %s - %s ignored"),
                    name.c_str(), val.c_str());
            else
                *opt->boolopt = val == wxT('1');
        } else if (!opt->enumvals.empty()) {
            wxString s     = val; s.MakeLower();
            wxString ev    = opt->enumvals; ev.MakeLower();
            auto enum_opts = str_split(ev, wxT("|"));

            const std::size_t found_pos = vec_find(enum_opts, s);
            const bool matched          = ((int)found_pos != wxNOT_FOUND);

            if (!matched) {
                const wxString evx = wxGetTranslation(opt->enumvals);
                bool isx = wxStrcmp(opt->enumvals, evx) != 0;
                // technically, the translation for this string could incorproate
                // the equals sign if necessary instead of doing it this way
                wxLogWarning(_("Invalid value %s for option %s; valid values are %s%s%s"),
                    s.c_str(), opt->opt.c_str(), opt->enumvals.c_str(),
                    isx ? wxT(" = ") : wxEmptyString,
                    isx ? evx.c_str() : wxEmptyString);
            } else {
                *opt->intopt = found_pos;
            }
        } else if (opt->intopt) {
            const wxString s(val);
            long ival;

            if (!s.ToLong(&ival) || ival < opt->min || ival > opt->max)
                wxLogWarning(_("Invalid value %d for option %s; valid values are %d - %d"), ival, name.c_str(), opt->min, opt->max);
            else
                *opt->intopt = ival;
        } else if (opt->doubleopt) {
            const wxString s(val);
            double dval;

            if (!s.ToDouble(&dval) || dval < opt->min || dval > opt->max)
                wxLogWarning(_("Invalid value %f for option %s; valid values are %f - %f"), dval, name.c_str(), opt->min, opt->max);
            else
                *opt->doubleopt = dval;
        } else if (opt->uintopt) {
            const wxString s(val);
            unsigned long uival;

            if (!s.ToULong(&uival) || uival < opt->min || uival > opt->max)
                wxLogWarning(_("Invalid value %f for option %s; valid values are %f - %f"), uival, name.c_str(), opt->min, opt->max);
            else
                *opt->uintopt = (uint32_t)uival;
        } else {
            // GB/Palette[0-2] is virtual
            for (int i = 0; i < 3; i++) {
                wxString optn;
                optn.Printf(wxT("GB/Palette%d"), i);

                if (optn != name)
                    continue;

                wxString vals(val);

                for (size_t j = 0, cpos = 0; j < 8; j++) {
                    int start = cpos;
                    cpos = vals.find(wxT(','), cpos);

                    if (cpos == wxString::npos)
                        cpos = vals.size();

                    long ival;
                    // ignoring errors; if the value is bad, palette will be corrupt
                    // -- tough.
                    // stupid wxString.ToLong doesn't support start @ offset
                    wxString entry = vals.substr(start, cpos - start);
                    entry.ToLong(&ival, 16);
                    systemGbPalette[i * 8 + j] = ival;

                    if (cpos != vals.size())
                        cpos++;
                }
            }
        }

        return true;
    } else {
        if (name.Find(wxT('/')) == wxNOT_FOUND)
            return false;

        auto parts = str_split(name, wxT("/"));

        if (parts[0] != wxT("Keyboard")) {
            cmditem* cmd = std::lower_bound(&cmdtab[0], &cmdtab[ncmds], cmditem{parts[1],wxString(),0,0,NULL}, cmditem_lt);

            if (cmd == &cmdtab[ncmds] || wxStrcmp(parts[1], cmd->cmd))
                return false;

            for (auto i = gopts.accels.begin(); i < gopts.accels.end(); ++i)
                if (i->GetCommand() == cmd->cmd_id) {
                    auto j = i;

                    for (; j < gopts.accels.end(); ++j)
                        if (j->GetCommand() != cmd->cmd_id)
                            break;

                    gopts.accels.erase(i, j);

                    break;
                }

            if (!val.empty()) {
                auto aval = wxKeyTextCtrl::FromString(val);

                for (size_t i = 0; i < aval.size(); i++)
                    aval[i].Set(aval[i].GetFlags(), aval[i].GetKeyCode(),
                        cmd->cmd_id);

                if (!aval.size())
                    wxLogWarning(_("Invalid key binding %s for %s"), val.c_str(), name.c_str());
                else
                    gopts.accels.insert(gopts.accels.end(), aval.begin(), aval.end());
            }

            return true;
        } else if (!wxStrncmp(name, wxT("Joypad"), wxStrlen(wxT("Joypad")))) {
            if (parts[1] < wxT('1') || parts[1] > wxT('4') || parts.size() < 3)
                return false;

            int jno = parts[1][0] - wxT('1');
            int kno;

            for (kno = 0; kno < NUM_KEYS; kno++)
                if (!wxStrcmp(joynames[kno], parts[2]))
                    break;

            if (kno == NUM_KEYS)
                return false;

            if (val.empty())
                gopts.joykey_bindings[jno][kno].clear();
            else {
                auto b = wxJoyKeyTextCtrl::FromString(val);

                if (!b.size())
                    wxLogWarning(_("Invalid key binding %s for %s"), val.c_str(), name.c_str());
                else
                    gopts.joykey_bindings[jno][kno] = b;
            }

            return true;
        } else
            return false;
    }
}
Example #2
0
void wxGridCellDateTimeRenderer::SetParameters(const wxString& params)
{
    if (!params.empty())
        m_oformat=params;
}
Example #3
0
bool wxTopLevelWindowGTK::Create( wxWindow *parent,
                                  wxWindowID id,
                                  const wxString& title,
                                  const wxPoint& pos,
                                  const wxSize& sizeOrig,
                                  long style,
                                  const wxString &name )
{
    // always create a frame of some reasonable, even if arbitrary, size (at
    // least for MSW compatibility)
    wxSize size = sizeOrig;
    size.x = WidthDefault(size.x);
    size.y = HeightDefault(size.y);

    wxTopLevelWindows.Append( this );

    if (!PreCreation( parent, pos, size ) ||
        !CreateBase( parent, id, pos, size, style, wxDefaultValidator, name ))
    {
        wxFAIL_MSG( wxT("wxTopLevelWindowGTK creation failed") );
        return false;
    }

    m_title = title;

    // NB: m_widget may be !=NULL if it was created by derived class' Create,
    //     e.g. in wxTaskBarIconAreaGTK
    if (m_widget == NULL)
    {
#if wxUSE_LIBHILDON || wxUSE_LIBHILDON2
        // we must create HildonWindow and not a normal GtkWindow as the latter
        // doesn't look correctly in Maemo environment and it must also be
        // registered with the main program object
        m_widget = hildon_window_new();
        hildon_program_add_window(wxTheApp->GetHildonProgram(),
                                  HILDON_WINDOW(m_widget));
#else // !wxUSE_LIBHILDON || !wxUSE_LIBHILDON2
        m_widget = gtk_window_new(GTK_WINDOW_TOPLEVEL);
        if (GetExtraStyle() & wxTOPLEVEL_EX_DIALOG)
        {
            // Tell WM that this is a dialog window and make it center
            // on parent by default (this is what GtkDialog ctor does):
            gtk_window_set_type_hint(GTK_WINDOW(m_widget),
                                     GDK_WINDOW_TYPE_HINT_DIALOG);
            gtk_window_set_position(GTK_WINDOW(m_widget),
                                    GTK_WIN_POS_CENTER_ON_PARENT);
        }
        else
        {
            if (style & wxFRAME_TOOL_WINDOW)
            {
                gtk_window_set_type_hint(GTK_WINDOW(m_widget),
                                         GDK_WINDOW_TYPE_HINT_UTILITY);

                // On some WMs, like KDE, a TOOL_WINDOW will still show
                // on the taskbar, but on Gnome a TOOL_WINDOW will not.
                // For consistency between WMs and with Windows, we
                // should set the NO_TASKBAR flag which will apply
                // the set_skip_taskbar_hint if it is available,
                // ensuring no taskbar entry will appear.
                style |= wxFRAME_NO_TASKBAR;
            }
        }
#endif // wxUSE_LIBHILDON || wxUSE_LIBHILDON2/!wxUSE_LIBHILDON || !wxUSE_LIBHILDON2

        g_object_ref(m_widget);
    }

    wxWindow *topParent = wxGetTopLevelParent(m_parent);
    if (topParent && (((GTK_IS_WINDOW(topParent->m_widget)) &&
                       (GetExtraStyle() & wxTOPLEVEL_EX_DIALOG)) ||
                       (style & wxFRAME_FLOAT_ON_PARENT)))
    {
        gtk_window_set_transient_for( GTK_WINDOW(m_widget),
                                      GTK_WINDOW(topParent->m_widget) );
    }

    if (style & wxFRAME_NO_TASKBAR)
    {
        gtk_window_set_skip_taskbar_hint(GTK_WINDOW(m_widget), TRUE);
    }

    if (style & wxSTAY_ON_TOP)
    {
        gtk_window_set_keep_above(GTK_WINDOW(m_widget), TRUE);
    }
    if (style & wxMAXIMIZE)
        gtk_window_maximize(GTK_WINDOW(m_widget));

#if 0
    if (!name.empty())
        gtk_window_set_role( GTK_WINDOW(m_widget), wxGTK_CONV( name ) );
#endif

    gtk_window_set_title( GTK_WINDOW(m_widget), wxGTK_CONV( title ) );
    gtk_widget_set_can_focus(m_widget, false);

    g_signal_connect (m_widget, "delete_event",
                      G_CALLBACK (gtk_frame_delete_callback), this);

    // m_mainWidget is a GtkVBox, holding the bars and client area (m_wxwindow)
    m_mainWidget = gtk_box_new(GTK_ORIENTATION_VERTICAL, 0);
    gtk_widget_show( m_mainWidget );
    gtk_widget_set_can_focus(m_mainWidget, false);
    gtk_container_add( GTK_CONTAINER(m_widget), m_mainWidget );

    // m_wxwindow is the client area
    m_wxwindow = wxPizza::New();
    gtk_widget_show( m_wxwindow );
    gtk_box_pack_start(GTK_BOX(m_mainWidget), m_wxwindow, true, true, 0);

    // we donm't allow the frame to get the focus as otherwise
    // the frame will grab it at arbitrary focus changes
    gtk_widget_set_can_focus(m_wxwindow, false);

    if (m_parent) m_parent->AddChild( this );

    g_signal_connect(m_wxwindow, "size_allocate",
        G_CALLBACK(size_allocate), this);

    PostCreation();

#ifndef __WXGTK3__
    if ((m_x != -1) || (m_y != -1))
        gtk_widget_set_uposition( m_widget, m_x, m_y );
#endif

    // for some reported size corrections
    g_signal_connect (m_widget, "map_event",
                      G_CALLBACK (gtk_frame_map_callback), this);

    // for iconized state
    g_signal_connect (m_widget, "window_state_event",
                      G_CALLBACK (gtk_frame_window_state_callback), this);


    // for wxMoveEvent
    g_signal_connect (m_widget, "configure_event",
                      G_CALLBACK (gtk_frame_configure_callback), this);

    // activation
    g_signal_connect_after (m_widget, "focus_in_event",
                      G_CALLBACK (gtk_frame_focus_in_callback), this);
    g_signal_connect_after (m_widget, "focus_out_event",
                      G_CALLBACK (gtk_frame_focus_out_callback), this);

    // GTK processes key events at the top level first, which handles for
    // menu accelerators and shortcuts before passing the event on to the
    // focus child window to begin propagation. We want to propagate
    // first, so we connect gtk_window_propagate_key_event to
    // key_press_event.
    g_signal_connect (m_widget, "key_press_event",
                      G_CALLBACK (gtk_window_propagate_key_event), NULL);

#ifdef GDK_WINDOWING_X11
#ifdef __WXGTK3__
    if (GDK_IS_X11_SCREEN(gtk_window_get_screen(GTK_WINDOW(m_widget))))
#endif
    {
        gtk_widget_add_events(m_widget, GDK_PROPERTY_CHANGE_MASK);
        g_signal_connect(m_widget, "property_notify_event",
            G_CALLBACK(property_notify_event), this);
    }
#endif // GDK_WINDOWING_X11

    // translate wx decorations styles into Motif WM hints (they are recognized
    // by other WMs as well)

    // always enable moving the window as we have no separate flag for enabling
    // it
    m_gdkFunc = GDK_FUNC_MOVE;

    if ( style & wxCLOSE_BOX )
        m_gdkFunc |= GDK_FUNC_CLOSE;

    if ( style & wxMINIMIZE_BOX )
        m_gdkFunc |= GDK_FUNC_MINIMIZE;

    if ( style & wxMAXIMIZE_BOX )
        m_gdkFunc |= GDK_FUNC_MAXIMIZE;

    if ( (style & wxSIMPLE_BORDER) || (style & wxNO_BORDER) )
    {
        m_gdkDecor = 0;
    }
    else // have border
    {
        m_gdkDecor = GDK_DECOR_BORDER;

        if ( style & wxCAPTION )
            m_gdkDecor |= GDK_DECOR_TITLE;

        if ( style & wxSYSTEM_MENU )
            m_gdkDecor |= GDK_DECOR_MENU;

        if ( style & wxMINIMIZE_BOX )
            m_gdkDecor |= GDK_DECOR_MINIMIZE;

        if ( style & wxMAXIMIZE_BOX )
            m_gdkDecor |= GDK_DECOR_MAXIMIZE;

        if ( style & wxRESIZE_BORDER )
        {
           m_gdkFunc |= GDK_FUNC_RESIZE;
           m_gdkDecor |= GDK_DECOR_RESIZEH;
        }
    }

    // GTK sometimes chooses very small size if max size hint is not explicitly set
    DoSetSizeHints(m_minWidth, m_minHeight, m_maxWidth, m_maxHeight, m_incWidth, m_incHeight);

    m_decorSize = GetCachedDecorSize();
    int w, h;
    GTKDoGetSize(&w, &h);
    gtk_window_set_default_size(GTK_WINDOW(m_widget), w, h);

    return true;
}
Example #4
0
bool wxTextCtrl::Create(wxWindow *parent,
                        wxWindowID id,
                        const wxString& value,
                        const wxPoint& pos,
                        const wxSize& size,
                        long style,
                        const wxValidator& validator,
                        const wxString& name)
{
    if( !CreateControl( parent, id, pos, size, style, validator, name ) )
        return false;
    PreCreation();

    m_tempCallbackStruct = NULL;
    m_modified = false;
    m_processedDefault = false;

    Widget parentWidget = (Widget) parent->GetClientWidget();

    Bool wantHorizScroll = (m_windowStyle & wxHSCROLL) != 0 ? True : False;
    // If we don't have horizontal scrollbars, we want word wrap.
    // OpenMotif 2.1 crashes if wantWordWrap is True in Japanese
    // locale (and probably other multibyte locales). The check might be
    // more precise
#if wxCHECK_LESSTIF() || wxCHECK_MOTIF_VERSION( 2, 2 )
    Bool wantWordWrap = wantHorizScroll == True ? False : True;
#else
    Bool wantWordWrap = False;
#endif

    if (m_windowStyle & wxTE_MULTILINE)
    {
        Arg args[8];
        int count = 0;
        XtSetArg (args[count], XmNscrollHorizontal, wantHorizScroll); ++count;
        if( m_font.IsOk() )
            XtSetArg (args[count], (String) wxFont::GetFontTag(),
                      m_font.GetFontType( XtDisplay(parentWidget) ) ); ++count;
        XtSetArg (args[count], XmNwordWrap, wantWordWrap); ++count;
        XtSetArg (args[count], XmNvalue, (const char*)value.mb_str()); ++count;
        XtSetArg (args[count], XmNeditable,
                  style & wxTE_READONLY ? False : True); ++count;
        XtSetArg (args[count], XmNeditMode, XmMULTI_LINE_EDIT ); ++count;

        m_mainWidget =
            (WXWidget) XmCreateScrolledText(parentWidget,
                                            name.char_str(),
                                            args, count);

        XtManageChild ((Widget) m_mainWidget);
    }
    else
    {
        m_mainWidget = (WXWidget)XtVaCreateManagedWidget
                                 (
                                  name.mb_str(),
                                  xmTextWidgetClass,
                                  parentWidget,
                                  wxFont::GetFontTag(), m_font.GetFontType( XtDisplay(parentWidget) ),
                                  XmNvalue, (const char*)value.mb_str(),
                                  XmNeditable, (style & wxTE_READONLY) ?
                                      False : True,
                                  NULL
                                 );

#if 0
        // TODO: Is this relevant? What does it do?
        int noCols = 2;
        if (!value.empty() && (value.length() > (unsigned int) noCols))
            noCols = value.length();
        XtVaSetValues((Widget) m_mainWidget,
                      XmNcolumns, noCols,
                      NULL);
#endif
    }

    // remove border if asked for
    if ( style & wxNO_BORDER )
    {
        XtVaSetValues((Widget)m_mainWidget,
                      XmNshadowThickness, 0,
                      NULL);
    }

    // install callbacks
    XtAddCallback((Widget) m_mainWidget, XmNvalueChangedCallback, (XtCallbackProc)wxTextWindowChangedProc, (XtPointer)this);

    XtAddCallback((Widget) m_mainWidget, XmNmodifyVerifyCallback, (XtCallbackProc)wxTextWindowModifyProc, (XtPointer)this);

    XtAddCallback((Widget) m_mainWidget, XmNactivateCallback, (XtCallbackProc)wxTextWindowActivateProc, (XtPointer)this);

    XtAddCallback((Widget) m_mainWidget, XmNfocusCallback, (XtCallbackProc)wxTextWindowGainFocusProc, (XtPointer)this);

    XtAddCallback((Widget) m_mainWidget, XmNlosingFocusCallback, (XtCallbackProc)wxTextWindowLoseFocusProc, (XtPointer)this);

    PostCreation();
    AttachWidget (parent, m_mainWidget, (WXWidget) NULL,
                  pos.x, pos.y, size.x, size.y);

    return true;
}
Example #5
0
wxFont *wxFontList::FindOrCreateFont(int pointSize,
                                     wxFontFamily family,
                                     wxFontStyle style,
                                     wxFontWeight weight,
                                     bool underline,
                                     const wxString& facename,
                                     wxFontEncoding encoding)
{
    // In all ports but wxOSX, the effective family of a font created using
    // wxFONTFAMILY_DEFAULT is wxFONTFAMILY_SWISS so this is what we need to
    // use for comparison.
    //
    // In wxOSX the original wxFONTFAMILY_DEFAULT seems to be kept and it uses
    // a different font than wxFONTFAMILY_SWISS anyhow so we just preserve it.
#ifndef __WXOSX__
    if ( family == wxFONTFAMILY_DEFAULT )
        family = wxFONTFAMILY_SWISS;
#endif // !__WXOSX__

    // In wxMSW, creating a font with wxFONTSTYLE_SLANT creates the same font
    // as wxFONTSTYLE_ITALIC and its GetStyle() returns the latter, so we must
    // account for it here. Notice that wxOSX also uses the same native font
    // for these styles, but wxFont::GetStyle() in it still returns different
    // values depending on how the font was created, so there is inconsistency
    // between ports here which it would be nice to fix in one way or another
    // (wxGTK supports both as separate styles, so it doesn't suffer from it).
 #ifdef __WXMSW__
    if ( style == wxFONTSTYLE_SLANT )
        style = wxFONTSTYLE_ITALIC;
 #endif // __WXMSW__

    wxFont *font;
    wxList::compatibility_iterator node;
    for (node = list.GetFirst(); node; node = node->GetNext())
    {
        font = (wxFont *)node->GetData();
        if (
             font->GetPointSize () == pointSize &&
             font->GetStyle () == style &&
             font->GetWeight () == weight &&
             font->GetUnderlined () == underline )
        {
            // empty facename matches anything at all: this is bad because
            // depending on which fonts are already created, we might get back
            // a different font if we create it with empty facename, but it is
            // still better than never matching anything in the cache at all
            // in this case
            bool same;
            const wxString fontFaceName(font->GetFaceName());

            if (facename.empty() || fontFaceName.empty())
                same = font->GetFamily() == family;
            else
                same = fontFaceName == facename;

            if ( same && (encoding != wxFONTENCODING_DEFAULT) )
            {
                // have to match the encoding too
                same = font->GetEncoding() == encoding;
            }

            if ( same )
            {
                return font;
            }
        }
    }

    // font not found, create the new one
    font = NULL;
    wxFont fontTmp(pointSize, family, style, weight, underline, facename, encoding);
    if (fontTmp.IsOk())
    {
        font = new wxFont(fontTmp);
        list.Append(font);
    }

    return font;
}
Example #6
0
// create the config object which stores its data under HKCU\vendor\app and, if
// style & wxCONFIG_USE_GLOBAL_FILE, under HKLM\vendor\app
wxRegConfig::wxRegConfig(const wxString& appName, const wxString& vendorName,
                         const wxString& strLocal, const wxString& strGlobal,
                         long style)
           : wxConfigBase(appName, vendorName, strLocal, strGlobal, style)
{
  wxString strRoot;

  bool bDoUseGlobal = (style & wxCONFIG_USE_GLOBAL_FILE) != 0;

  // the convention is to put the programs keys under <vendor>\<appname>
  // (but it can be overriden by specifying the pathes explicitly in strLocal
  // and/or strGlobal)
  if ( strLocal.empty() || (strGlobal.empty() && bDoUseGlobal) )
  {
    if ( vendorName.empty() )
    {
      if ( wxTheApp )
        strRoot = wxTheApp->GetVendorName();
    }
    else
    {
      strRoot = vendorName;
    }

    // no '\\' needed if no vendor name
    if ( !strRoot.empty() )
    {
      strRoot += '\\';
    }

    if ( appName.empty() )
    {
      wxCHECK_RET( wxTheApp, wxT("No application name in wxRegConfig ctor!") );
      strRoot << wxTheApp->GetAppName();
    }
    else
    {
      strRoot << appName;
    }
  }
  //else: we don't need to do all the complicated stuff above

  wxString str = strLocal.empty() ? strRoot : strLocal;

  // as we're going to change the name of these keys fairly often and as
  // there are only few of wxRegConfig objects (usually 1), we can allow
  // ourselves to be generous and spend some memory to significantly improve
  // performance of SetPath()
  static const size_t MEMORY_PREALLOC = 512;

  m_keyLocalRoot.ReserveMemoryForName(MEMORY_PREALLOC);
  m_keyLocal.ReserveMemoryForName(MEMORY_PREALLOC);

  m_keyLocalRoot.SetName(wxRegKey::HKCU, SOFTWARE_KEY + str);
  m_keyLocal.SetName(m_keyLocalRoot, wxEmptyString);

  if ( bDoUseGlobal )
  {
    str = strGlobal.empty() ? strRoot : strGlobal;

    m_keyGlobalRoot.ReserveMemoryForName(MEMORY_PREALLOC);
    m_keyGlobal.ReserveMemoryForName(MEMORY_PREALLOC);

    m_keyGlobalRoot.SetName(wxRegKey::HKLM, SOFTWARE_KEY + str);
    m_keyGlobal.SetName(m_keyGlobalRoot, wxEmptyString);
  }

  // Create() will Open() if key already exists
  m_keyLocalRoot.Create();

  // as it's the same key, Open() shouldn't fail (i.e. no need for Create())
  m_keyLocal.Open();

  // OTOH, this key may perfectly not exist, so suppress error messages the call
  // to Open() might generate
  if ( bDoUseGlobal )
  {
    wxLogNull nolog;
    m_keyGlobalRoot.Open(wxRegKey::Read);
    m_keyGlobal.Open(wxRegKey::Read);
  }
}
Example #7
0
wxFileDialog::wxFileDialog(wxWindow *parent, const wxString& message,
                           const wxString& defaultDir,
                           const wxString& defaultFileName,
                           const wxString& wildCard,
                           long style, const wxPoint& pos)
    : wxGenericFileDialog(parent, message, defaultDir, defaultFileName,
                       wildCard, style, pos, true )
{
#ifdef __WXGTK24__
    if (!gtk_check_version(2,4,0))
    {
        wxASSERT_MSG( !( (style & wxSAVE) && (style & wxMULTIPLE) ), wxT("wxFileDialog - wxMULTIPLE used on a save dialog" ) );
        m_needParent = false;
        m_destroyed_by_delete = false;

        if (!PreCreation(parent, pos, wxDefaultSize) ||
            !CreateBase(parent, wxID_ANY, pos, wxDefaultSize, style,
                    wxDefaultValidator, wxT("filedialog")))
        {
            wxFAIL_MSG( wxT("wxFileDialog creation failed") );
            return;
        }

        GtkFileChooserAction gtk_action;
        GtkWindow* gtk_parent = NULL;
        if (parent)
            gtk_parent = GTK_WINDOW(parent->m_widget);

        gchar* ok_btn_stock;
        if ( style & wxSAVE )
        {
            gtk_action = GTK_FILE_CHOOSER_ACTION_SAVE;
            ok_btn_stock = GTK_STOCK_SAVE;
        }
        else
        {
            gtk_action = GTK_FILE_CHOOSER_ACTION_OPEN;
            ok_btn_stock = GTK_STOCK_OPEN;
        }

        m_widget = gtk_file_chooser_dialog_new(
                       wxGTK_CONV(m_message),
                       gtk_parent,
                       gtk_action,
                       GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
                       ok_btn_stock, GTK_RESPONSE_ACCEPT,
                       NULL);

        if ( style & wxMULTIPLE )
            gtk_file_chooser_set_select_multiple(GTK_FILE_CHOOSER(m_widget), true);

        // local-only property could be set to false to allow non-local files to be loaded.
        // In that case get/set_uri(s) should be used instead of get/set_filename(s) everywhere
        // and the GtkFileChooserDialog should probably also be created with a backend,
        // e.g "gnome-vfs", "default", ... (gtk_file_chooser_dialog_new_with_backend).
        // Currently local-only is kept as the default - true:
        // gtk_file_chooser_set_local_only(GTK_FILE_CHOOSER(m_widget), true);

        g_signal_connect(G_OBJECT(m_widget), "response",
            GTK_SIGNAL_FUNC(gtk_filedialog_response_callback), (gpointer)this);

        SetWildcard(wildCard);

        if ( style & wxSAVE )
        {
            if ( !defaultDir.empty() )
                gtk_file_chooser_set_current_folder(GTK_FILE_CHOOSER(m_widget),
                wxConvFileName->cWX2MB(defaultDir));

            gtk_file_chooser_set_current_name(GTK_FILE_CHOOSER(m_widget),
                wxConvFileName->cWX2MB(defaultFileName));
        }
        else
        {
            if ( !defaultFileName.empty() )
            {
                wxString dir;
                if ( defaultDir.empty() )
                    dir = ::wxGetCwd();
                else
                    dir = defaultDir;

                gtk_file_chooser_set_filename(
                    GTK_FILE_CHOOSER(m_widget),
                    wxConvFileName->cWX2MB( wxFileName(dir, defaultFileName).GetFullPath() ) );
            }
            else if ( !defaultDir.empty() )
                gtk_file_chooser_set_current_folder( GTK_FILE_CHOOSER(m_widget),
                    wxConvFileName->cWX2MB(defaultDir) );
        }
    }
    else
#endif
        wxGenericFileDialog::Create( parent, message, defaultDir, defaultFileName, wildCard, style, pos );
}
Example #8
0
bool CAboutDialog::Create(wxWindow* parent)
{
	if (!Load(parent, _T("ID_ABOUT"))) {
		return false;
	}

        wxBitmap bmp = CThemeProvider::Get()->CreateBitmap("ART_FILEZILLA", wxString(), CThemeProvider::GetIconSize(iconSizeLarge));
        xrc_call(*this, "ID_FILEZILLA_LOGO", &wxStaticBitmap::SetBitmap, bmp);

	xrc_call(*this, "ID_URL", &wxHyperlinkCtrl::SetLabel, _T("https://filezilla-project.org/"));
	xrc_call(*this, "ID_COPYRIGHT", &wxStaticText::SetLabel, _T("Copyright (C) 2004-2016  Tim Kosse"));

	wxString version = CBuildInfo::GetVersion();
	if (CBuildInfo::GetBuildType() == _T("nightly"))
		version += _T("-nightly");
	if (!SetChildLabel(XRCID("ID_VERSION"), version))
		return false;

	wxString const host = CBuildInfo::GetHostname();
	if (host.empty()) {
		xrc_call(*this, "ID_HOST", &wxStaticText::Hide);
		xrc_call(*this, "ID_HOST_DESC", &wxStaticText::Hide);
	}
	else {
		xrc_call(*this, "ID_HOST", &wxStaticText::SetLabel, host);
	}

	wxString const build = CBuildInfo::GetBuildSystem();
	if (build.empty()) {
		xrc_call(*this, "ID_BUILD", &wxStaticText::Hide);
		xrc_call(*this, "ID_BUILD_DESC", &wxStaticText::Hide);
	}
	else {
		xrc_call(*this, "ID_BUILD", &wxStaticText::SetLabel, build);
	}

	if (!SetChildLabel(XRCID("ID_BUILDDATE"), CBuildInfo::GetBuildDateString()))
		return false;

	if (!SetChildLabel(XRCID("ID_COMPILEDWITH"), CBuildInfo::GetCompiler(), 200))
		return false;

	wxString compilerFlags = CBuildInfo::GetCompilerFlags();
	if (compilerFlags.empty()) {
		xrc_call(*this, "ID_CFLAGS", &wxStaticText::Hide);
		xrc_call(*this, "ID_CFLAGS_DESC", &wxStaticText::Hide);
	}
	else {
		WrapText(this, compilerFlags, 250);
		xrc_call(*this, "ID_CFLAGS", &wxStaticText::SetLabel, compilerFlags);
	}

	xrc_call(*this, "ID_VER_WX", &wxStaticText::SetLabel, GetDependencyVersion(lib_dependency::wxwidgets));
	xrc_call(*this, "ID_VER_GNUTLS", &wxStaticText::SetLabel, GetDependencyVersion(lib_dependency::gnutls));
	xrc_call(*this, "ID_VER_SQLITE", &wxStaticText::SetLabel, GetDependencyVersion(lib_dependency::sqlite));

	wxString const os = wxGetOsDescription();
	if (os.empty()) {
		xrc_call(*this, "ID_SYSTEM_NAME", &wxStaticText::Hide);
		xrc_call(*this, "ID_SYSTEM_NAME_DESC", &wxStaticText::Hide);
	}
	else {
		xrc_call(*this, "ID_SYSTEM_NAME", &wxStaticText::SetLabel, os);
	}

	int major, minor;
	if (GetRealOsVersion(major, minor)) {
		wxString osVersion = wxString::Format(_T("%d.%d"), major, minor);
		int fakeMajor, fakeMinor;
		if (wxGetOsVersion(&fakeMajor, &fakeMinor) != wxOS_UNKNOWN && (fakeMajor != major || fakeMinor != minor)) {
			osVersion += _T(" ");
			osVersion += wxString::Format(_("(app-compat is set to %d.%d)"), fakeMajor, fakeMinor);
		}
		xrc_call(*this, "ID_SYSTEM_VER", &wxStaticText::SetLabel, osVersion);
	}
	else {
		xrc_call(*this, "ID_SYSTEM_VER", &wxStaticText::Hide);
		xrc_call(*this, "ID_SYSTEM_VER_DESC", &wxStaticText::Hide);
	}

#ifdef __WXMSW__
	if (::wxIsPlatform64Bit())
		xrc_call(*this, "ID_SYSTEM_PLATFORM", &wxStaticText::SetLabel, _("64-bit system"));
	else
		xrc_call(*this, "ID_SYSTEM_PLATFORM", &wxStaticText::SetLabel, _("32-bit system"));
#else
	xrc_call(*this, "ID_SYSTEM_PLATFORM", &wxStaticText::Hide);
	xrc_call(*this, "ID_SYSTEM_PLATFORM_DESC", &wxStaticText::Hide);
#endif

	wxString cpuCaps = CBuildInfo::GetCPUCaps(' ');
	if (!cpuCaps.empty()) {
		WrapText(this, cpuCaps, 250);
		xrc_call(*this, "ID_SYSTEM_CPU", &wxStaticText::SetLabel, cpuCaps);
	}
	else {
		xrc_call(*this, "ID_SYSTEM_CPU_DESC", &wxStaticText::Hide);
		xrc_call(*this, "ID_SYSTEM_CPU", &wxStaticText::Hide);
	}

	xrc_call(*this, "ID_SYSTEM_SETTINGS_DIR", &wxStaticText::SetLabel, COptions::Get()->GetOption(OPTION_DEFAULT_SETTINGSDIR));

	GetSizer()->Fit(this);
	GetSizer()->SetSizeHints(this);

	return true;
}
Example #9
0
bool wxSpinCtrl::Create(wxWindow *parent,
                        wxWindowID id,
                        const wxString& value,
                        const wxPoint& pos,
                        const wxSize& size,
                        long style,
                        int min, int max, int initial,
                        const wxString& name)
{
    // before using DoGetBestSize(), have to set style to let the base class
    // know whether this is a horizontal or vertical control (we're always
    // vertical)
    style |= wxSP_VERTICAL;

    if ( (style & wxBORDER_MASK) == wxBORDER_DEFAULT )
#ifdef __WXWINCE__
        style |= wxBORDER_SIMPLE;
#else
        style |= wxBORDER_SUNKEN;
#endif

    SetWindowStyle(style);

    WXDWORD exStyle = 0;
    WXDWORD msStyle = MSWGetStyle(GetWindowStyle(), & exStyle) ;

    // Scroll text automatically if there is not enough space to show all of
    // it, this is better than not allowing to enter more digits at all.
    msStyle |= ES_AUTOHSCROLL;

    // propagate text alignment style to text ctrl
    if ( style & wxALIGN_RIGHT )
        msStyle |= ES_RIGHT;
    else if ( style & wxALIGN_CENTER )
        msStyle |= ES_CENTER;

    // calculate the sizes: the size given is the total size for both controls
    // and we need to fit them both in the given width (height is the same)
    wxSize sizeText(size), sizeBtn(size);
    sizeBtn.x = wxSpinButton::DoGetBestSize().x;
    if ( sizeText.x <= 0 )
    {
        // DEFAULT_ITEM_WIDTH is the default width for the text control
        sizeText.x = DEFAULT_ITEM_WIDTH + MARGIN_BETWEEN + sizeBtn.x;
    }

    sizeText.x -= sizeBtn.x + MARGIN_BETWEEN;
    if ( sizeText.x <= 0 )
    {
        wxLogDebug(wxS("wxSpinCtrl \"%s\": initial width %d is too small, ")
                   wxS("at least %d pixels needed."),
                   name, size.x, sizeBtn.x + MARGIN_BETWEEN + 1);
    }

    wxPoint posBtn(pos);
    posBtn.x += sizeText.x + MARGIN_BETWEEN;

    // we must create the text control before the spin button for the purpose
    // of the dialog navigation: if there is a static text just before the spin
    // control, activating it by Alt-letter should give focus to the text
    // control, not the spin and the dialog navigation code will give focus to
    // the next control (at Windows level), not the one after it

    // create the text window

    m_hwndBuddy = (WXHWND)::CreateWindowEx
                    (
                     exStyle,                // sunken border
                     wxT("EDIT"),             // window class
                     NULL,                   // no window title
                     msStyle,                // style (will be shown later)
                     pos.x, pos.y,           // position
                     0, 0,                   // size (will be set later)
                     GetHwndOf(parent),      // parent
                     (HMENU)-1,              // control id
                     wxGetInstance(),        // app instance
                     NULL                    // unused client data
                    );

    if ( !m_hwndBuddy )
    {
        wxLogLastError(wxT("CreateWindow(buddy text window)"));

        return false;
    }


    // create the spin button
    if ( !wxSpinButton::Create(parent, id, posBtn, sizeBtn, style, name) )
    {
        return false;
    }

    wxSpinButtonBase::SetRange(min, max);

    // subclass the text ctrl to be able to intercept some events
    gs_spinForTextCtrl[GetBuddyHwnd()] = this;

    m_wndProcBuddy = (WXFARPROC)wxSetWindowProc(GetBuddyHwnd(),
                                                wxBuddyTextWndProc);

    // set up fonts and colours  (This is nomally done in MSWCreateControl)
    InheritAttributes();
    if (!m_hasFont)
        SetFont(GetDefaultAttributes().font);

    // set the size of the text window - can do it only now, because we
    // couldn't call DoGetBestSize() before as font wasn't set
    if ( sizeText.y <= 0 )
    {
        int cx, cy;
        wxGetCharSize(GetHWND(), &cx, &cy, GetFont());

        sizeText.y = EDIT_HEIGHT_FROM_CHAR_HEIGHT(cy);
    }

    SetInitialSize(size);

    (void)::ShowWindow(GetBuddyHwnd(), SW_SHOW);

    // associate the text window with the spin button
    (void)::SendMessage(GetHwnd(), UDM_SETBUDDY, (WPARAM)m_hwndBuddy, 0);

    // If the initial text value is actually a number, it overrides the
    // "initial" argument specified later.
    long initialFromText;
    if ( value.ToLong(&initialFromText) )
        initial = initialFromText;

    // Set the range in the native control: notice that we must do it before
    // calling SetValue() to use the correct validity checks for the initial
    // value.
    SetRange(min, max);
    SetValue(initial);

    // Also set the text part of the control if it was specified independently
    // but don't generate an event for this, it would be unexpected.
    m_blockEvent = true;
    if ( !value.empty() )
        SetValue(value);
    m_blockEvent = false;

    return true;
}
Example #10
0
void BundlePane::NewItem(BundleItemType type) {
	const wxTreeItemId selItem = m_bundleTree->GetSelection();
	if (!selItem.IsOk()) return; // Can't add item if no bundle
	const BundleItemData* data = (BundleItemData*)m_bundleTree->GetItemData(selItem);

	// Get the parent bundle
	const BundleItemData* bundleData = data;
	wxTreeItemId bundleItem = selItem;
	while (!bundleData->IsBundle()) {
		bundleItem = m_bundleTree->GetItemParent(bundleItem);
		bundleData = (BundleItemData*)m_bundleTree->GetItemData(bundleItem);
	}

	// Get name of new item
	wxString name;
	switch (type) {
	case BUNDLE_COMMAND:  name = _("New Command"); break;
	case BUNDLE_SNIPPET:  name = _("New Snippet"); break;
	case BUNDLE_DRAGCMD:  name = _("New DragCommand"); break;
	case BUNDLE_PREF:     name = _("New Preference"); break;
	case BUNDLE_LANGUAGE: name = _("New Language"); break;
	default: wxASSERT(false);
	}
	name = wxGetTextFromUser(_("Name of new item:"), _("New Item"), name, this);
	if (name.empty()) return; // user cancel

	// Create a new (unsaved) command item
	const unsigned int bundleId = data->m_bundleId;
	const unsigned int itemId = m_plistHandler.New(type, bundleId, name);
	
	// Set default values
	PListDict itemDict = m_plistHandler.GetEditable(type, bundleId, itemId);
	switch (type) {
	case BUNDLE_COMMAND:
		itemDict.SetString("input", "selection");
		itemDict.SetString("output", "replaceSelectedText");
		itemDict.SetString("command", s_commandsyntax);
		break;
	case BUNDLE_SNIPPET:
		itemDict.SetString("tabTrigger", "");
		itemDict.SetString("content", s_snippetsyntax);
		break;
	case BUNDLE_DRAGCMD:
		{
			PListArray extArray = itemDict.NewArray("draggedFileExtensions");
			extArray.AddString("png");
			extArray.AddString("jpg");
			itemDict.SetString("command", "echo \"$TM_DROPPED_FILE\"");
		}
		break;
	case BUNDLE_PREF:
		break;
	case BUNDLE_LANGUAGE:
		break;
	default:
		wxASSERT(false);
	}

	// Save the new item
	m_plistHandler.Save(type, bundleId, itemId);

	// Add to tree
	const wxString uuid = itemDict.wxGetString("uuid");
	BundleItemData* itemData = new BundleItemData(type, bundleId, itemId, uuid);
	const wxTreeItemId treeItem = m_bundleTree->AppendItem(bundleItem, name, itemData->GetImageId(), -1, itemData);
	m_bundleTree->SortChildren(bundleItem);
	m_bundleTree->SelectItem(treeItem);

	// Also add to menu if needed
	if (data->IsMenuItem()) {
		PListDict infoDict = GetEditableMenuPlist(bundleId);
		BundleItemData* menuData = new BundleItemData(*itemData);
		InsertMenuItem(selItem, name, menuData, infoDict);
		m_plistHandler.SaveBundle(bundleId);

		// Update menu in editorFrame
		m_syntaxHandler.ReParseBundles(true/*onlyMenu*/);
	}

	// Open in editor
	const wxString bundlePath = m_plistHandler.GetBundleItemUri(type, bundleId, itemId);
	if (bundlePath.empty()) return;
	m_parentFrame.Open(bundlePath);
}
Example #11
0
int BenchApp::OnRun()
{
    int rc = EXIT_SUCCESS;
    for ( Bench::Function *func = Bench::Function::GetFirst();
          func;
          func = func->GetNext() )
    {
        if ( m_toRun.Index(func->GetName()) == wxNOT_FOUND )
            continue;

        wxString params;
        if ( m_numParam )
            params += wxString::Format(" with N=%ld", m_numParam);
        if ( !m_strParam.empty() )
        {
            if ( !params.empty() )
                params += " and";
            params += wxString::Format(" with s=\"%s\"", m_strParam);
        }

        wxPrintf("Benchmarking %s%s: ", func->GetName(), params);

        long timeMin = LONG_MAX,
             timeMax = 0,
             timeTotal = 0;
        bool ok = func->Init();
        for ( long a = 0; ok && a < m_avgCount; a++ )
        {
            wxStopWatch sw;
            for ( long n = 0; n < m_numRuns && ok; n++ )
            {
                ok = func->Run();
            }

            sw.Pause();

            const long t = sw.Time();
            if ( t < timeMin )
                timeMin = t;
            if ( t > timeMax )
                timeMax = t;
            timeTotal += t;
        }

        func->Done();

        if ( !ok )
        {
            wxPrintf("ERROR\n");
            rc = EXIT_FAILURE;
        }
        else
        {
            wxPrintf("%ldms total, ", timeTotal);

            long times = m_avgCount;
            if ( m_avgCount > 2 )
            {
                timeTotal -= timeMin + timeMax;
                times -= 2;
            }

            wxPrintf("%.2f avg (min=%ld, max=%ld)\n",
                     (float)timeTotal / times, timeMin, timeMax);
        }
    }

    return rc;
}
Example #12
0
void BundlePane::OnMenuNew(wxCommandEvent& event) {
	const int menuId = event.GetId();

	switch (menuId) {
		case MENU_NEW_BUNDLE:
			{
				// Get name from user
				const wxString name = wxGetTextFromUser(_("Name of new item:"), _("New Item"), _("New Bundle"), this);
				if (name.empty()) return; // user cancel

				// Create a new  bundle item
				const unsigned int bundleId = m_plistHandler.NewBundle(name);
				m_plistHandler.SaveBundle(bundleId);

				// Add to tree
				const wxTreeItemId rootItem = m_bundleTree->GetRootItem();
				const wxTreeItemId bundleItem = m_bundleTree->AppendItem(rootItem, name, 0, -1, new BundleItemData(bundleId));
				const wxTreeItemId menuItem = m_bundleTree->AppendItem(bundleItem, _("Menu"), 6, -1, new BundleItemData(BUNDLE_MENU, bundleId));
				m_bundleTree->SortChildren(rootItem);
				m_bundleTree->SelectItem(bundleItem);
			}
			break;
		case MENU_NEW_COMMAND:
			NewItem(BUNDLE_COMMAND);
			break;
		case MENU_NEW_SNIPPET:
			NewItem(BUNDLE_SNIPPET);
			break;
		case MENU_NEW_DRAGCMD:
			NewItem(BUNDLE_DRAGCMD);
			break;
		case MENU_NEW_PREF:
			NewItem(BUNDLE_PREF);
			break;
		case MENU_NEW_LANGUAGE:
			NewItem(BUNDLE_LANGUAGE);
			break;
		case MENU_NEW_SEPARATOR:
			{
				const wxTreeItemId selItem = m_bundleTree->GetSelection();
				const BundleItemData* data = (BundleItemData*)m_bundleTree->GetItemData(selItem);

				PListDict infoDict = GetEditableMenuPlist(data->m_bundleId);
				InsertMenuItem(selItem, wxT("---- separator ----"), new BundleItemData(BUNDLE_SEPARATOR, data->m_bundleId), infoDict);
				m_plistHandler.SaveBundle(data->m_bundleId);

				// Update menu in editorFrame
				m_syntaxHandler.ReParseBundles(true/*onlyMenu*/);
			}
			break;
		case MENU_NEW_SUBMENU:
			{
				// Get name from user
				const wxString name = wxGetTextFromUser(_("Name of new item:"), _("New Item"), _("New SubMenu"), this);
				if (name.empty()) return; // user cancel

				const wxTreeItemId selItem = m_bundleTree->GetSelection();
				const BundleItemData* data = (BundleItemData*)m_bundleTree->GetItemData(selItem);
				
				// Get a new uuid
				const wxString newUuid = PListHandler::GetNewUuid();
				const wxCharBuffer uuidBuf = newUuid.ToUTF8();
				const char* uuid = uuidBuf.data();

				// Create the new group
				PListDict infoDict = GetEditableMenuPlist(data->m_bundleId);
				PListDict menuDict;
				if (!infoDict.GetDict("mainMenu", menuDict)) {
					wxFAIL_MSG(wxT("No mainMenu in info.plist"));
					return;
				}
				PListDict submenuDict = menuDict.NewDict("submenus");
				PListDict subDict = submenuDict.NewDict(uuid);
				subDict.NewArray("items");
				subDict.wxSetString("name", name);

				// Insert in menu
				InsertMenuItem(selItem, name, new BundleItemData(BUNDLE_SUBDIR, data->m_bundleId, newUuid), infoDict);
				m_plistHandler.SaveBundle(data->m_bundleId);

				// Update menu in editorFrame
				m_syntaxHandler.ReParseBundles(true/*onlyMenu*/);
			}
			break;
		default: wxASSERT(false);
	}
};
bool wxShell(const wxString& command, wxArrayString& output)
{
    wxCHECK_MSG( !command.empty(), false, _T("can't exec shell non interactively") );

    return wxExecute(wxMakeShellCommand(command), output);
}
long wxExecute( const wxString& command, int flags, wxProcess *process )
{
    wxCHECK_MSG( !command.empty(), 0, wxT("can't exec empty command") );
    wxLogDebug(wxString(wxT("Launching: ")) + command);

#if wxUSE_THREADS
    // fork() doesn't mix well with POSIX threads: on many systems the program
    // deadlocks or crashes for some reason. Probably our code is buggy and
    // doesn't do something which must be done to allow this to work, but I
    // don't know what yet, so for now just warn the user (this is the least we
    // can do) about it
    wxASSERT_MSG( wxThread::IsMain(),
                    _T("wxExecute() can be called only from the main thread") );
#endif // wxUSE_THREADS

    int argc = 0;
    wxChar *argv[WXEXECUTE_NARGS];
    wxString argument;
    const wxChar *cptr = command.c_str();
    wxChar quotechar = wxT('\0'); // is arg quoted?
    bool escaped = false;

    // split the command line in arguments
    do
    {
        argument=wxT("");
        quotechar = wxT('\0');

        // eat leading whitespace:
        while ( wxIsspace(*cptr) )
            cptr++;

        if ( *cptr == wxT('\'') || *cptr == wxT('"') )
            quotechar = *cptr++;

        do
        {
            if ( *cptr == wxT('\\') && ! escaped )
            {
                escaped = true;
                cptr++;
                continue;
            }

            // all other characters:
            argument += *cptr++;
            escaped = false;

            // have we reached the end of the argument?
            if ( (*cptr == quotechar && ! escaped)
                 || (quotechar == wxT('\0') && wxIsspace(*cptr))
                 || *cptr == wxT('\0') )
            {
                wxASSERT_MSG( argc < WXEXECUTE_NARGS,
                              wxT("too many arguments in wxExecute") );

                argv[argc] = new wxChar[argument.length() + 1];
                wxStrcpy(argv[argc], argument.c_str());
                argc++;

                // if not at end of buffer, swallow last character:
                if(*cptr)
                    cptr++;

                break; // done with this one, start over
            }
        } while(*cptr);
    } while(*cptr);
    argv[argc] = NULL;

    long lRc;
#if defined(__DARWIN__)
    // wxMacExecute only executes app bundles.
    // It returns an error code if the target is not an app bundle, thus falling
    // through to the regular wxExecute for non app bundles.
    lRc = wxMacExecute(argv, flags, process);
    if( lRc != ((flags & wxEXEC_SYNC) ? -1 : 0))
        return lRc;
#endif

    // do execute the command
    lRc = wxExecute(argv, flags, process);

    // clean up
    argc = 0;
    while( argv[argc] )
        delete [] argv[argc++];

    return lRc;
}
Example #15
0
//---------------------------------------------------------------------------
// wxMediaCtrl::Create (file version)
// wxMediaCtrl::Create (URL version)
//
// Searches for a backend that is installed on the system (backends
// starting with lower characters in the alphabet are given priority),
// and creates the control from it
//
// This searches by searching the global RTTI hashtable, class by class,
// attempting to call CreateControl on each one found that is a derivative
// of wxMediaBackend - if it succeeded Create returns true, otherwise
// it keeps iterating through the hashmap.
//---------------------------------------------------------------------------
bool wxMediaCtrl::Create(wxWindow* parent, wxWindowID id,
                const wxString& fileName,
                const wxPoint& pos,
                const wxSize& size,
                long style,
                const wxString& szBackend,
                const wxValidator& validator,
                const wxString& name)
{
    if(!szBackend.empty())
    {
        wxClassInfo* pClassInfo = wxClassInfo::FindClass(szBackend);

        if(!pClassInfo || !DoCreate(pClassInfo, parent, id,
                                    pos, size, style, validator, name))
        {
            m_imp = NULL;
            return false;
        }

        if (!fileName.empty())
        {
            if (!Load(fileName))
            {
                wxDELETE(m_imp);
                return false;
            }
        }

        SetInitialSize(size);
        return true;
    }
    else
    {
        wxClassInfo::const_iterator it = wxClassInfo::begin_classinfo();

        const wxClassInfo* classInfo;

        while((classInfo = NextBackend(&it)) != NULL)
        {
            if(!DoCreate(classInfo, parent, id,
                         pos, size, style, validator, name))
                continue;

            if (!fileName.empty())
            {
                if (Load(fileName))
                {
                    SetInitialSize(size);
                    return true;
                }
                else
                    delete m_imp;
            }
            else
            {
                SetInitialSize(size);
                return true;
            }
        }

        m_imp = NULL;
        return false;
    }
}
Example #16
0
//---------------------------------------------------------------------------
// wxMediaCtrl::Create (file version)
// wxMediaCtrl::Create (URL version)
//
// Searches for a backend that is installed on the system (backends
// starting with lower characters in the alphabet are given priority),
// and creates the control from it
//
// This searches by searching the global RTTI hashtable, class by class,
// attempting to call CreateControl on each one found that is a derivative
// of wxMediaBackend - if it succeeded Create returns true, otherwise
// it keeps iterating through the hashmap.
//---------------------------------------------------------------------------
bool wxMediaCtrl::Create(wxWindow* parent, wxWindowID id,
                const wxString& fileName,
                const wxPoint& pos,
                const wxSize& size,
                long style,
                const wxString& szBackend,
                const wxValidator& validator,
                const wxString& name)
{
    if(!szBackend.empty())
    {
        wxClassInfo* pClassInfo = wxClassInfo::FindClass(szBackend);

        if(!pClassInfo || !DoCreate(pClassInfo, parent, id,
                                    pos, size, style, validator, name))
        {
            m_imp = NULL;
            return false;
        }

        if (!fileName.empty())
        {
            if (!Load(fileName))
            {
                delete m_imp;
                m_imp = NULL;
                return false;
            }
        }

        SetBestFittingSize(size);
        return true;
    }
    else
    {
        wxClassInfo::sm_classTable->BeginFind();

        wxClassInfo* classInfo;

        while((classInfo = NextBackend()) != NULL)
        {
            if(!DoCreate(classInfo, parent, id,
                         pos, size, style, validator, name))
                continue;

            if (!fileName.empty())
            {
                if (Load(fileName))
                {
                    SetBestFittingSize(size);
                    return true;
                }
                else
                    delete m_imp;
            }
            else
            {
                SetBestFittingSize(size);
                return true;
            }
        }

        m_imp = NULL;
        return false;
    }
}
Example #17
0
// this function is called a *lot* of times (as I learned after seeing from
// profiler output that it is called ~12000 times from Mahogany start up code!)
// so it is important to optimize it - in particular, avoid using generic
// string functions here and do everything manually because it is faster
//
// I still kept the old version to be able to check that the optimized code has
// the same output as the non optimized version.
void wxRegConfig::SetPath(const wxString& strPath)
{
    // remember the old path
    wxString strOldPath = m_strPath;

#ifdef WX_DEBUG_SET_PATH // non optimized version kept here for testing
    wxString m_strPathAlt;

    {
        wxArrayString aParts;

        // because GetPath() returns "" when we're at root, we must understand
        // empty string as "/"
        if ( strPath.empty() || (strPath[0] == wxCONFIG_PATH_SEPARATOR) ) {
            // absolute path
            wxSplitPath(aParts, strPath);
        }
        else {
            // relative path, combine with current one
            wxString strFullPath = GetPath();
            strFullPath << wxCONFIG_PATH_SEPARATOR << strPath;
            wxSplitPath(aParts, strFullPath);
        }

        // recombine path parts in one variable
        wxString strRegPath;
        m_strPathAlt.Empty();
        for ( size_t n = 0; n < aParts.Count(); n++ ) {
            strRegPath << '\\' << aParts[n];
            m_strPathAlt << wxCONFIG_PATH_SEPARATOR << aParts[n];
        }
    }
#endif // 0

    // check for the most common case first
    if ( strPath.empty() )
    {
        m_strPath = wxCONFIG_PATH_SEPARATOR;
    }
    else // not root
    {
        // construct the full path
        wxString strFullPath;
        if ( strPath[0u] == wxCONFIG_PATH_SEPARATOR )
        {
            // absolute path
            strFullPath = strPath;
        }
        else // relative path
        {
            strFullPath.reserve(2*m_strPath.length());

            strFullPath << m_strPath;
            if ( strFullPath.Len() == 0 ||
                 strFullPath.Last() != wxCONFIG_PATH_SEPARATOR )
                strFullPath << wxCONFIG_PATH_SEPARATOR;
            strFullPath << strPath;
        }

        // simplify it: we need to handle ".." here

        // count the total number of slashes we have to know if we can go upper
        size_t totalSlashes = 0;

        // position of the last slash to be able to backtrack to it quickly if
        // needed, but we set it to -1 if we don't have a valid position
        //
        // we only remember the last position which means that we handle ".."
        // quite efficiently but not "../.." - however the latter should be
        // much more rare, so it is probably ok
        int posLastSlash = -1;

        const wxChar *src = strFullPath.c_str();
        size_t len = strFullPath.length();
        const wxChar *end = src + len;

        wxStringBufferLength buf(m_strPath, len);
        wxChar *dst = buf;
        wxChar *start = dst;

        for ( ; src < end; src++, dst++ )
        {
            if ( *src == wxCONFIG_PATH_SEPARATOR )
            {
                // check for "/.."

                // note that we don't have to check for src < end here as
                // *end == 0 so can't be '.'
                if ( src[1] == wxT('.') && src[2] == wxT('.') &&
                     (src + 3 == end || src[3] == wxCONFIG_PATH_SEPARATOR) )
                {
                    if ( !totalSlashes )
                    {
                        wxLogWarning(_("'%s' has extra '..', ignored."),
                                     strFullPath.c_str());
                    }
                    else // return to the previous path component
                    {
                        // do we already have its position?
                        if ( posLastSlash == -1 )
                        {
                            // no, find it: note that we are sure to have one
                            // because totalSlashes > 0 so we don't have to
                            // check the boundary condition below

                            // this is more efficient than strrchr()
                            dst--;
                            while ( *dst != wxCONFIG_PATH_SEPARATOR )
                            {
                                dst--;
                            }
                        }
                        else // the position of last slash was stored
                        {
                            // go directly there
                            dst = start + posLastSlash;

                            // invalidate posLastSlash
                            posLastSlash = -1;
                        }

                        // we must have found a slash one way or another!
                        wxASSERT_MSG( *dst == wxCONFIG_PATH_SEPARATOR,
                                      wxT("error in wxRegConfig::SetPath") );

                        // stay at the same position
                        dst--;

                        // we killed one
                        totalSlashes--;
                    }

                    // skip both dots
                    src += 2;
                }
                else // not "/.."
                {
                    if ( (dst == start) || (dst[-1] != wxCONFIG_PATH_SEPARATOR) )
                    {
                        *dst = wxCONFIG_PATH_SEPARATOR;

                        posLastSlash = dst - start;

                        totalSlashes++;
                    }
                    else // previous char was a slash too
                    {
                        // squeeze several subsequent slashes into one: i.e.
                        // just ignore this one
                        dst--;
                    }
                }
            }
            else // normal character
            {
                // just copy
                *dst = *src;
            }
        }

        // NUL terminate the string
        if ( dst[-1] == wxCONFIG_PATH_SEPARATOR && (dst != start + 1) )
        {
            // if it has a trailing slash we remove it unless it is the only
            // string character
            dst--;
        }

        *dst = wxT('\0');
        buf.SetLength(dst - start);
    }

#ifdef WX_DEBUG_SET_PATH
    wxASSERT( m_strPath == m_strPathAlt );
#endif

    if ( m_strPath == strOldPath )
        return;

    // registry APIs want backslashes instead of slashes
    wxString strRegPath;
    if ( !m_strPath.empty() )
    {
        size_t len = m_strPath.length();

        const wxChar *src = m_strPath.c_str();
        wxStringBufferLength buf(strRegPath, len);
        wxChar *dst = buf;

        const wxChar *end = src + len;
        for ( ; src < end; src++, dst++ )
        {
            if ( *src == wxCONFIG_PATH_SEPARATOR )
                *dst = wxT('\\');
            else
                *dst = *src;
        }

        buf.SetLength(len);
    }

    // this is not needed any longer as we don't create keys unnecessarily any
    // more (now it is done on demand, i.e. only when they're going to contain
    // something)
#if 0
    // as we create the registry key when SetPath(key) is done, we can be left
    // with plenty of empty keys if this was only done to try to read some
    // value which, in fact, doesn't exist - to prevent this from happening we
    // automatically delete the old key if it was empty
    if ( m_keyLocal.Exists() && LocalKey().IsEmpty() )
    {
        m_keyLocal.DeleteSelf();
    }
#endif // 0

    // change current key(s)
    m_keyLocal.SetName(m_keyLocalRoot, strRegPath);

    if ( GetStyle() & wxCONFIG_USE_GLOBAL_FILE )
    {
      m_keyGlobal.SetName(m_keyGlobalRoot, strRegPath);

      wxLogNull nolog;
      m_keyGlobal.Open(wxRegKey::Read);
    }
}
Example #18
0
/* static */
wxProtocolError wxProtocol::ReadLine(wxSocketBase *sock, wxString& result)
{
    static const int LINE_BUF = 4095;

    result.clear();

    wxCharBuffer buf(LINE_BUF);
    char *pBuf = buf.data();
    while ( sock->WaitForRead() )
    {
        // peek at the socket to see if there is a CRLF
        sock->Peek(pBuf, LINE_BUF);

        size_t nRead = sock->LastCount();
        if ( !nRead && sock->Error() )
            return wxPROTO_NETERR;

        // look for "\r\n" paying attention to a special case: "\r\n" could
        // have been split by buffer boundary, so check also for \r at the end
        // of the last chunk and \n at the beginning of this one
        pBuf[nRead] = '\0';
        const char *eol = strchr(pBuf, '\n');

        // if we found '\n', is there a '\r' as well?
        if ( eol )
        {
            if ( eol == pBuf )
            {
                // check for case of "\r\n" being split
                if ( result.empty() || result.Last() != wxT('\r') )
                {
                    // ignore the stray '\n'
                    eol = NULL;
                }
                //else: ok, got real EOL

                // read just this '\n' and restart
                nRead = 1;
            }
            else // '\n' in the middle of the buffer
            {
                // in any case, read everything up to and including '\n'
                nRead = eol - pBuf + 1;

                if ( eol[-1] != '\r' )
                {
                    // as above, simply ignore stray '\n'
                    eol = NULL;
                }
            }
        }

        sock->Read(pBuf, nRead);
        if ( sock->LastCount() != nRead )
            return wxPROTO_NETERR;

        pBuf[nRead] = '\0';
        result += wxString::FromAscii(pBuf);

        if ( eol )
        {
            // remove trailing "\r\n"
            result.RemoveLast(2);

            return wxPROTO_NOERR;
        }
    }

    return wxPROTO_NETERR;
}
Example #19
0
wxString wxTextBuffer::Translate(const wxString& text, wxTextFileType type)
{
    // don't do anything if there is nothing to do
    if ( type == wxTextFileType_None )
        return text;

    // nor if it is empty
    if ( text.empty() )
        return text;

    wxString eol = GetEOL(type), result;

    // optimization: we know that the length of the new string will be about
    // the same as the length of the old one, so prealloc memory to avoid
    // unnecessary relocations
    result.Alloc(text.Len());

    wxChar chLast = 0;
    for ( wxString::const_iterator i = text.begin(); i != text.end(); ++i )
    {
        wxChar ch = *i;
        switch ( ch ) {
            case wxT('\n'):
                // Dos/Unix line termination
                result += eol;
                chLast = 0;
                break;

            case wxT('\r'):
                if ( chLast == wxT('\r') ) {
                    // Mac empty line
                    result += eol;
                }
                else {
                    // just remember it: we don't know whether it is just "\r"
                    // or "\r\n" yet
                    chLast = wxT('\r');
                }
                break;

            default:
                if ( chLast == wxT('\r') ) {
                    // Mac line termination
                    result += eol;

                    // reset chLast to avoid inserting another eol before the
                    // next character
                    chLast = 0;
                }

                // add to the current line
                result += ch;
        }
    }

    if ( chLast ) {
        // trailing '\r'
        result += eol;
    }

    return result;
}
bool S3D_CACHE::getSHA1( const wxString& aFileName, unsigned char* aSHA1Sum )
{
    if( aFileName.empty() )
    {
        #ifdef DEBUG
        do {
            std::ostringstream ostr;
            ostr << __FILE__ << ": " << __FUNCTION__ << ": " << __LINE__ << "\n";
            ostr << " * [BUG] empty filename";
            wxLogTrace( MASK_3D_CACHE, "%s\n", ostr.str().c_str() );
        } while( 0 );
        #endif

        return false;
    }

    if( NULL == aSHA1Sum )
    {
        #ifdef DEBUG
        do {
            std::ostringstream ostr;
            ostr << __FILE__ << ": " << __FUNCTION__ << ": " << __LINE__ << "\n";
            ostr << " * [BUG] NULL pointer passed for aMD5Sum";
            wxLogTrace( MASK_3D_CACHE, "%s\n", ostr.str().c_str() );
        } while( 0 );
        #endif

        return false;
    }

    FILE* fp = fopen( aFileName.ToUTF8(), "rb" );

    if( NULL == fp )
        return false;

    boost::uuids::detail::sha1 dblock;
    unsigned char block[4096];
    size_t bsize = 0;

    while( ( bsize = fread( &block, 1, 4096, fp ) ) > 0 )
        dblock.process_bytes( block, bsize );

    fclose( fp );
    unsigned int digest[5];
    dblock.get_digest( digest );

    // ensure MSB order
    for( int i = 0; i < 5; ++i )
    {
        int idx = i << 2;
        unsigned int tmp = digest[i];
        aSHA1Sum[idx+3] = tmp & 0xff;
        tmp >>= 8;
        aSHA1Sum[idx+2] = tmp & 0xff;
        tmp >>= 8;
        aSHA1Sum[idx+1] = tmp & 0xff;
        tmp >>= 8;
        aSHA1Sum[idx] = tmp & 0xff;
    }

    return true;
}
Example #21
0
void wxGenericAboutDialog::AddText(const wxString& text)
{
    if ( !text.empty() )
        AddControl(new wxStaticText(this, wxID_ANY, text));
}
Example #22
0
static wxString GetGtkHotKey( const wxMenuItem& item )
{
    wxString hotkey;

    wxAcceleratorEntry *accel = item.GetAccel();
    if ( accel )
    {
        int flags = accel->GetFlags();
        if ( flags & wxACCEL_ALT )
            hotkey += wxT("<alt>");
        if ( flags & wxACCEL_CTRL )
            hotkey += wxT("<control>");
        if ( flags & wxACCEL_SHIFT )
            hotkey += wxT("<shift>");

        int code = accel->GetKeyCode();
        switch ( code )
        {
            case WXK_F1:
            case WXK_F2:
            case WXK_F3:
            case WXK_F4:
            case WXK_F5:
            case WXK_F6:
            case WXK_F7:
            case WXK_F8:
            case WXK_F9:
            case WXK_F10:
            case WXK_F11:
            case WXK_F12:
            case WXK_F13:
            case WXK_F14:
            case WXK_F15:
            case WXK_F16:
            case WXK_F17:
            case WXK_F18:
            case WXK_F19:
            case WXK_F20:
            case WXK_F21:
            case WXK_F22:
            case WXK_F23:
            case WXK_F24:
                hotkey += wxString::Format(wxT("F%d"), code - WXK_F1 + 1);
                break;

                // TODO: we should use gdk_keyval_name() (a.k.a.
                //       XKeysymToString) here as well as hardcoding the keysym
                //       names this might be not portable
           case WXK_INSERT:
                hotkey << wxT("Insert" );
                break;
            case WXK_DELETE:
                hotkey << wxT("Delete" );
                break;
            case WXK_UP:
                hotkey << wxT("Up" );
                break;
            case WXK_DOWN:
                hotkey << wxT("Down" );
                break;
            case WXK_PAGEUP:
                hotkey << wxT("Page_Up" );
                break;
            case WXK_PAGEDOWN:
                hotkey << wxT("Page_Down" );
                break;
            case WXK_LEFT:
                hotkey << wxT("Left" );
                break;
            case WXK_RIGHT:
                hotkey << wxT("Right" );
                break;
            case WXK_HOME:
                hotkey << wxT("Home" );
                break;
            case WXK_END:
                hotkey << wxT("End" );
                break;
            case WXK_RETURN:
                hotkey << wxT("Return" );
                break;
            case WXK_BACK:
                hotkey << wxT("BackSpace" );
                break;
            case WXK_TAB:
                hotkey << wxT("Tab" );
                break;
            case WXK_ESCAPE:
                hotkey << wxT("Esc" );
                break;
            case WXK_SPACE:
                hotkey << wxT("space" );
                break;
            case WXK_MULTIPLY:
                hotkey << wxT("Multiply" );
                break;
            case WXK_ADD:
                hotkey << wxT("Add" );
                break;
            case WXK_SEPARATOR:
                hotkey << wxT("Separator" );
                break;
            case WXK_SUBTRACT:
                hotkey << wxT("Subtract" );
                break;
            case WXK_DECIMAL:
                hotkey << wxT("Decimal" );
                break;
            case WXK_DIVIDE:
                hotkey << wxT("Divide" );
                break;
            case WXK_CANCEL:
                hotkey << wxT("Cancel" );
                break;
            case WXK_CLEAR:
                hotkey << wxT("Clear" );
                break;
            case WXK_MENU:
                hotkey << wxT("Menu" );
                break;
            case WXK_PAUSE:
                hotkey << wxT("Pause" );
                break;
            case WXK_CAPITAL:
                hotkey << wxT("Capital" );
                break;
            case WXK_SELECT:
                hotkey << wxT("Select" );
                break;
            case WXK_PRINT:
                hotkey << wxT("Print" );
                break;
            case WXK_EXECUTE:
                hotkey << wxT("Execute" );
                break;
            case WXK_SNAPSHOT:
                hotkey << wxT("Snapshot" );
                break;
            case WXK_HELP:
                hotkey << wxT("Help" );
                break;
            case WXK_NUMLOCK:
                hotkey << wxT("Num_Lock" );
                break;
            case WXK_SCROLL:
                hotkey << wxT("Scroll_Lock" );
                break;
            case WXK_NUMPAD_INSERT:
                hotkey << wxT("KP_Insert" );
                break;
            case WXK_NUMPAD_DELETE:
                hotkey << wxT("KP_Delete" );
                break;
             case WXK_NUMPAD_SPACE:
                hotkey << wxT("KP_Space" );
                break;
            case WXK_NUMPAD_TAB:
                hotkey << wxT("KP_Tab" );
                break;
            case WXK_NUMPAD_ENTER:
                hotkey << wxT("KP_Enter" );
                break;
            case WXK_NUMPAD_F1: case WXK_NUMPAD_F2: case WXK_NUMPAD_F3:
            case WXK_NUMPAD_F4:
                hotkey += wxString::Format(wxT("KP_F%d"), code - WXK_NUMPAD_F1 + 1);
                break;
            case WXK_NUMPAD_HOME:
                hotkey << wxT("KP_Home" );
                break;
            case WXK_NUMPAD_LEFT:
                hotkey << wxT("KP_Left" );
                break;
             case WXK_NUMPAD_UP:
                hotkey << wxT("KP_Up" );
                break;
            case WXK_NUMPAD_RIGHT:
                hotkey << wxT("KP_Right" );
                break;
            case WXK_NUMPAD_DOWN:
                hotkey << wxT("KP_Down" );
                break;
            case WXK_NUMPAD_PAGEUP:
                hotkey << wxT("KP_Page_Up" );
                break;
            case WXK_NUMPAD_PAGEDOWN:
                hotkey << wxT("KP_Page_Down" );
                break;
            case WXK_NUMPAD_END:
                hotkey << wxT("KP_End" );
                break;
            case WXK_NUMPAD_BEGIN:
                hotkey << wxT("KP_Begin" );
                break;
            case WXK_NUMPAD_EQUAL:
                hotkey << wxT("KP_Equal" );
                break;
            case WXK_NUMPAD_MULTIPLY:
                hotkey << wxT("KP_Multiply" );
                break;
            case WXK_NUMPAD_ADD:
                hotkey << wxT("KP_Add" );
                break;
            case WXK_NUMPAD_SEPARATOR:
                hotkey << wxT("KP_Separator" );
                break;
            case WXK_NUMPAD_SUBTRACT:
                hotkey << wxT("KP_Subtract" );
                break;
            case WXK_NUMPAD_DECIMAL:
                hotkey << wxT("KP_Decimal" );
                break;
            case WXK_NUMPAD_DIVIDE:
                hotkey << wxT("KP_Divide" );
                break;
           case WXK_NUMPAD0: case WXK_NUMPAD1: case WXK_NUMPAD2:
           case WXK_NUMPAD3: case WXK_NUMPAD4: case WXK_NUMPAD5:
           case WXK_NUMPAD6: case WXK_NUMPAD7: case WXK_NUMPAD8: case WXK_NUMPAD9:
                hotkey += wxString::Format(wxT("KP_%d"), code - WXK_NUMPAD0);
                break;
            case WXK_WINDOWS_LEFT:
                hotkey << wxT("Super_L" );
                break;
            case WXK_WINDOWS_RIGHT:
                hotkey << wxT("Super_R" );
                break;
            case WXK_WINDOWS_MENU:
                hotkey << wxT("Menu" );
                break;
            case WXK_COMMAND:
                hotkey << wxT("Command" );
                break;
          /* These probably wouldn't work as there is no SpecialX in gdk/keynames.txt
            case WXK_SPECIAL1: case WXK_SPECIAL2: case WXK_SPECIAL3: case WXK_SPECIAL4:
            case WXK_SPECIAL5: case WXK_SPECIAL6: case WXK_SPECIAL7: case WXK_SPECIAL8:
            case WXK_SPECIAL9:  case WXK_SPECIAL10:  case WXK_SPECIAL11: case WXK_SPECIAL12:
            case WXK_SPECIAL13: case WXK_SPECIAL14: case WXK_SPECIAL15: case WXK_SPECIAL16:
            case WXK_SPECIAL17: case WXK_SPECIAL18: case WXK_SPECIAL19:  case WXK_SPECIAL20:
                hotkey += wxString::Format(wxT("Special%d"), code - WXK_SPECIAL1 + 1);
                break;
          */
                // if there are any other keys wxAcceleratorEntry::Create() may
                // return, we should process them here

            default:
                if ( code < 127 )
                {
                    const wxString
                        name = wxGTK_CONV_BACK_SYS(gdk_keyval_name((guint)code));
                    if ( !name.empty() )
                    {
                        hotkey << name;
                        break;
                    }
                }

                wxFAIL_MSG( wxT("unknown keyboard accel") );
        }

        delete accel;
    }

    return hotkey;
}
Example #23
0
static wxNativeFont wxLoadQueryFont(int pointSize,
                                    wxFontFamily family,
                                    wxFontStyle style,
                                    wxFontWeight weight,
                                    bool WXUNUSED(underlined),
                                    const wxString& facename,
                                    const wxString& xregistry,
                                    const wxString& xencoding,
                                    wxString* xFontName)
{
    wxString xfamily("*");
    switch (family)
    {
        case wxFONTFAMILY_DECORATIVE: xfamily = wxT("lucida"); break;
        case wxFONTFAMILY_ROMAN:      xfamily = wxT("times");  break;
        case wxFONTFAMILY_MODERN:     xfamily = wxT("courier"); break;
        case wxFONTFAMILY_SWISS:      xfamily = wxT("helvetica"); break;
        case wxFONTFAMILY_TELETYPE:   xfamily = wxT("lucidatypewriter"); break;
        case wxFONTFAMILY_SCRIPT:     xfamily = wxT("utopia"); break;
    }
#if wxUSE_NANOX
    int xweight;
    switch (weight)
    {
         case wxFONTWEIGHT_BOLD:
             {
                 xweight = MWLF_WEIGHT_BOLD;
                 break;
             }
        case wxFONTWEIGHT_LIGHT:
             {
                 xweight = MWLF_WEIGHT_LIGHT;
                 break;
             }
         case wxFONTWEIGHT_NORMAL:
             {
                 xweight = MWLF_WEIGHT_NORMAL;
                 break;
             }

     default:
             {
                 xweight = MWLF_WEIGHT_DEFAULT;
                 break;
             }
    }
    GR_SCREEN_INFO screenInfo;
    GrGetScreenInfo(& screenInfo);

    int yPixelsPerCM = screenInfo.ydpcm;

    // A point is 1/72 of an inch.
    // An inch is 2.541 cm.
    // So pixelHeight = (pointSize / 72) (inches) * 2.541 (for cm) * yPixelsPerCM (for pixels)
    // In fact pointSize is 10 * the normal point size so
    // divide by 10.

    int pixelHeight = (int) ( (((float)pointSize) / 720.0) * 2.541 * (float) yPixelsPerCM) ;

    // An alternative: assume that the screen is 72 dpi.
    //int pixelHeight = (int) (((float)pointSize / 720.0) * 72.0) ;
    //int pixelHeight = (int) ((float)pointSize / 10.0) ;

    GR_LOGFONT logFont;
    logFont.lfHeight = pixelHeight;
    logFont.lfWidth = 0;
    logFont.lfEscapement = 0;
    logFont.lfOrientation = 0;
    logFont.lfWeight = xweight;
    logFont.lfItalic = (style == wxFONTSTYLE_ITALIC ? 0 : 1) ;
    logFont.lfUnderline = 0;
    logFont.lfStrikeOut = 0;
    logFont.lfCharSet = MWLF_CHARSET_DEFAULT; // TODO: select appropriate one
    logFont.lfOutPrecision = MWLF_TYPE_DEFAULT;
    logFont.lfClipPrecision = 0; // Not used
    logFont.lfRoman = (family == wxROMAN ? 1 : 0) ;
    logFont.lfSerif = (family == wxSWISS ? 0 : 1) ;
    logFont.lfSansSerif = !logFont.lfSerif ;
    logFont.lfModern = (family == wxMODERN ? 1 : 0) ;
    logFont.lfProportional = (family == wxTELETYPE ? 0 : 1) ;
    logFont.lfOblique = 0;
    logFont.lfSmallCaps = 0;
    logFont.lfPitch = 0; // 0 = default
    strcpy(logFont.lfFaceName, facename.c_str());

    XFontStruct* fontInfo = (XFontStruct*) malloc(sizeof(XFontStruct));
    fontInfo->fid = GrCreateFont((GR_CHAR*) facename.c_str(), pixelHeight, & logFont);
    GrGetFontInfo(fontInfo->fid, & fontInfo->info);
    return (wxNativeFont) fontInfo;

#else
    wxString fontSpec;
    if (!facename.empty())
    {
        fontSpec.Printf(wxT("-*-%s-*-*-normal-*-*-*-*-*-*-*-*-*"),
                        facename.c_str());

        if ( wxTestFontSpec(fontSpec) )
        {
            xfamily = facename;
        }
        //else: no such family, use default one instead
    }

    wxString xstyle;
    switch (style)
    {
        case wxFONTSTYLE_SLANT:
            fontSpec.Printf(wxT("-*-%s-*-o-*-*-*-*-*-*-*-*-*-*"),
                    xfamily.c_str());
            if ( wxTestFontSpec(fontSpec) )
            {
                xstyle = wxT("o");
                break;
            }
            // fall through - try wxFONTSTYLE_ITALIC now

        case wxFONTSTYLE_ITALIC:
            fontSpec.Printf(wxT("-*-%s-*-i-*-*-*-*-*-*-*-*-*-*"),
                    xfamily.c_str());
            if ( wxTestFontSpec(fontSpec) )
            {
                xstyle = wxT("i");
            }
            else if ( style == wxFONTSTYLE_ITALIC ) // and not wxFONTSTYLE_SLANT
            {
                // try wxFONTSTYLE_SLANT
                fontSpec.Printf(wxT("-*-%s-*-o-*-*-*-*-*-*-*-*-*-*"),
                        xfamily.c_str());
                if ( wxTestFontSpec(fontSpec) )
                {
                    xstyle = wxT("o");
                }
                else
                {
                    // no italic, no slant - leave default
                    xstyle = wxT("*");
                }
            }
            break;

        default:
            wxFAIL_MSG(wxT("unknown font style"));
            // fall back to normal

        case wxFONTSTYLE_NORMAL:
            xstyle = wxT("r");
            break;
    }

    wxString xweight;
    switch (weight)
    {
         case wxFONTWEIGHT_BOLD:
             {
                  fontSpec.Printf(wxT("-*-%s-bold-*-*-*-*-*-*-*-*-*-*-*"),
                         xfamily.c_str());
                  if ( wxTestFontSpec(fontSpec) )
                  {
                       xweight = wxT("bold");
                       break;
                  }
                  fontSpec.Printf(wxT("-*-%s-heavy-*-*-*-*-*-*-*-*-*-*-*"),
                         xfamily.c_str());
                  if ( wxTestFontSpec(fontSpec) )
                  {
                       xweight = wxT("heavy");
                       break;
                  }
                  fontSpec.Printf(wxT("-*-%s-extrabold-*-*-*-*-*-*-*-*-*-*-*"),
                         xfamily.c_str());
                  if ( wxTestFontSpec(fontSpec) )
                  {
                      xweight = wxT("extrabold");
                      break;
                  }
                  fontSpec.Printf(wxT("-*-%s-demibold-*-*-*-*-*-*-*-*-*-*-*"),
                         xfamily.c_str());
                  if ( wxTestFontSpec(fontSpec) )
                  {
                      xweight = wxT("demibold");
                      break;
                  }
                  fontSpec.Printf(wxT("-*-%s-black-*-*-*-*-*-*-*-*-*-*-*"),
                         xfamily.c_str());
                  if ( wxTestFontSpec(fontSpec) )
                  {
                      xweight = wxT("black");
                      break;
                  }
                  fontSpec.Printf(wxT("-*-%s-ultrablack-*-*-*-*-*-*-*-*-*-*-*"),
                         xfamily.c_str());
                  if ( wxTestFontSpec(fontSpec) )
                  {
                      xweight = wxT("ultrablack");
                      break;
                  }
              }
              break;
        case wxFONTWEIGHT_LIGHT:
             {
                  fontSpec.Printf(wxT("-*-%s-light-*-*-*-*-*-*-*-*-*-*-*"),
                         xfamily.c_str());
                  if ( wxTestFontSpec(fontSpec) )
                  {
                       xweight = wxT("light");
                       break;
                  }
                  fontSpec.Printf(wxT("-*-%s-thin-*-*-*-*-*-*-*-*-*-*-*"),
                         xfamily.c_str());
                  if ( wxTestFontSpec(fontSpec) )
                  {
                       xweight = wxT("thin");
                       break;
                  }
             }
             break;
         case wxFONTWEIGHT_NORMAL:
             {
                  fontSpec.Printf(wxT("-*-%s-medium-*-*-*-*-*-*-*-*-*-*-*"),
                         xfamily.c_str());
                  if ( wxTestFontSpec(fontSpec) )
                  {
                       xweight = wxT("medium");
                       break;
                  }
                  fontSpec.Printf(wxT("-*-%s-normal-*-*-*-*-*-*-*-*-*-*-*"),
                         xfamily.c_str());
                  if ( wxTestFontSpec(fontSpec) )
                  {
                       xweight = wxT("normal");
                       break;
                  }
                  fontSpec.Printf(wxT("-*-%s-regular-*-*-*-*-*-*-*-*-*-*-*"),
                         xfamily.c_str());
                  if ( wxTestFontSpec(fontSpec) )
                  {
                      xweight = wxT("regular");
                      break;
                  }
                  xweight = wxT("*");
              }
              break;
        default:           xweight = wxT("*"); break;
    }

    // if pointSize is -1, don't specify any
    wxString sizeSpec;
    if ( pointSize == -1 )
    {
        sizeSpec = wxT('*');
    }
    else
    {
        sizeSpec.Printf(wxT("%d"), pointSize);
    }

    // construct the X font spec from our data
    fontSpec.Printf(wxT("-*-%s-%s-%s-normal-*-*-%s-*-*-*-*-%s-%s"),
                    xfamily.c_str(), xweight.c_str(), xstyle.c_str(),
                    sizeSpec.c_str(), xregistry.c_str(), xencoding.c_str());

    if( xFontName )
        *xFontName = fontSpec;

    return wxLoadFont(fontSpec);
#endif
    // wxUSE_NANOX
}
Example #24
0
const RemoteProfile* eSettings::GetRemoteProfileFromUrl(const wxString& url, bool withDir) {
	// Split url up in elements
	wxRegEx reUrl(wxT("([[:alpha:]]+)://(([^:@]*):([^:@]*)@)?([^/]+)(.*)"));
	if (!reUrl.Matches(url)) return NULL; // invalid url

	const wxString protocol = reUrl.GetMatch(url, 1);
	const wxString username = reUrl.GetMatch(url, 3);
	const wxString pwd = reUrl.GetMatch(url, 4);
	const wxString address = reUrl.GetMatch(url, 5);
	const wxString dir = reUrl.GetMatch(url, 6);
	const wxString sDir = StripSlashes(dir);

	// See if we can find a matching profile in cache
	for (auto_vector<RemoteProfile>::iterator p = m_tempRemotes.begin(); p != m_tempRemotes.end(); ++p) {
		RemoteProfile* rp = (*p);
		if (rp->IsActive() && rp->m_address == address && rp->m_protocol == protocol) {
			if (!username.empty() && rp->m_username != username) continue;
			if (withDir && StripSlashes(rp->m_dir) != sDir) continue;
			if (!pwd.empty() && rp->m_pwd != pwd) {
				rp->m_pwd = pwd; // Password may have changed
				if (!rp->IsTemp()) SaveRemoteProfile(rp);
			}
			return rp;
		}
	}

	// See if we can find a matching profile in settings
	const wxJSONValue remotes = m_jsonRoot.ItemAt(wxT("remoteProfiles"));
	const int profile_count = remotes.Size();
	for (int i = 0; i < profile_count; ++i) {
		const wxJSONValue profile = remotes.ItemAt(i);
		if (profile.ItemAt(wxT("address")).AsString() != address) continue;

		// Ftp is default protocol
		wxString prot = profile.ItemAt(wxT("protocol")).AsString();
		if (prot.empty()) prot = wxT("ftp");

		if (prot != protocol) continue; // ftp is default
		if (!username.empty() && profile.ItemAt(wxT("username")).AsString() != username) continue;

		RemoteProfile* rp = DoGetRemoteProfile(i);
		if (withDir && StripSlashes(rp->m_dir) != sDir) continue;

		// Password may have changed
		if (!pwd.empty() && rp->m_pwd != pwd) {
			rp->m_pwd = pwd;
			SaveRemoteProfile(rp);
		}

		return rp;
	}

	// Add new temp profile
	auto_ptr<RemoteProfile> newRp(new RemoteProfile());
	newRp->m_protocol = protocol;
	newRp->m_name = address;
	newRp->m_address = address;
	newRp->m_dir = dir;
	newRp->m_username = username;
	newRp->m_pwd = pwd;
	m_tempRemotes.push_back(newRp);
	return m_tempRemotes.back();
}
Example #25
0
bool wxTextCtrl::Create( wxWindow *parent,
                         wxWindowID id,
                         const wxString &value,
                         const wxPoint &pos,
                         const wxSize &size,
                         long style,
                         const wxValidator& validator,
                         const wxString &name )
{
    m_needParent = true;
    m_acceptsFocus = true;

    if (!PreCreation( parent, pos, size ) ||
            !CreateBase( parent, id, pos, size, style, validator, name ))
    {
        wxFAIL_MSG( wxT("wxTextCtrl creation failed") );
        return false;
    }


    m_vScrollbarVisible = false;

    bool multi_line = (style & wxTE_MULTILINE) != 0;

    if (multi_line)
    {
        // create our control ...
        m_text = gtk_text_new( NULL, NULL );

        // ... and put into the upper left hand corner of the table
        bool bHasHScrollbar = false;
        m_widget = gtk_table_new(bHasHScrollbar ? 2 : 1, 2, FALSE);
        GTK_WIDGET_UNSET_FLAGS( m_widget, GTK_CAN_FOCUS );
        gtk_table_attach( GTK_TABLE(m_widget), m_text, 0, 1, 0, 1,
                          (GtkAttachOptions)(GTK_FILL | GTK_EXPAND | GTK_SHRINK),
                          (GtkAttachOptions)(GTK_FILL | GTK_EXPAND | GTK_SHRINK),
                          0, 0);

        // always wrap words
        gtk_text_set_word_wrap( GTK_TEXT(m_text), TRUE );

        // finally, put the vertical scrollbar in the upper right corner
        m_vScrollbar = gtk_vscrollbar_new( GTK_TEXT(m_text)->vadj );
        GTK_WIDGET_UNSET_FLAGS( m_vScrollbar, GTK_CAN_FOCUS );
        gtk_table_attach(GTK_TABLE(m_widget), m_vScrollbar, 1, 2, 0, 1,
                         GTK_FILL,
                         (GtkAttachOptions)(GTK_EXPAND | GTK_FILL | GTK_SHRINK),
                         0, 0);
    }
    else
    {
        // a single-line text control: no need for scrollbars
        m_widget =
            m_text = gtk_entry_new();
    }

    m_parent->DoAddChild( this );

    m_focusWidget = m_text;

    PostCreation(size);

    if (multi_line)
        gtk_widget_show(m_text);

    if (multi_line)
    {
        gtk_signal_connect(GTK_OBJECT(GTK_TEXT(m_text)->vadj), "changed",
                           (GtkSignalFunc) gtk_scrollbar_changed_callback, (gpointer) this );

        // only initialize gs_gtk_text_draw once, starting from the next the
        // klass::draw will already be wxgtk_text_draw
        if ( !gs_gtk_text_draw )
        {
            GtkDrawCallback&
            draw = GTK_WIDGET_CLASS(GTK_OBJECT(m_text)->klass)->draw;

            gs_gtk_text_draw = draw;

            draw = wxgtk_text_draw;
        }
    }

    if (!value.empty())
    {
#if !GTK_CHECK_VERSION(1, 2, 0)
        // if we don't realize it, GTK 1.0.6 dies with a SIGSEGV in
        // gtk_editable_insert_text()
        gtk_widget_realize(m_text);
#endif // GTK 1.0

        gint tmp = 0;
#if wxUSE_UNICODE
        wxWX2MBbuf val = value.mbc_str();
        gtk_editable_insert_text( GTK_EDITABLE(m_text), val, strlen(val), &tmp );
#else
        gtk_editable_insert_text( GTK_EDITABLE(m_text), value, value.length(), &tmp );
#endif

        if (multi_line)
        {
            // Bring editable's cursor uptodate. Bug in GTK.
            SET_EDITABLE_POS(m_text, gtk_text_get_point( GTK_TEXT(m_text) ));
        }
    }

    if (style & wxTE_PASSWORD)
    {
        if (!multi_line)
            gtk_entry_set_visibility( GTK_ENTRY(m_text), FALSE );
    }

    if (style & wxTE_READONLY)
    {
        if (!multi_line)
            gtk_entry_set_editable( GTK_ENTRY(m_text), FALSE );
    }
    else
    {
        if (multi_line)
            gtk_text_set_editable( GTK_TEXT(m_text), 1 );
    }

    // We want to be notified about text changes.
    gtk_signal_connect( GTK_OBJECT(m_text), "changed",
                        GTK_SIGNAL_FUNC(gtk_text_changed_callback), (gpointer)this);

    m_cursor = wxCursor( wxCURSOR_IBEAM );

    wxTextAttr attrDef(GetForegroundColour(), GetBackgroundColour(), GetFont());
    SetDefaultStyle( attrDef );

    return true;
}
Example #26
0
wxString eSettings::StripSlashes(const wxString& path) { // static
	if (path.empty() || path == wxT('/')) return wxEmptyString;
	const size_t start = (path[0] == wxT('/')) ? 1 : 0;
	const size_t end = (path.Last() ==  wxT('/')) ? path.size()-1 : path.size();
	return path.substr(start, end-start);
}
Example #27
0
wxGridCellEnumRenderer::wxGridCellEnumRenderer(const wxString& choices)
{
    if (!choices.empty())
        SetParameters(choices);
}
Example #28
0
bool wxSpinCtrl::Create(wxWindow *parent,
                        wxWindowID id,
                        const wxString& value,
                        const wxPoint& pos,
                        const wxSize& size,
                        long style,
                        int min, int max, int initial,
                        const wxString& name)
{
    m_blockEvent = false;

    // this should be in ctor/init function but I don't want to add one to 2.8
    // to avoid problems with default ctor which can be inlined in the user
    // code and so might not get this fix without recompilation
    m_oldValue = INT_MIN;

    // before using DoGetBestSize(), have to set style to let the base class
    // know whether this is a horizontal or vertical control (we're always
    // vertical)
    style |= wxSP_VERTICAL;

    if ( (style & wxBORDER_MASK) == wxBORDER_DEFAULT )
#ifdef __WXWINCE__
        style |= wxBORDER_SIMPLE;
#else
        style |= wxBORDER_SUNKEN;
#endif

    SetWindowStyle(style);

    WXDWORD exStyle = 0;
    WXDWORD msStyle = MSWGetStyle(GetWindowStyle(), & exStyle) ;

    // propagate text alignment style to text ctrl
    if ( style & wxALIGN_RIGHT )
        msStyle |= ES_RIGHT;
    else if ( style & wxALIGN_CENTER )
        msStyle |= ES_CENTER;

    // calculate the sizes: the size given is the total size for both controls
    // and we need to fit them both in the given width (height is the same)
    wxSize sizeText(size), sizeBtn(size);
    sizeBtn.x = wxSpinButton::DoGetBestSize().x;
    if ( sizeText.x <= 0 )
    {
        // DEFAULT_ITEM_WIDTH is the default width for the text control
        sizeText.x = DEFAULT_ITEM_WIDTH + MARGIN_BETWEEN + sizeBtn.x;
    }

    sizeText.x -= sizeBtn.x + MARGIN_BETWEEN;
    if ( sizeText.x <= 0 )
    {
        wxLogDebug(wxT("not enough space for wxSpinCtrl!"));
    }

    wxPoint posBtn(pos);
    posBtn.x += sizeText.x + MARGIN_BETWEEN;

    // we must create the text control before the spin button for the purpose
    // of the dialog navigation: if there is a static text just before the spin
    // control, activating it by Alt-letter should give focus to the text
    // control, not the spin and the dialog navigation code will give focus to
    // the next control (at Windows level), not the one after it

    // create the text window

    m_hwndBuddy = (WXHWND)::CreateWindowEx
                    (
                     exStyle,                // sunken border
                     wxT("EDIT"),             // window class
                     NULL,                   // no window title
                     msStyle,                // style (will be shown later)
                     pos.x, pos.y,           // position
                     0, 0,                   // size (will be set later)
                     GetHwndOf(parent),      // parent
                     (HMENU)-1,              // control id
                     wxGetInstance(),        // app instance
                     NULL                    // unused client data
                    );

    if ( !m_hwndBuddy )
    {
        wxLogLastError(wxT("CreateWindow(buddy text window)"));

        return false;
    }


    // create the spin button
    if ( !wxSpinButton::Create(parent, id, posBtn, sizeBtn, style, name) )
    {
        return false;
    }

    wxSpinButtonBase::SetRange(min, max);

    // subclass the text ctrl to be able to intercept some events
    wxSetWindowUserData(GetBuddyHwnd(), this);
    m_wndProcBuddy = (WXFARPROC)wxSetWindowProc(GetBuddyHwnd(),
                                                wxBuddyTextWndProc);

    // set up fonts and colours  (This is nomally done in MSWCreateControl)
    InheritAttributes();
    if (!m_hasFont)
        SetFont(GetDefaultAttributes().font);

    // set the size of the text window - can do it only now, because we
    // couldn't call DoGetBestSize() before as font wasn't set
    if ( sizeText.y <= 0 )
    {
        int cx, cy;
        wxGetCharSize(GetHWND(), &cx, &cy, GetFont());

        sizeText.y = EDIT_HEIGHT_FROM_CHAR_HEIGHT(cy);
    }

    SetInitialSize(size);

    (void)::ShowWindow(GetBuddyHwnd(), SW_SHOW);

    // associate the text window with the spin button
    (void)::SendMessage(GetHwnd(), UDM_SETBUDDY, (WPARAM)m_hwndBuddy, 0);

    SetValue(initial);

    // Set the range in the native control
    SetRange(min, max);

    if ( !value.empty() )
    {
        SetValue(value);
        m_oldValue = (int) wxAtol(value);
    }
    else
    {
        SetValue(wxString::Format(wxT("%d"), initial));
        m_oldValue = initial;
    }

    // do it after finishing with m_hwndBuddy creation to avoid generating
    // initial wxEVT_COMMAND_TEXT_UPDATED message
    ms_allSpins.Add(this);

    return true;
}
Example #29
0
bool
wxProgressDialog::Update(int value, const wxString& newmsg, bool *skip)
{
    wxASSERT_MSG( value == -1 || m_gauge, wxT("cannot update non existent dialog") );

#ifdef __WXMSW__
    value /= m_factor;
#endif // __WXMSW__

    wxASSERT_MSG( value <= m_maximum, wxT("invalid progress value") );

    // fill up the gauge if value == maximum because this means that the dialog
    // is going to close and the gauge shouldn't be partly empty in this case
    if ( m_gauge && value <= m_maximum )
    {
        m_gauge->SetValue(value == m_maximum ? value : value + 1);
    }

    if ( !newmsg.empty() && newmsg != m_msg->GetLabel() )
    {
        m_msg->SetLabel(newmsg);

        wxYieldIfNeeded() ;
    }

    if ( (m_elapsed || m_remaining || m_estimated) && (value != 0) )
    {
        unsigned long elapsed = wxGetCurrentTime() - m_timeStart;
        if (    m_last_timeupdate < elapsed
                || value == m_maximum
           )
        {
            m_last_timeupdate = elapsed;
            unsigned long estimated = m_break +
                                      (unsigned long)(( (double) (elapsed-m_break) * m_maximum ) / ((double)value)) ;
            if (    estimated > m_display_estimated
                    && m_ctdelay >= 0
               )
            {
                ++m_ctdelay;
            }
            else if (    estimated < m_display_estimated
                         && m_ctdelay <= 0
                    )
            {
                --m_ctdelay;
            }
            else
            {
                m_ctdelay = 0;
            }
            if (    m_ctdelay >= m_delay          // enough confirmations for a higher value
                    || m_ctdelay <= (m_delay*-1)     // enough confirmations for a lower value
                    || value == m_maximum            // to stay consistent
                    || elapsed > m_display_estimated // to stay consistent
                    || ( elapsed > 0 && elapsed < 4 ) // additional updates in the beginning
               )
            {
                m_display_estimated = estimated;
                m_ctdelay = 0;
            }
        }

        long display_remaining = m_display_estimated - elapsed;
        if ( display_remaining < 0 )
        {
            display_remaining = 0;
        }

        SetTimeLabel(elapsed, m_elapsed);
        SetTimeLabel(m_display_estimated, m_estimated);
        SetTimeLabel(display_remaining, m_remaining);
    }

    if ( value == m_maximum )
    {
        if ( m_state == Finished )
        {
            // ignore multiple calls to Update(m_maximum): it may sometimes be
            // troublesome to ensure that Update() is not called twice with the
            // same value (e.g. because of the rounding errors) and if we don't
            // return now we're going to generate asserts below
            return true;
        }

        // so that we return true below and that out [Cancel] handler knew what
        // to do
        m_state = Finished;
        if( !(GetWindowStyle() & wxPD_AUTO_HIDE) )
        {
            EnableClose();
            DisableSkip();
#if defined(__WXMSW__) && !defined(__WXUNIVERSAL__)
            EnableCloseButton();
#endif // __WXMSW__

            if ( newmsg.empty() )
            {
                // also provide the finishing message if the application didn't
                m_msg->SetLabel(_("Done."));
            }

            wxYieldIfNeeded() ;

            (void)ShowModal();
        }
        else // auto hide
        {
            // reenable other windows before hiding this one because otherwise
            // Windows wouldn't give the focus back to the window which had
            // been previously focused because it would still be disabled
            ReenableOtherWindows();

            Hide();
        }
    }
    else
    {
        // we have to yield because not only we want to update the display but
        // also to process the clicks on the cancel and skip buttons
        wxYieldIfNeeded() ;

        if ( (m_skip) && (skip != NULL) && (*skip == false) )
        {
            *skip = true;
            m_skip = false;
            EnableSkip();
        }
    }

    // update the display in case yielding above didn't do it
    Update();

    return m_state != Canceled;
}
Example #30
0
bool
wxGenericProgressDialog::Update(int value, const wxString& newmsg, bool *skip)
{
    if ( !DoBeforeUpdate(skip) )
        return false;

    wxCHECK_MSG( m_gauge, false, "dialog should be fully created" );

#ifdef __WXMSW__
    value /= m_factor;
#endif // __WXMSW__

    wxASSERT_MSG( value <= m_maximum, wxT("invalid progress value") );

    m_gauge->SetValue(value);

    UpdateMessage(newmsg);

    if ( (m_elapsed || m_remaining || m_estimated) && (value != 0) )
    {
        unsigned long elapsed;
        unsigned long display_remaining;

        UpdateTimeEstimates( value,
                             elapsed,
                             m_display_estimated,
                             display_remaining );

        SetTimeLabel(elapsed, m_elapsed);
        SetTimeLabel(m_display_estimated, m_estimated);
        SetTimeLabel(display_remaining, m_remaining);
    }

    if ( value == m_maximum )
    {
        if ( m_state == Finished )
        {
            // ignore multiple calls to Update(m_maximum): it may sometimes be
            // troublesome to ensure that Update() is not called twice with the
            // same value (e.g. because of the rounding errors) and if we don't
            // return now we're going to generate asserts below
            return true;
        }

        // so that we return true below and that out [Cancel] handler knew what
        // to do
        m_state = Finished;
        if( !HasPDFlag(wxPD_AUTO_HIDE) )
        {
            EnableClose();
            DisableSkip();
#if defined(__WXMSW__) && !defined(__WXUNIVERSAL__)
            EnableCloseButton();
#endif // __WXMSW__

            if ( newmsg.empty() )
            {
                // also provide the finishing message if the application didn't
                m_msg->SetLabel(_("Done."));
            }

            // allow the window to repaint:
            // NOTE: since we yield only for UI events with this call, there
            //       should be no side-effects
            wxEventLoopBase::GetActive()->YieldFor(wxEVT_CATEGORY_UI);

            // NOTE: this call results in a new event loop being created
            //       and to a call to ProcessPendingEvents() (which may generate
            //       unwanted re-entrancies).
            (void)ShowModal();
        }
        else // auto hide
        {
            // reenable other windows before hiding this one because otherwise
            // Windows wouldn't give the focus back to the window which had
            // been previously focused because it would still be disabled
            ReenableOtherWindows();

            Hide();
        }
    }
    else // not at maximum yet
    {
        DoAfterUpdate();
    }

    // update the display in case yielding above didn't do it
    Update();

    return m_state != Canceled;
}