void MainWindow::dropEvent(QDropEvent *e)
{
	if(ignore_drops_)
		return;

	QImage newimg;
	QString newpath = "";

	e->acceptProposedAction();

	if(e->mimeData()->hasImage()) {
		newimg = qvariant_cast<QImage>(e->mimeData()->imageData());
	}
	else if(e->mimeData()->hasUrls()) {
		newpath = e->mimeData()->urls().front().path();
		newimg.load(newpath);
	}

	if(newimg.isNull()) {
		return;
	}

	img_original_ = newimg.convertToFormat(QImage::Format_ARGB32);

	// Refresh UI
	if(newpath.isEmpty() != true) {
		img_path_ = newpath;
		update_window_title(img_path_);
	}
	else {
		update_window_title("");
	}

	refresh_previews();
}
Exemple #2
0
void
ui_signal_save_as (GtkMenuItem * item, gpointer data)
{
  GtkWidget *dialog;
  GtkWidget *window = GET_OBJECT("window");
  dialog = gtk_file_chooser_dialog_new (_("Save"),
                                        GTK_WINDOW(window),
                                        GTK_FILE_CHOOSER_ACTION_SAVE,
                                        GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
                                        GTK_STOCK_SAVE, GTK_RESPONSE_ACCEPT,
                                        NULL);
  /* Set filters */
  gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (dialog), filter_sgf);
  gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (dialog), filter_lg_sgf);

  if (gtk_dialog_run (GTK_DIALOG (dialog)) == GTK_RESPONSE_ACCEPT)
    {
      g_free (game_file);
      game_file = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (dialog));
      game_format = dialog_selected_format (dialog);
      gtk_file_chooser_set_do_overwrite_confirmation (GTK_FILE_CHOOSER (dialog), TRUE);
      if (game_format != HEX_AUTO)
        hex_save_sgf (game, game_format, game_file);
      update_window_title();
    }
  gtk_widget_destroy (dialog);
}
extern void handle_login_success(const char *username)
{
    /*connect the "Add Contact" button to its handler*/
    enable_add_contact_button();
    
    /*set the username that user logged in with*/
    set_username(username);

    /*initialize the users directory*/
    if(init_user_directory() != 0 )
    {
    	//TODO don't change the GUI to logged in if this step doesn't work...
    }

    /*update window title*/
    update_window_title();

	/*load and show contacts TODO free model? or unref it?*/
	GtkListStore *model = create_contact_list_model();
	if(model)
	{
		toggle_list_view(TRUE, model);
	}
	else
	{
		edit_label("You don't have any contacts yet.");
		toggle_list_view(FALSE, NULL);
	}

    return;
}
Exemple #4
0
static void
keypress(Display *dpy, Window win, char key)
{
   switch (key) {
   case 27:
      /* escape */
      exit(0);
      break;
   case 's':
      Buffer = STENCIL_BUFFER;
      break;
   case 'z':
      Buffer = Z_BUFFER;
      break;
   case 'f':
      Buffer = FRONT_BUFFER;
      break;
   case 'b':
      Buffer = BACK_BUFFER;
      break;
   default:
      return;
   }

   update_window_title(dpy, win);
   redraw(dpy, WindowID, win);
}
Exemple #5
0
int
main( int argc, char *argv[] )
{
   Display *dpy;
   VisualID vid;
   XVisualInfo *visinfo;
   Window win;

   parse_opts(argc, argv);

   key_usage();

   dpy = XOpenDisplay(DisplayName);

   /* find the VisualID for the named window */
   vid = get_window_visualid(dpy, WindowID);
   get_window_size(dpy, WindowID, &Width, &Height);

   visinfo = visualid_to_visualinfo(dpy, vid);

   Context = glXCreateContext( dpy, visinfo, NULL, True );
   if (!Context) {
      printf("Error: glXCreateContext failed\n");
      exit(1);
   }

   win = make_gl_window(dpy, visinfo, Width, Height);
   XMapWindow(dpy, win);
   update_window_title(dpy, win);

   event_loop( dpy, win );

   return 0;
}
Exemple #6
0
void check_and_update_window_title(struct Window *win_data, gboolean custom_window_title, gint page_no,
				   gchar *custom_page_name, gchar *page_name)
{
#ifdef DETAIL
	g_debug("! Launch check_and_update_window_title with win_data = %p, custom_window_title = %d, "
		"page_no = %d, custom_page_name = %s, page_name = %s",
		win_data, custom_window_title, page_no, custom_page_name, page_name);
#endif
#ifdef DEFENSIVE
	if ((win_data==NULL) || (win_data->notebook==NULL)) return;
#endif
	if ((win_data->window_title_shows_current_page == FALSE) || (custom_window_title == TRUE)) return;

	gint current_page_no = gtk_notebook_get_current_page(GTK_NOTEBOOK(win_data->notebook));

	// we only update the window title for current page
	// g_debug("current_page_no = %d, page_no = %d", current_page_no, page_no);

	// FIXME: A dirty hack... current_page_no=-1 when creating a 2rd new window.
	// if (win_data->adding_page && (current_page_no<0)) current_page_no = 0;

	if ((current_page_no == (page_no-1)) || ((current_page_no==-1) && (page_no==1)))
	{
		gchar *window_title = NULL;
		if (custom_page_name)
			window_title = custom_page_name;
		else
			window_title = page_name;

		if (window_title)
			// g_debug("page_name = %s before calling update_window_title()", page_name);
			update_window_title(win_data->window, window_title,
					    win_data->window_title_append_package_name);
	}
}
Exemple #7
0
int main(void)
{
    float position;
    unsigned long frame_count = 0;
    double last_time, current_time;
    GLFWwindow* window;

    glfwSetErrorCallback(error_callback);

    if (!glfwInit())
        exit(EXIT_FAILURE);

    window = glfwCreateWindow(640, 480, "", NULL, NULL);
    if (!window)
    {
        glfwTerminate();
        exit(EXIT_FAILURE);
    }

    glfwMakeContextCurrent(window);
    set_swap_interval(window, 0);

    last_time = glfwGetTime();
    frame_rate = 0.0;

    glfwSetWindowSizeCallback(window, window_size_callback);
    glfwSetKeyCallback(window, key_callback);

    glMatrixMode(GL_PROJECTION);
    glOrtho(-1.f, 1.f, -1.f, 1.f, 1.f, -1.f);
    glMatrixMode(GL_MODELVIEW);

    while (!glfwWindowShouldClose(window))
    {
        glClear(GL_COLOR_BUFFER_BIT);

        position = cosf((float) glfwGetTime() * 4.f) * 0.75f;
        glRectf(position - 0.25f, -1.f, position + 0.25f, 1.f);

        glfwSwapBuffers(window);
        glfwPollEvents();

        frame_count++;

        current_time = glfwGetTime();
        if (current_time - last_time > 1.0)
        {
            frame_rate = frame_count / (current_time - last_time);
            frame_count = 0;
            last_time = current_time;
            update_window_title(window);
        }
    }

    glfwTerminate();
    exit(EXIT_SUCCESS);
}
Exemple #8
0
/** \brief Add a new module to mod-mgr.
 *  \param module The GtkSatModule widget to add
 *  \param dock Flag indicating whether module should be docked or not.
 *
 * This function registers a new module in the mod-mgr. If the dock flag is true
 * the module is added to the mod-mgr notebook, otherwise it will be up to the
 * caller to create a proper container.
 *
 */
gint
mod_mgr_add_module     (GtkWidget *module, gboolean dock)
{
    gint       retcode = 0;
    gint       page;


    if (module) {

        /* add module to internal list */
        modules = g_slist_append (modules, module);

        if (dock) {
            /* add module to notebook if state = DOCKED */
            page = gtk_notebook_append_page (GTK_NOTEBOOK (nbook),
                                             module,
                                             gtk_label_new (GTK_SAT_MODULE (module)->name));

            /* allow nmodule to be dragged to different position */
            gtk_notebook_set_tab_reorderable (GTK_NOTEBOOK(nbook), module, TRUE);

            gtk_notebook_set_current_page (GTK_NOTEBOOK (nbook), page);

            /* send message to logger */
            sat_log_log (SAT_LOG_LEVEL_MSG,
                         _("%s: Added %s to module manger (page %d)."),
                         __FUNCTION__, GTK_SAT_MODULE (module)->name, page);
        }
        else {
            /* send message to logger */
            sat_log_log (SAT_LOG_LEVEL_MSG,
                         _("%s: Added %s to module manger (NOT DOCKED)."),
                         __FUNCTION__, GTK_SAT_MODULE (module)->name);
        }
        retcode = 0;
    }
    else {
        sat_log_log (SAT_LOG_LEVEL_ERROR,
                     _("%s: Module %s seems to be NULL"),
                     __FUNCTION__, GTK_SAT_MODULE (module)->name);
        retcode = 1;
    }

    /* disable tabs if only one page in notebook */
    if ((gtk_notebook_get_n_pages (GTK_NOTEBOOK(nbook))) == 1) {
        gtk_notebook_set_show_tabs (GTK_NOTEBOOK (nbook), FALSE);
    }
    else {
        gtk_notebook_set_show_tabs (GTK_NOTEBOOK (nbook), TRUE);
    }

    update_window_title    ();

    return retcode;

}
Exemple #9
0
void mainwnd::new_file()
{
    m_mainperf->clear_all();

    m_main_wid->reset();
    m_entry_notes->set_text( * m_mainperf->get_screen_set_notepad(
                m_mainperf->get_screenset() ));

    global_filename = "";
    update_window_title();
    m_modified = false;
}
Exemple #10
0
/** \brief Remove a module from the notebook.
 *  \param module The module that should be removed.
 *  \return 0 if the module has been removed or 1 if the requested module
 *          could not be found in the notebook.
 */
gint
mod_mgr_remove_module (GtkWidget *module)
{
    gint page;
    gint retcode = 0;


    /* remove from notebook */
    if (GTK_SAT_MODULE (module)->state == GTK_SAT_MOD_STATE_DOCKED) {
        /* get page number for this module */
        page = gtk_notebook_page_num (GTK_NOTEBOOK (nbook), module);

        if (page == -1) {
            /* this is some kind of bug (inconsistency between internal states) */
            sat_log_log (SAT_LOG_LEVEL_BUG,
                         _("%s: Could not find child in notebook. This may hurt..."),
                         __FUNCTION__);

            retcode = 1;
        }
        else {
            gtk_notebook_remove_page (GTK_NOTEBOOK (nbook), page);

            sat_log_log (SAT_LOG_LEVEL_MSG,
                         _("%s: Removed child from notebook page %d."),
                         __FUNCTION__, page);

            retcode = 0;
        }
    }

    /* remove from list */
    modules = g_slist_remove (modules, module);

    /* undocked modules will have to destroy themselves
       because of their parent window
    */


    /* disable tabs if only one page in notebook */
    if ((gtk_notebook_get_n_pages (GTK_NOTEBOOK(nbook))) == 1) {
        gtk_notebook_set_show_tabs (GTK_NOTEBOOK (nbook), FALSE);
    }
    else {
        gtk_notebook_set_show_tabs (GTK_NOTEBOOK (nbook), TRUE);
    }

    /* update window title */
    update_window_title ();

    return retcode;
}
Exemple #11
0
void mainwnd::choose_file(const bool setlist_mode)
{
    Gtk::FileChooserDialog dialog("Open MIDI file",
                      Gtk::FILE_CHOOSER_ACTION_OPEN);
    dialog.set_transient_for(*this);

    if(setlist_mode)
    	dialog.set_title("Open Playlist file");

    dialog.add_button(Gtk::Stock::CANCEL, Gtk::RESPONSE_CANCEL);
    dialog.add_button(Gtk::Stock::OPEN, Gtk::RESPONSE_OK);

    if(!setlist_mode){
		Gtk::FileFilter filter_midi;
		filter_midi.set_name("MIDI files");
		filter_midi.add_pattern("*.midi");
		filter_midi.add_pattern("*.mid");
		dialog.add_filter(filter_midi);
    }

    Gtk::FileFilter filter_any;
    filter_any.set_name("Any files");
    filter_any.add_pattern("*");
    dialog.add_filter(filter_any);

    dialog.set_current_folder(last_used_dir);

    int result = dialog.run();

    switch(result) {
        case(Gtk::RESPONSE_OK):
        	if(setlist_mode){

        		char fn[250];

        		strcpy(fn,dialog.get_filename().c_str());

        		printf("Opening setlist %s\n",fn);

            	m_mainperf->set_setlist_mode(true);
            	m_mainperf->set_setlist_file(fn);
                update_window_title();
        	}
        	else{
        		open_file(dialog.get_filename(), false);
        	}
        	break;
        default:
            break;
    }
}
Exemple #12
0
void
ui_run (void)
{
  GtkWidget * box;
  GtkWidget * about;
  GtkWidget * window;
  int success;

  builder = gtk_builder_new();
  success = gtk_builder_add_from_file (builder, UI_BUILDER_FILENAME, NULL);
  if (!success)
    success = gtk_builder_add_from_file (builder, UI_BUILDER_FILE, NULL);
  if (!success)
    g_error (_("User interface definition file '%s' was not found.\n"));

  gtk_builder_connect_signals (builder, NULL);
  window = GET_OBJECT("window");
  box = GET_OBJECT("box");
  about = GET_OBJECT ("window-about");

  g_log_set_handler (G_LOG_DOMAIN, G_LOG_LEVEL_MESSAGE, ui_log_level_message, NULL);
  g_log_set_handler (G_LOG_DOMAIN, G_LOG_LEVEL_INFO, ui_log_level_info, NULL);

  game = hex_new (DEFAULT_BOARD_SIZE);
  gtk_about_dialog_set_version (GTK_ABOUT_DIALOG (about), PACKAGE_VERSION);
  hexboard = hexboard_new(DEFAULT_BOARD_SIZE);

  filter_auto = gtk_file_filter_new ();
  filter_sgf = gtk_file_filter_new ();
  filter_lg_sgf = gtk_file_filter_new ();
  gtk_file_filter_set_name (filter_auto, "Select Automatically");
  gtk_file_filter_set_name (filter_sgf, "Smart Game Format (SGF)");
  gtk_file_filter_set_name (filter_lg_sgf, "LittleGolem's Smart Game Format (SGF)");
  gtk_file_filter_add_pattern (filter_auto, "*");
  gtk_file_filter_add_pattern (filter_sgf, "*.sgf");
  gtk_file_filter_add_pattern (filter_lg_sgf, "*.hsgf");
  gtk_file_filter_add_pattern (filter_lg_sgf, "*.sgf");
  g_object_ref_sink (filter_auto);
  g_object_ref_sink (filter_sgf);
  g_object_ref_sink (filter_lg_sgf);

  g_signal_connect (GTK_WIDGET(hexboard), "cell_clicked", G_CALLBACK(ui_signal_cell_clicked), game);
  gtk_container_add (GTK_CONTAINER(box), hexboard);
  gtk_widget_show_all (window);
  update_history_buttons();
  update_window_title();
  gtk_main();
  hex_free (game);
}
Exemple #13
0
/** \brief Dock a module into the notebook.
 *  \param module The module to insert into the notebook.
 *  \return 0 if the operation was successful, 1 otherwise.
 *
 * This function inserts the module into the notebook but does not add it
 * to the list of modules, since it should already be there.
 *
 * The function does some sanity checks to ensure the the module actually
 * is in the internal list of modules and also that the module is not
 * already present in the notebook. If any of these checks fail, the function
 * will send an error message and try to recover.
 *
 * The function does not modify the internal state of the module, module->state,
 * that is up to the module itself.
 */
gint
mod_mgr_dock_module    (GtkWidget *module)
{
    gint retcode = 0;
    gint page;

    
    if (!g_slist_find (modules, module)) {
        sat_log_log (SAT_LOG_LEVEL_BUG,
                     _("%s: Module %s not found in list. Trying to recover."),
                     __FUNCTION__, GTK_SAT_MODULE (module)->name);
        modules = g_slist_append (modules, module);
    }

    page = gtk_notebook_page_num (GTK_NOTEBOOK (nbook), module);
    if (page != -1) {
        sat_log_log (SAT_LOG_LEVEL_BUG,
                     _("%s: Module %s already in notebook!"),
                     __FUNCTION__, GTK_SAT_MODULE (module)->name);
        retcode = 1;
    }
    else {
        /* add module to notebook */
        page = gtk_notebook_append_page (GTK_NOTEBOOK (nbook),
                                         module,
                                         gtk_label_new (GTK_SAT_MODULE (module)->name));

        sat_log_log (SAT_LOG_LEVEL_MSG,
                     _("%s: Docked %s into notebook (page %d)"),
                     __FUNCTION__, GTK_SAT_MODULE (module)->name, page);
        
        retcode = 0;
    }

    /* disable tabs if only one page in notebook */
    if ((gtk_notebook_get_n_pages (GTK_NOTEBOOK(nbook))) == 1) {
        gtk_notebook_set_show_tabs (GTK_NOTEBOOK (nbook), FALSE);
    }
    else {
        gtk_notebook_set_show_tabs (GTK_NOTEBOOK (nbook), TRUE);
    }

    /* update window title */
    update_window_title ();

    return retcode;
}
Exemple #14
0
void
ui_signal_open (GtkMenuItem * item, gpointer data)
{
  GtkWidget *dialog;
  GtkWidget *window = GET_OBJECT("window");
  char * filename;
  Hexboard * board;

  dialog = gtk_file_chooser_dialog_new (_("Open"),
                                        GTK_WINDOW(window),
                                        GTK_FILE_CHOOSER_ACTION_OPEN,
                                        GTK_STOCK_CANCEL, GTK_RESPONSE_CANCEL,
                                        GTK_STOCK_OPEN, GTK_RESPONSE_ACCEPT,
                                        NULL);

  gtk_widget_set_size_request(GTK_WIDGET(dialog), 800, 600);

  /* Configure the previewer widget */
  board = HEXBOARD (hexboard_new (10));
  gtk_widget_set_size_request(GTK_WIDGET(board), 340, 240);
  gtk_file_chooser_set_preview_widget (GTK_FILE_CHOOSER(dialog), GTK_WIDGET(board));
  g_signal_connect (dialog, "update-preview", G_CALLBACK (ui_signal_open_update_preview), board);

  /* Set filters */
  gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (dialog), filter_auto);
  gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (dialog), filter_sgf);
  gtk_file_chooser_add_filter (GTK_FILE_CHOOSER (dialog), filter_lg_sgf);

  if (gtk_dialog_run (GTK_DIALOG (dialog)) == GTK_RESPONSE_ACCEPT)
    {
      Hexboard * board = HEXBOARD (hexboard);
      filename = gtk_file_chooser_get_filename (GTK_FILE_CHOOSER (dialog));
      game_file = filename;
      update_window_title();
      hex_free (game);
      game_format = dialog_selected_format (dialog);
      game = hex_load_sgf (game_format, filename);
      hexboard_set_size (board, hex_size (game));
      g_free (filename);
      history_marker = undo_history_marker = hex_history_current (game);
      update_hexboard_colors ();
      update_hexboard_sensitive();
      update_history_buttons();
      check_end_of_game();
    }
  gtk_widget_destroy (dialog);
}
MainWindow::MainWindow(const QString &defaultDisplay, QSplashScreen *splash, QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),
    _qpd(NULL), _kcpos(0), _defaultDisplay(defaultDisplay),
    _silent(false), _allowSilent(false), _splash(splash), _settings(NULL),
    _activatedEth(false), _numInstalledOS(0), _netaccess(NULL), _displayModeBox(NULL)
{
    ui->setupUi(this);
    setWindowFlags(Qt::Window | Qt::CustomizeWindowHint | Qt::WindowTitleHint);
    setContextMenuPolicy(Qt::NoContextMenu);
    update_window_title();
    _kc << 0x01000013 << 0x01000013 << 0x01000015 << 0x01000015 << 0x01000012
        << 0x01000014 << 0x01000012 << 0x01000014 << 0x42 << 0x41;
    ui->list->setItemDelegate(new TwoIconsDelegate(this));
    ui->list->installEventFilter(this);
    ui->advToolBar->setVisible(false);

    QRect s = QApplication::desktop()->screenGeometry();
    if (s.height() < 500)
        resize(s.width()-10, s.height()-100);

    if (qApp->arguments().contains("-runinstaller") && !_partInited)
    {
        QMessageBox::warning(this,
                                        tr("Confirm"),
                                        tr("Warning: setting up SD card."),
                                        QMessageBox::Yes, QMessageBox::No);

        /* Repartition SD card first */
        _partInited = true;
        setEnabled(false);
        _qpd = new QProgressDialog( tr("Setting up SD card"), QString(), 0, 0, this);
        _qpd->setWindowModality(Qt::WindowModal);
        _qpd->setWindowFlags(Qt::Window | Qt::CustomizeWindowHint | Qt::WindowTitleHint);

        InitDriveThread *idt = new InitDriveThread(this);
        connect(idt, SIGNAL(statusUpdate(QString)), _qpd, SLOT(setLabelText(QString)));
        connect(idt, SIGNAL(completed()), _qpd, SLOT(deleteLater()));
        connect(idt, SIGNAL(error(QString)), this, SLOT(onError(QString)));
        connect(idt, SIGNAL(query(QString, QString, QMessageBox::StandardButton*)),
                this, SLOT(onQuery(QString, QString, QMessageBox::StandardButton*)),
                Qt::BlockingQueuedConnection);

        idt->start();
        _qpd->exec();
        setEnabled(true);
    }
Exemple #16
0
/** \brief Undock module from notebook
 *  \param module The module that should be undocked.
 *
 * This function removes module from the notebook without removing it from
 * the internal list of modules.
 *
 * The function does some sanity checks to ensure that the module actually
 * exists in the mod-mgr, if not it will add module to the internal list
 * and raise a warning.
 *
 * The function does not modify the internal state of the module, module->state,
 * that is up to the module itself.
 *
 * \note The module itself is responsible for temporarily incrementing the
 *       reference count of the widget in order to avoid destruction when
 *       removing from the notebook.
 */
gint
mod_mgr_undock_module  (GtkWidget *module)
{
    gint retcode = 0;
    gint page;


    if (!g_slist_find (modules, module)) {
        sat_log_log (SAT_LOG_LEVEL_BUG,
                     _("%s: Module %s not found in list. Trying to recover."),
                     __FUNCTION__, GTK_SAT_MODULE (module)->name);
        modules = g_slist_append (modules, module);
    }

    page = gtk_notebook_page_num (GTK_NOTEBOOK (nbook), module);
    if (page == -1) {
        sat_log_log (SAT_LOG_LEVEL_BUG,
                     _("%s: Module %s does not seem to be docked!"),
                     __FUNCTION__, GTK_SAT_MODULE (module)->name);
        retcode = 1;
    }
    else {

        gtk_notebook_remove_page (GTK_NOTEBOOK (nbook), page);

        sat_log_log (SAT_LOG_LEVEL_MSG,
                     _("%s: Removed %s from notebook page %d."),
                     __FUNCTION__, GTK_SAT_MODULE (module)->name, page);

        retcode = 0;
    }

    /* disable tabs if only one page in notebook */
    if ((gtk_notebook_get_n_pages (GTK_NOTEBOOK(nbook))) == 1) {
        gtk_notebook_set_show_tabs (GTK_NOTEBOOK (nbook), FALSE);
    }
    else {
        gtk_notebook_set_show_tabs (GTK_NOTEBOOK (nbook), TRUE);
    }

    /* update window title */
    update_window_title ();

    return retcode;
}
Exemple #17
0
void
ui_signal_new (GtkMenuItem * item, gpointer data)
{
  Hexboard * board = HEXBOARD (hexboard);
  GtkWidget * dialog = GET_OBJECT ("window-new");
  GtkSpinButton * sizespin = GTK_SPIN_BUTTON (GET_OBJECT ("window-new-size"));
  GtkColorButton * color1 = GTK_COLOR_BUTTON (GET_OBJECT ("window-new-color1"));
  GtkColorButton * color2 = GTK_COLOR_BUTTON (GET_OBJECT ("window-new-color2"));
  gint ok;
  ok = gtk_dialog_run (GTK_DIALOG (dialog));
  if (ok)
    {
      gint size = gtk_spin_button_get_value_as_int(GTK_SPIN_BUTTON (sizespin));
      GdkColor color;
      double r,g,b;
      hex_free (game);
      game = hex_new (size);
      hexboard_set_size (board, size);
      history_marker = undo_history_marker = 0;

      /* Colors */
      hexboard_color[0][0] = hexboard_color[0][1] = hexboard_color[0][2] = 1;

      gtk_color_button_get_color (color1, &color);
      r = hexboard_color[1][0] = color.red / 65535.0;;
      g = hexboard_color[1][1] = color.green / 65535.0;;
      b = hexboard_color[1][2] = color.blue / 65535.0;;
      hexboard_border_set_color (board, HEXBOARD_BORDER_SE, r,g,b);
      hexboard_border_set_color (board, HEXBOARD_BORDER_NW, r,g,b);

      gtk_color_button_get_color (color2, &color);
      r = hexboard_color[2][0] = color.red / 65535.0;;
      g = hexboard_color[2][1] = color.green / 65535.0;;
      b = hexboard_color[2][2] = color.blue / 65535.0;;
      hexboard_border_set_color (board, HEXBOARD_BORDER_NE, r,g,b);
      hexboard_border_set_color (board, HEXBOARD_BORDER_SW, r,g,b);

      game_file = NULL;
      update_window_title();
      update_hexboard_colors();
      update_hexboard_sensitive();
      update_history_buttons();
    }
  gtk_widget_hide (dialog);
}
void STMainWindow::slot_new_sequence() {
	STSequenceView *SV=new STSequenceView;
	connect_sequence_view(SV);
	STMetaSequence *Seq=new STMetaSequence;
	STMetaClass *root_class=new STMetaClass;
	root_class->setClassName("STRoot");
	root_class->setCode(read_text_file(ST_TEMPLATES_DIR+"/stroot.h"),read_text_file(ST_TEMPLATES_DIR+"/stroot.cpp"));
	Seq->addMetaClass(root_class);
	Seq->loadFoundationClasses(ST_FOUNDATION_DIR,false);
	Seq->loadFoundationClasses(ST_USER_DIR,true);
	SV->setSequence(Seq);
	ui.tabWidget->addTab(SV,"[untitled]");
	ui.tabWidget->setCurrentWidget(SV);
	update_window_title();
	qApp->processEvents();
	SV->setPreferredSizes();
	update_actions();
}
Exemple #19
0
void
newDocCB( Widget w, XtPointer client_data, 
 		XtPointer call_data)
{
	Widget widget;
	
	widget = get_document_text(w, "newDocCB");
	XmTextSetString(widget, "");
	
	widget = get_widget_by_name(w, "newDocCB", "lineTextField");
	XmTextFieldSetString(widget, "");
	
	update_message(w, "newDocCB", "Created new empty file.");
	set_save_path(NULL);
	set_been_saved(False);
	
	update_document_linecount(w, "newDocCB");
	update_window_title(w, "newDocCB");
}
Exemple #20
0
bool mainwnd::open_file(const Glib::ustring& fn, bool setlist_mode)
{
    bool result;

    stop_playing();

    /*We aren't using a playlist if we've opened a file*/
    set_wsetlist_mode(setlist_mode);

    m_mainperf->clear_all();

    midifile f(fn);
    result = f.parse(m_mainperf, 0);
    m_modified = !result;

    if (!result) {
    	if(setlist_mode){
    		//We don't want dialog boxes in setlist mode!
    		printf("Error reading file: %s\n",fn.data());
    	}
    	else{
		    Gtk::MessageDialog errdialog(*this,
		            "Error reading file: " + fn, false,
		            Gtk::MESSAGE_ERROR, Gtk::BUTTONS_OK, true);
		    errdialog.run();
        }
        return false;
    }

    last_used_dir = fn.substr(0, fn.rfind("/") + 1);
    global_filename = fn;
    update_window_title();

    m_main_wid->reset();
    m_entry_notes->set_text(*m_mainperf->get_screen_set_notepad(
                m_mainperf->get_screenset()));
    m_adjust_bpm->set_value( m_mainperf->get_bpm());

    //Check what the max tick is
    m_mainperf->update_max_tick();

    return true;
}
Exemple #21
0
int main(int argc, char *argv[])
{
    initialize();

    // Handle a map file passed as argument
    if (argc == 2 && exists(argv[1]))
    {
        PACKFILE *file = pack_fopen(argv[1], F_READ_PACKED);
        if (file) {
            currentMap->loadFrom(file, tileRepository);
            pack_fclose(file);
            ustrcpy(map_filename, argv[1]);
            update_window_title();
        } else {
            alert("Invalid map file:", argv[1], NULL, "OK", NULL, 13, 0);
        }
    }

    do_dialog(main_dlg, -1);
    clean_up();
    return 0;
}
void STMainWindow::openSequence(QString sequence_fname) {
	if (sequenceView(sequence_fname)) {
		ui.tabWidget->setCurrentWidget(sequenceView(sequence_fname));
	}
	else {
		STSequenceView *SV=new STSequenceView;
		connect_sequence_view(SV);
		STMetaSequence *Seq=new STMetaSequence;
		Seq->read(sequence_fname);
		SV->setSequence(Seq);
		SV->setFileName(sequence_fname);
		Seq->setFileName(sequence_fname);	
		ui.tabWidget->addTab(SV,"");
		ui.tabWidget->setCurrentWidget(SV);
		update_tab_labels();
		update_window_title();
		add_to_recent_files(sequence_fname);
		qApp->processEvents();
		SV->setPreferredSizes();
	}
	update_actions();
}
bool STMainWindow::slot_close_sequence() {
	if (!currentSequenceView()) return false;
	QString fname=QFileInfo(currentSequenceView()->fileName()).fileName();
	if (currentSequenceView()->isModified()) {
		if (fname.isEmpty()) fname="[untitled]";
		QMessageBox::StandardButton ret=QMessageBox::question(this,"Save changes?",tr("Save changes to %1?").arg(fname),
				QMessageBox::Save|QMessageBox::Discard|QMessageBox::Cancel);
		if (ret==QMessageBox::Save) {
			slot_save_sequence();
			if (!currentSequenceView()->isModified()) {
				return slot_close_sequence();
			}
		}
		else if (ret==QMessageBox::Cancel) {
			return false;
		}
	}
	statusBar()->showMessage(tr("Closing sequence: %1").arg(fname),MSG_DELAY);
	delete currentSequenceView();
	statusBar()->showMessage(tr("Sequence closed: %1").arg(fname),MSG_DELAY);
	update_window_title();
	update_actions();
	return true;
}
void STMainWindow::openSequenceFromText(const QString fname, const QString &txt) {
	if (sequenceView(fname)) {
		ui.tabWidget->setCurrentWidget(sequenceView(fname));
	}
	else {
		STSequenceView *SV=new STSequenceView;
		connect_sequence_view(SV);
		STMetaSequence *Seq=new STMetaSequence;
		QStringList text_lines=txt.split('\n');
		long index=0;
		Seq->loadFromText(text_lines,index);
		SV->setSequence(Seq);
		SV->setFileName(fname);
		Seq->setFileName(fname);	
		ui.tabWidget->addTab(SV,"");
		ui.tabWidget->setCurrentWidget(SV);
		update_tab_labels();
		update_window_title();
		//add_to_recent_files(sequence_fname);
		qApp->processEvents();
		SV->setPreferredSizes();
	}
	update_actions();
}
Exemple #25
0
int reinit_video_chain(struct MPContext *mpctx)
{
    struct MPOpts *opts = mpctx->opts;
    assert(!mpctx->d_video);
    struct track *track = mpctx->current_track[0][STREAM_VIDEO];
    struct sh_stream *sh = track ? track->stream : NULL;
    if (!sh)
        goto no_video;

    if (!mpctx->video_out) {
        struct vo_extra ex = {
            .input_ctx = mpctx->input,
            .osd = mpctx->osd,
            .encode_lavc_ctx = mpctx->encode_lavc_ctx,
            .opengl_cb_context = mpctx->gl_cb_ctx,
        };
        mpctx->video_out = init_best_video_out(mpctx->global, &ex);
        if (!mpctx->video_out) {
            MP_FATAL(mpctx, "Error opening/initializing "
                    "the selected video_out (-vo) device.\n");
            mpctx->error_playing = MPV_ERROR_VO_INIT_FAILED;
            goto err_out;
        }
        mpctx->mouse_cursor_visible = true;
    }

    update_window_title(mpctx, true);

    struct dec_video *d_video = talloc_zero(NULL, struct dec_video);
    mpctx->d_video = d_video;
    d_video->global = mpctx->global;
    d_video->log = mp_log_new(d_video, mpctx->log, "!vd");
    d_video->opts = mpctx->opts;
    d_video->header = sh;
    d_video->fps = sh->video->fps;
    d_video->vo = mpctx->video_out;

    MP_VERBOSE(d_video, "Container reported FPS: %f\n", sh->video->fps);

    if (opts->force_fps) {
        d_video->fps = opts->force_fps;
        MP_INFO(mpctx, "FPS forced to %5.3f.\n", d_video->fps);
        MP_INFO(mpctx, "Use --no-correct-pts to force FPS based timing.\n");
    }

#if HAVE_ENCODING
    if (mpctx->encode_lavc_ctx && d_video)
        encode_lavc_set_video_fps(mpctx->encode_lavc_ctx, d_video->fps);
#endif

    vo_control(mpctx->video_out, VOCTRL_GET_HWDEC_INFO, &d_video->hwdec_info);

    recreate_video_filters(mpctx);

    if (!video_init_best_codec(d_video, opts->video_decoders))
        goto err_out;

    if (d_video->header->attached_picture && !decode_coverart(d_video))
        goto err_out;

    bool saver_state = opts->pause || !opts->stop_screensaver;
    vo_control(mpctx->video_out, saver_state ? VOCTRL_RESTORE_SCREENSAVER
                                             : VOCTRL_KILL_SCREENSAVER, NULL);

    vo_set_paused(mpctx->video_out, mpctx->paused);

    mpctx->sync_audio_to_video = !sh->attached_picture;
    mpctx->vo_pts_history_seek_ts++;

    // If we switch on video again, ensure audio position matches up.
    if (mpctx->d_audio)
        mpctx->audio_status = STATUS_SYNCING;

    reset_video_state(mpctx);
    reset_subtitle_state(mpctx);

    return 1;

err_out:
no_video:
    uninit_video_chain(mpctx);
    if (track)
        error_on_track(mpctx, track);
    handle_force_window(mpctx, true);
    return 0;
}

// Try to refresh the video by doing a precise seek to the currently displayed
// frame. This can go wrong in all sorts of ways, so use sparingly.
void mp_force_video_refresh(struct MPContext *mpctx)
{
    struct MPOpts *opts = mpctx->opts;
    struct dec_video *d_video = mpctx->d_video;

    if (!d_video || !d_video->decoder_output.imgfmt)
        return;

    // If not paused, the next frame should come soon enough.
    if (opts->pause && mpctx->video_status == STATUS_PLAYING &&
        mpctx->last_vo_pts != MP_NOPTS_VALUE)
    {
        queue_seek(mpctx, MPSEEK_ABSOLUTE, mpctx->last_vo_pts,
                   MPSEEK_VERY_EXACT, true);
    }
}

static int check_framedrop(struct MPContext *mpctx)
{
    struct MPOpts *opts = mpctx->opts;
    // check for frame-drop:
    if (mpctx->video_status == STATUS_PLAYING && !mpctx->paused &&
        mpctx->audio_status == STATUS_PLAYING && !ao_untimed(mpctx->ao))
    {
        float fps = mpctx->d_video->fps;
        double frame_time = fps > 0 ? 1.0 / fps : 0;
        // we should avoid dropping too many frames in sequence unless we
        // are too late. and we allow 100ms A-V delay here:
        if (mpctx->last_av_difference - 0.100 > mpctx->dropped_frames * frame_time)
            return !!(opts->frame_dropping & 2);
    }
    return 0;
}

static bool decode_coverart(struct dec_video *d_video)
{
    d_video->cover_art_mpi =
        video_decode(d_video, d_video->header->attached_picture, 0);
    // Might need flush.
    if (!d_video->cover_art_mpi)
        d_video->cover_art_mpi = video_decode(d_video, NULL, 0);

    return !!d_video->cover_art_mpi;
}
int main(int argc, char *argv[])
{
	if(!glfwInit()) {
		std::cerr << "Failed to init GLFW" << std::endl;
		return 1;
	}

	atexit(glfwTerminate);

	glfwSetErrorCallback(error_callback);

	glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 4);
	glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 1);
	glfwWindowHint(GLFW_OPENGL_FORWARD_COMPAT, GL_TRUE);
	glfwWindowHint(GLFW_OPENGL_PROFILE, GLFW_OPENGL_CORE_PROFILE);

	window = glfwCreateWindow(w, h, "Mandelbrot", NULL, NULL);
	if(!window) {
		std::cerr << "Failed to create window" << std::endl;
		return 1;
	}

	glfwSetKeyCallback(window, key_callback);
	glfwSetCursorPosCallback(window, cursor_callback);
	glfwSetMouseButtonCallback(window, mouse_button_callback);
	glfwSetScrollCallback(window, scroll_callback);
	glfwSetInputMode(window, GLFW_CURSOR_NORMAL, GLFW_STICKY_KEYS);

	glfwMakeContextCurrent(window);

	glewExperimental = GL_TRUE;
	glewInit();

	std::cout << "Renderer: " << glGetString(GL_RENDERER) << std::endl;
	std::cout << "OpenGL Version: " << glGetString(GL_VERSION) << std::endl;

	GLuint prog;
	compile_shader(prog);

	last_mtime = get_mtime("shader.glsl");

	float points[] = {
	   -1.0f,  1.0f,  0.0f,
	   -1.0f,  -1.0f,  0.0f,
	   1.0f,  -1.0f,  0.0f,

	   -1.0f,  1.0f,  0.0f,
	   1.0f,  -1.0f,  0.0f,
	   1.0f,  1.0f,  0.0f,
	};

	GLuint vbo = 0;
	glGenBuffers (1, &vbo);
	glBindBuffer (GL_ARRAY_BUFFER, vbo);
	glBufferData (GL_ARRAY_BUFFER, 2 * 9 * sizeof (float), points, GL_STATIC_DRAW);

	GLuint vao = 0;
	glGenVertexArrays (1, &vao);
	glBindVertexArray (vao);
	glEnableVertexAttribArray (0);
	glBindBuffer (GL_ARRAY_BUFFER, vbo);
	glVertexAttribPointer (0, 3, GL_FLOAT, GL_FALSE, 0, NULL);

	glUseProgram (prog);

	last_time = glfwGetTime();

	glBindVertexArray (vao);

	while(!glfwWindowShouldClose(window)) {
		time_t new_time = get_mtime("shader.glsl");
		if(new_time != last_mtime) {
			glDeleteProgram(prog);
			compile_shader(prog);
			glUseProgram(prog);
			last_mtime = new_time;

			std::cout << "Reloaded shader: " << last_mtime << std::endl;
		}

		glfwGetWindowSize(window, &w, &h);
		glUniform2d(glGetUniformLocation(prog, "screen_size"), (double)w, (double)h);
		glUniform1d(glGetUniformLocation(prog, "screen_ratio"), (double)w / (double)h);
		glUniform2d(glGetUniformLocation(prog, "center"), cx, cy);
		glUniform1d(glGetUniformLocation(prog, "zoom"), zoom);
		glUniform1i(glGetUniformLocation(prog, "itr"), itr);

		glClear (GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

		glDrawArrays (GL_TRIANGLES, 0, 6);

		glfwSwapBuffers(window);
		glfwPollEvents();

		ticks++;
		current_time = glfwGetTime();
		if(current_time - last_time > 1.0) {
			fps = ticks;
			update_window_title();
			last_time = glfwGetTime();
			ticks = 0;
		}
	}

	glfwDestroyWindow(window);
}
Exemple #27
0
static void set_swap_interval(GLFWwindow* window, int interval)
{
    swap_interval = interval;
    glfwSwapInterval(swap_interval);
    update_window_title(window);
}
Exemple #28
0
int main(int argc, char** argv)
{
    unsigned long frame_count = 0;
    double last_time, current_time;
    GLFWwindow* window;
    GLuint vertex_buffer, vertex_shader, fragment_shader, program;
    GLint mvp_location, vpos_location;

    glfwSetErrorCallback(error_callback);

    if (!glfwInit())
        exit(EXIT_FAILURE);

    glfwWindowHint(GLFW_CONTEXT_VERSION_MAJOR, 2);
    glfwWindowHint(GLFW_CONTEXT_VERSION_MINOR, 0);

    window = glfwCreateWindow(640, 480, "Tearing detector", NULL, NULL);
    if (!window)
    {
        glfwTerminate();
        exit(EXIT_FAILURE);
    }

    glfwMakeContextCurrent(window);
    gladLoadGL(glfwGetProcAddress);
    set_swap_interval(window, 0);

    last_time = glfwGetTime();
    frame_rate = 0.0;
    swap_tear = (glfwExtensionSupported("WGL_EXT_swap_control_tear") ||
                 glfwExtensionSupported("GLX_EXT_swap_control_tear"));

    glfwSetKeyCallback(window, key_callback);

    glGenBuffers(1, &vertex_buffer);
    glBindBuffer(GL_ARRAY_BUFFER, vertex_buffer);
    glBufferData(GL_ARRAY_BUFFER, sizeof(vertices), vertices, GL_STATIC_DRAW);

    vertex_shader = glCreateShader(GL_VERTEX_SHADER);
    glShaderSource(vertex_shader, 1, &vertex_shader_text, NULL);
    glCompileShader(vertex_shader);

    fragment_shader = glCreateShader(GL_FRAGMENT_SHADER);
    glShaderSource(fragment_shader, 1, &fragment_shader_text, NULL);
    glCompileShader(fragment_shader);

    program = glCreateProgram();
    glAttachShader(program, vertex_shader);
    glAttachShader(program, fragment_shader);
    glLinkProgram(program);

    mvp_location = glGetUniformLocation(program, "MVP");
    vpos_location = glGetAttribLocation(program, "vPos");

    glEnableVertexAttribArray(vpos_location);
    glVertexAttribPointer(vpos_location, 2, GL_FLOAT, GL_FALSE,
                          sizeof(vertices[0]), (void*) 0);

    while (!glfwWindowShouldClose(window))
    {
        int width, height;
        mat4x4 m, p, mvp;
        float position = cosf((float) glfwGetTime() * 4.f) * 0.75f;

        glfwGetFramebufferSize(window, &width, &height);

        glViewport(0, 0, width, height);
        glClear(GL_COLOR_BUFFER_BIT);

        mat4x4_ortho(p, -1.f, 1.f, -1.f, 1.f, 0.f, 1.f);
        mat4x4_translate(m, position, 0.f, 0.f);
        mat4x4_mul(mvp, p, m);

        glUseProgram(program);
        glUniformMatrix4fv(mvp_location, 1, GL_FALSE, (const GLfloat*) mvp);
        glDrawArrays(GL_TRIANGLE_FAN, 0, 4);

        glfwSwapBuffers(window);
        glfwPollEvents();

        frame_count++;

        current_time = glfwGetTime();
        if (current_time - last_time > 1.0)
        {
            frame_rate = frame_count / (current_time - last_time);
            frame_count = 0;
            last_time = current_time;
            update_window_title(window);
        }
    }

    glfwTerminate();
    exit(EXIT_SUCCESS);
}
Exemple #29
0
static void print_status(struct MPContext *mpctx)
{
    struct MPOpts *opts = mpctx->opts;

    update_window_title(mpctx, false);
    update_vo_playback_state(mpctx);

    if (!opts->use_terminal)
        return;

    if (opts->quiet || !mpctx->playback_initialized || !mpctx->playing_msg_shown)
    {
        term_osd_set_status(mpctx, "");
        return;
    }

    if (opts->status_msg) {
        char *r = mp_property_expand_escaped_string(mpctx, opts->status_msg);
        term_osd_set_status(mpctx, r);
        talloc_free(r);
        return;
    }

    char *line = NULL;

    // Playback status
    if (is_busy(mpctx)) {
        saddf(&line, "(...) ");
    } else if (mpctx->paused_for_cache && !opts->pause) {
        saddf(&line, "(Buffering) ");
    } else if (mpctx->paused) {
        saddf(&line, "(Paused) ");
    }

    if (mpctx->d_audio)
        saddf(&line, "A");
    if (mpctx->d_video)
        saddf(&line, "V");
    saddf(&line, ": ");

    // Playback position
    sadd_hhmmssff_u(&line, get_playback_time(mpctx), mpctx->opts->osd_fractions);

    double len = get_time_length(mpctx);
    if (len >= 0) {
        saddf(&line, " / ");
        sadd_hhmmssff(&line, len, mpctx->opts->osd_fractions);
    }

    sadd_percentage(&line, get_percent_pos(mpctx));

    // other
    if (opts->playback_speed != 1)
        saddf(&line, " x%4.2f", opts->playback_speed);

    // A-V sync
    if (mpctx->d_audio && mpctx->d_video && mpctx->sync_audio_to_video) {
        saddf(&line, " A-V:%7.3f", mpctx->last_av_difference);
        if (fabs(mpctx->total_avsync_change) > 0.05)
            saddf(&line, " ct:%7.3f", mpctx->total_avsync_change);
    }

#if HAVE_ENCODING
    double position = get_current_pos_ratio(mpctx, true);
    char lavcbuf[80];
    if (encode_lavc_getstatus(mpctx->encode_lavc_ctx, lavcbuf, sizeof(lavcbuf),
            position) >= 0)
    {
        // encoding stats
        saddf(&line, " %s", lavcbuf);
    } else
#endif
    {
        // VO stats
        if (mpctx->d_video) {
            if (mpctx->display_sync_active) {
                saddf(&line, " DS: %d/%"PRId64, mpctx->mistimed_frames_total,
                      vo_get_delayed_count(mpctx->video_out));
            }
            int64_t c = vo_get_drop_count(mpctx->video_out);
            if (c > 0 || mpctx->dropped_frames_total > 0) {
                saddf(&line, " Dropped: %"PRId64, c);
                if (mpctx->dropped_frames_total)
                    saddf(&line, "/%d", mpctx->dropped_frames_total);
            }
        }
    }

    if (mpctx->demuxer) {
        int64_t fill = -1;
        demux_stream_control(mpctx->demuxer, STREAM_CTRL_GET_CACHE_FILL, &fill);
        if (fill >= 0) {
            saddf(&line, " Cache: ");

            struct demux_ctrl_reader_state s = {.ts_duration = -1};
            demux_control(mpctx->demuxer, DEMUXER_CTRL_GET_READER_STATE, &s);

            if (s.ts_duration < 0) {
                saddf(&line, "???");
            } else {
                saddf(&line, "%2ds", (int)s.ts_duration);
            }
            if (fill >= 1024 * 1024) {
                saddf(&line, "+%lldMB", (long long)(fill / 1024 / 1024));
            } else {
                saddf(&line, "+%lldKB", (long long)(fill / 1024));
            }
        }
    }
Exemple #30
0
int reinit_video_chain(struct MPContext *mpctx)
{
    struct MPOpts *opts = mpctx->opts;
    assert(!mpctx->d_video);
    struct track *track = mpctx->current_track[0][STREAM_VIDEO];
    struct sh_stream *sh = track ? track->stream : NULL;
    if (!sh)
        goto no_video;

    MP_VERBOSE(mpctx, "[V] fourcc:0x%X  size:%dx%d  fps:%5.3f\n",
               sh->format,
               sh->video->disp_w, sh->video->disp_h,
               sh->video->fps);

    //================== Init VIDEO (codec & libvo) ==========================
    if (!opts->fixed_vo || !mpctx->video_out) {
        struct vo_extra ex = {
            .input_ctx = mpctx->input,
            .osd = mpctx->osd,
            .encode_lavc_ctx = mpctx->encode_lavc_ctx,
            .opengl_cb_context = mpctx->gl_cb_ctx,
        };
        mpctx->video_out = init_best_video_out(mpctx->global, &ex);
        if (!mpctx->video_out) {
            MP_FATAL(mpctx, "Error opening/initializing "
                    "the selected video_out (-vo) device.\n");
            mpctx->error_playing = MPV_ERROR_VO_INIT_FAILED;
            goto err_out;
        }
        mpctx->mouse_cursor_visible = true;
    }

    update_window_title(mpctx, true);

    struct dec_video *d_video = talloc_zero(NULL, struct dec_video);
    mpctx->d_video = d_video;
    d_video->global = mpctx->global;
    d_video->log = mp_log_new(d_video, mpctx->log, "!vd");
    d_video->opts = mpctx->opts;
    d_video->header = sh;
    d_video->fps = sh->video->fps;
    d_video->vo = mpctx->video_out;

    if (opts->force_fps) {
        d_video->fps = opts->force_fps;
        MP_INFO(mpctx, "FPS forced to %5.3f.\n", d_video->fps);
        MP_INFO(mpctx, "Use --no-correct-pts to force FPS based timing.\n");
    }
    update_fps(mpctx);

    vo_control(mpctx->video_out, VOCTRL_GET_HWDEC_INFO, &d_video->hwdec_info);

    recreate_video_filters(mpctx);

    if (!video_init_best_codec(d_video, opts->video_decoders))
        goto err_out;

    bool saver_state = opts->pause || !opts->stop_screensaver;
    vo_control(mpctx->video_out, saver_state ? VOCTRL_RESTORE_SCREENSAVER
                                             : VOCTRL_KILL_SCREENSAVER, NULL);

    vo_set_paused(mpctx->video_out, mpctx->paused);

    mpctx->sync_audio_to_video = !sh->attached_picture;
    mpctx->vo_pts_history_seek_ts++;

    // If we switch on video again, ensure audio position matches up.
    if (mpctx->d_audio)
        mpctx->audio_status = STATUS_SYNCING;

    reset_video_state(mpctx);
    reset_subtitle_state(mpctx);

    return 1;

err_out:
no_video:
    uninit_video_chain(mpctx);
    if (track)
        error_on_track(mpctx, track);
    handle_force_window(mpctx, true);
    return 0;
}

// Try to refresh the video by doing a precise seek to the currently displayed
// frame. This can go wrong in all sorts of ways, so use sparingly.
void mp_force_video_refresh(struct MPContext *mpctx)
{
    struct MPOpts *opts = mpctx->opts;
    struct dec_video *d_video = mpctx->d_video;

    if (!d_video || !d_video->decoder_output.imgfmt)
        return;

    // If not paused, the next frame should come soon enough.
    if (opts->pause && mpctx->last_vo_pts != MP_NOPTS_VALUE)
        queue_seek(mpctx, MPSEEK_ABSOLUTE, mpctx->last_vo_pts, 2, true);
}

static int check_framedrop(struct MPContext *mpctx)
{
    struct MPOpts *opts = mpctx->opts;
    // check for frame-drop:
    if (mpctx->video_status == STATUS_PLAYING && !mpctx->paused &&
        mpctx->audio_status == STATUS_PLAYING && !ao_untimed(mpctx->ao))
    {
        float fps = mpctx->d_video->fps;
        double frame_time = fps > 0 ? 1.0 / fps : 0;
        // we should avoid dropping too many frames in sequence unless we
        // are too late. and we allow 100ms A-V delay here:
        if (mpctx->last_av_difference - 0.100 > mpctx->dropped_frames * frame_time)
            return !!(opts->frame_dropping & 2);
    }
    return 0;
}

// Read a packet, store decoded image into d_video->waiting_decoded_mpi
// returns VD_* code
static int decode_image(struct MPContext *mpctx)
{
    struct dec_video *d_video = mpctx->d_video;

    if (d_video->header->attached_picture) {
        d_video->waiting_decoded_mpi =
                    video_decode(d_video, d_video->header->attached_picture, 0);
        return VD_EOF;
    }

    struct demux_packet *pkt;
    if (demux_read_packet_async(d_video->header, &pkt) == 0)
        return VD_WAIT;
    if (pkt && pkt->pts != MP_NOPTS_VALUE)
        pkt->pts += mpctx->video_offset;
    if ((pkt && pkt->pts >= mpctx->hrseek_pts - .005) ||
        d_video->has_broken_packet_pts ||
        !mpctx->opts->hr_seek_framedrop)
    {
        mpctx->hrseek_framedrop = false;
    }
    bool hrseek = mpctx->hrseek_active && mpctx->video_status == STATUS_SYNCING;
    int framedrop_type = hrseek && mpctx->hrseek_framedrop ?
                         2 : check_framedrop(mpctx);
    d_video->waiting_decoded_mpi =
        video_decode(d_video, pkt, framedrop_type);
    bool had_packet = !!pkt;
    talloc_free(pkt);

    if (had_packet && !d_video->waiting_decoded_mpi &&
        mpctx->video_status == STATUS_PLAYING)
    {
        mpctx->dropped_frames_total++;
        mpctx->dropped_frames++;
    }

    return had_packet ? VD_PROGRESS : VD_EOF;
}


// Called after video reinit. This can be generally used to try to insert more
// filters using the filter chain edit functionality in command.c.
static void init_filter_params(struct MPContext *mpctx)
{
    struct MPOpts *opts = mpctx->opts;

    // Note that the filter chain is already initialized. This code might
    // recreate the chain a second time, which is not very elegant, but allows
    // us to test whether enabling deinterlacing works with the current video
    // format and other filters.
    if (opts->deinterlace >= 0)
        mp_property_do("deinterlace", M_PROPERTY_SET, &opts->deinterlace, mpctx);
}

// Feed newly decoded frames to the filter, take care of format changes.
// If eof=true, drain the filter chain, and return VD_EOF if empty.
static int video_filter(struct MPContext *mpctx, bool eof)
{
    struct dec_video *d_video = mpctx->d_video;
    struct vf_chain *vf = d_video->vfilter;

    if (vf->initialized < 0)
        return VD_ERROR;

    // There is already a filtered frame available.
    // If vf_needs_input() returns > 0, the filter wants input anyway.
    if (vf_output_frame(vf, eof) > 0 && vf_needs_input(vf) < 1)
        return VD_PROGRESS;

    // Decoder output is different from filter input?
    bool need_vf_reconfig = !vf->input_params.imgfmt || vf->initialized < 1 ||
        !mp_image_params_equal(&d_video->decoder_output, &vf->input_params);

    // (If imgfmt==0, nothing was decoded yet, and the format is unknown.)
    if (need_vf_reconfig && d_video->decoder_output.imgfmt) {
        // Drain the filter chain.
        if (vf_output_frame(vf, true) > 0)
            return VD_PROGRESS;

        // The filter chain is drained; execute the filter format change.
        filter_reconfig(mpctx, false);
        if (vf->initialized == 0)
            return VD_PROGRESS; // hw decoding fallback; try again
        if (vf->initialized < 1)
            return VD_ERROR;
        init_filter_params(mpctx);
        return VD_RECONFIG;
    }

    // If something was decoded, and the filter chain is ready, filter it.
    if (!need_vf_reconfig && d_video->waiting_decoded_mpi) {
        vf_filter_frame(vf, d_video->waiting_decoded_mpi);
        d_video->waiting_decoded_mpi = NULL;
        return VD_PROGRESS;
    }

    return eof ? VD_EOF : VD_PROGRESS;
}

// Make sure at least 1 filtered image is available, decode new video if needed.
// returns VD_* code
// A return value of VD_PROGRESS doesn't necessarily output a frame, but makes
// the promise that calling this function again will eventually do something.
static int video_decode_and_filter(struct MPContext *mpctx)
{
    struct dec_video *d_video = mpctx->d_video;

    int r = video_filter(mpctx, false);
    if (r < 0)
        return r;

    if (!d_video->waiting_decoded_mpi) {
        // Decode a new image, or at least feed the decoder a packet.
        r = decode_image(mpctx);
        if (r == VD_WAIT)
            return r;
        if (d_video->waiting_decoded_mpi)
            d_video->decoder_output = d_video->waiting_decoded_mpi->params;
    }

    bool eof = !d_video->waiting_decoded_mpi && (r == VD_EOF || r < 0);
    r = video_filter(mpctx, eof);
    if (r == VD_RECONFIG) // retry feeding decoded image
        r = video_filter(mpctx, eof);
    return r;
}

static int video_feed_async_filter(struct MPContext *mpctx)
{
    struct dec_video *d_video = mpctx->d_video;
    struct vf_chain *vf = d_video->vfilter;

    if (vf->initialized < 0)
        return VD_ERROR;

    if (vf_needs_input(vf) < 1)
        return 0;
    mpctx->sleeptime = 0; // retry until done
    return video_decode_and_filter(mpctx);
}

/* Modify video timing to match the audio timeline. There are two main
 * reasons this is needed. First, video and audio can start from different
 * positions at beginning of file or after a seek (MPlayer starts both
 * immediately even if they have different pts). Second, the file can have
 * audio timestamps that are inconsistent with the duration of the audio
 * packets, for example two consecutive timestamp values differing by
 * one second but only a packet with enough samples for half a second
 * of playback between them.
 */
static void adjust_sync(struct MPContext *mpctx, double v_pts, double frame_time)
{
    struct MPOpts *opts = mpctx->opts;

    if (mpctx->audio_status != STATUS_PLAYING)
        return;

    double a_pts = written_audio_pts(mpctx) + mpctx->audio_delay - mpctx->delay;
    double av_delay = a_pts - v_pts;

    double change = av_delay * 0.1;
    double max_change = opts->default_max_pts_correction >= 0 ?
                        opts->default_max_pts_correction : frame_time * 0.1;
    if (change < -max_change)
        change = -max_change;
    else if (change > max_change)
        change = max_change;
    mpctx->delay += change;
    mpctx->total_avsync_change += change;
}

// Enough video filtered already to push one frame to the VO?
static bool have_new_frame(struct MPContext *mpctx)
{
    bool need_2nd = !!(mpctx->opts->frame_dropping & 1) // we need the duration
        && mpctx->video_pts != MP_NOPTS_VALUE; // ...except for the 1st frame

    return mpctx->next_frame[0] && (!need_2nd || mpctx->next_frame[1]);
}