StateLayer::StateLayer(ViewLayer& view)
{
  mappings[&view] = this;
  _view = &view;
  _project = new Project();
  assembly::Assembly& assembly = _project->getAssembly();

  _selectionModel = new SelectionModel();

  _view->constructShots(assembly);
  _view->populateConceptSelectCombo(assembly.getOntology());
  _view->rendererBoundsChanged();

  scenegraph::Shot& shot = view.getRootShot();

  _renderingState = new RenderingState(shot);
  _defaultPerspective = new SearchPerspective();

  _currentPerspective = _defaultPerspective;
  _currentInteractionState = new SelectState(*_renderingState);

  _currentPerspective->activate(*_view);

  WindowRef window = _view->getWindow();
  ActivateWindow(window, true);
  SetPortWindowPort(window);
  ShowWindow(window);
  SelectWindow(window);
  ActivateWindow(window, true);

  _selectedLayer = 0;
  _creationType = 0;
}
Example #2
0
void _glfwPlatformRestoreWindow( void )
{
    if( _glfwWin.Fullscreen )
    {
        ScreenToFront( _glfwWin.Screen );
    }
    WindowToFront( _glfwWin.Window );
    ActivateWindow( _glfwWin.Window );
    _glfwWin.Iconified = GL_FALSE;
}
 void DatabaseConnectionWindow::Show()
 {
     if(IsSilent)
     {
         QTimer::singleShot(20000,this,SLOT(Timeout()));
     }else
     {
         QTimer::singleShot(3000,this,SLOT(ActivateWindow()));
     }
 }
Example #4
0
void QuartzWindow::activate() {
  WindowPtr wp = my_window();
  if (!IsWindowVisible(wp))
    ShowWindow(wp);
  SelectWindow(wp);
  OSStatus e = SetUserFocusWindow(wp); 
  if (e) lprintf("SetUserFocus %d\n", e);
  
  e = ActivateWindow(wp, true);
  if (e) lprintf("ActivateWindow %d\n", e);
}
Example #5
0
bool nuiWindowManager::KeyDown(const nglKeyEvent& rEvent)
{
  if (rEvent.mKey == NK_TAB)
  {
    if (IsKeyDown(NK_LCTRL) || IsKeyDown(NK_LCTRL))
    {
      if (mpChildren.front() && mpChildren.size())
      { 
        //        if (!(((nuiWindow*)mpChildren.front())->IsModal()))
        {
          nuiWidgetList::iterator it;
          nuiWidgetList::iterator end = mpChildren.begin();

          it = mpChildren.end();
          it--;
          for (; it!=end; it--)
          {
            if (*it)
            {
              if ((*it)->IsVisible())
              {
                ActivateWindow((nuiWindow*)*it);
                return true;
              }
            }
          }
          if (*it)
          {
            if ((*it)->IsVisible())
            {
              ActivateWindow((nuiWindow*)*it);
              return true;
            }
          }
        }
      }
    }
  }
  return false;
}
Example #6
0
void WindowManager::RegisterWindow(RenderWindow* winPtr) {
#if defined( NEX_WINDOWS )
	Win32Window* window = static_cast<Win32Window*>(winPtr);
	HWND wndH = window->GetWindowHandle();
	SetWindowLongPtr(wndH, GWLP_USERDATA,
			reinterpret_cast<LONG_PTR>(window));

	WNDPROC proc = reinterpret_cast<WNDPROC>(SetWindowLongPtr(wndH,
					GWLP_WNDPROC, reinterpret_cast<LONG_PTR>(&Win32Window::WndProc)));
	window->SetWindowProc(proc);

#endif
	registeredWindows.push_back(winPtr);
	ActivateWindow(winPtr);
}
Example #7
0
bool nuiWindowManager::DispatchMouseClick(const nglMouseInfo& rInfo)
{
  if (!IsEnabled())
    return false;

  if (IsInsideFromRoot(rInfo.X, rInfo.Y))
  {
    if (!mWindows.empty())
    {
      std::list<nuiWindow*>::iterator it;
      std::list<nuiWindow*>::iterator begin = mWindows.begin();
      it = mWindows.end();
      do 
      {
        it--;
        nuiWindow* win = *it;
        if (win->IsInsideFromRoot(rInfo.X, rInfo.Y))
        {
          if (GetActiveWindow() != win)
            ActivateWindow(win);
          break;
        }
      } while (it!=begin);
    }

    IteratorPtr pIt;
    for (pIt = GetLastChild(); pIt && pIt->IsValid(); GetPreviousChild(pIt))
    {
      nuiWidgetPtr pItem = pIt->GetWidget();
      if (pItem && pItem->IsVisible() && pItem->IsEnabled())
      {
        if (pItem->DispatchMouseClick(rInfo))
        {
          delete pIt;
          return true;
        }
      }
    }
    delete pIt;

    nglMouseInfo info(rInfo);
    GlobalToLocal(info.X, info.Y);
    bool ret = MouseClicked(info);
    ret |= Clicked(info);
    return ret;
  }
  return false;
}
Example #8
0
/* $ 29.12.2000 IS
  Аналог CloseAll, но разрешает продолжение полноценной работы в фаре,
  если пользователь продолжил редактировать файл.
  Возвращает TRUE, если все закрыли и можно выходить из фара.
*/
BOOL Manager::ExitAll()
{
	_MANAGER(CleverSysLog clv(L"Manager::ExitAll()"));

	// BUGBUG don't use iterators here, may be invalidated by DeleteCommit()
	for(size_t i = m_modalWindows.size(); i; --i)
	{
		if (i - 1 >= m_modalWindows.size())
			continue;
		auto CurrentWindow = m_modalWindows[i - 1];
		if (!CurrentWindow->GetCanLoseFocus(TRUE))
		{
			auto PrevWindowCount = m_modalWindows.size();
			CurrentWindow->ProcessKey(Manager::Key(KEY_ESC));
			Commit();

			if (PrevWindowCount == m_modalWindows.size())
			{
				return FALSE;
			}
		}
	}

	// BUGBUG don't use iterators here, may be invalidated by DeleteCommit()
	for(size_t i = m_windows.size(); i; --i)
	{
		if (i - 1 >= m_windows.size())
			continue;
		auto CurrentWindow = m_windows[i - 1];
		if (!CurrentWindow->GetCanLoseFocus(TRUE))
		{
			ActivateWindow(CurrentWindow);
			Commit();
			auto PrevWindoowCount = m_windows.size();
			CurrentWindow->ProcessKey(Manager::Key(KEY_ESC));
			Commit();

			if (PrevWindoowCount == m_windows.size())
			{
				return FALSE;
			}
		}
	}

	return TRUE;
}
Example #9
0
void ShowDialog(Dialog dialog) {
  InitializeDialogProperties();

  auto it = dialog_properties.find(dialog);

  if (it != dialog_properties.end()) {
    if (it->second.dialog) {
      if (!it->second.dialog->IsWindow()) {
        it->second.dialog->Create(it->second.resource_id,
                                  GetWindowHandle(it->second.parent),
                                  it->second.modal);
      } else {
        ActivateWindow(it->second.dialog->GetWindowHandle());
      }
    }
  }
}
Example #10
0
// Show about requester
void font_show_about(font_data *data)
{
	struct EasyStruct easy;

	// Window open?
	if (data->about)
	{
		WindowToFront(data->about);
		ActivateWindow(data->about);
		return;
	}

	// Fill out easy struct
	easy.es_StructSize=sizeof(easy);
	easy.es_Flags=0;
	easy.es_Title=0;
	easy.es_TextFormat="Directory Opus 5 Font Viewer\nv55.0 (01.08.96)\n\n© 1996 Jonathan Potter";
	easy.es_GadgetFormat=GetString(&data->locale,MSG_OK);

	// Open requester
	data->about=BuildEasyRequest(data->window,&easy,0,0);
}
short LIBFUNC L_Config_Filetypes(
	REG(a0, struct Screen *screen),
	REG(a1, IPCData *ipc),
	REG(a2, IPCData *owner_ipc),
	REG(d0, ULONG command_list),
	REG(a3, char *name))
{
	config_filetypes_data *data;
	IPCMessage *quit_msg=0;
	short undo_flag=0,pending_quit=0;
	short ret=0,fontsize;
	struct IBox pos;
	ConfigWindow dims;

	// Allocate data and memory handle
	if (!(data=AllocVec(sizeof(config_filetypes_data),MEMF_CLEAR)) ||
		!(data->memory=NewMemHandle(4096,256,MEMF_CLEAR)))
		return 0;

	// Save pointers
	data->ipc=ipc;
	data->owner_ipc=owner_ipc;
	data->command_list=command_list;

	// Initialise data
	NewList(&data->list_list);
	InitListLock(&data->proc_list,0);

	// Fill in new window
	data->newwin.parent=screen;
	data->newwin.dims=&dims;
	data->newwin.title=GetString(locale,MSG_FILETYPES_TITLE);
	data->newwin.locale=locale;
	data->newwin.flags=WINDOW_SCREEN_PARENT|WINDOW_VISITOR|WINDOW_REQ_FILL|WINDOW_AUTO_KEYS|WINDOW_SIZE_BOTTOM;

	// Get default size
	dims=_config_filetypes_window;

	// Get saved position
	if (LoadPos("dopus/windows/filetypes",&pos,&fontsize))
	{
		dims.char_dim.Width=0;
		dims.char_dim.Height=0;
		dims.fine_dim.Width=pos.Width;
		dims.fine_dim.Height=pos.Height;
	}
		
	// Open window and add objects
	if (!(data->window=OpenConfigWindow(&data->newwin)) ||
		!(data->objlist=AddObjectList(data->window,_config_filetypes_objects)))
	{
		CloseConfigWindow(data->window);
		FreeMemHandle(data->memory);
		FreeVec(data);
		return 0;
	}

	// Set minimum size
	SetConfigWindowLimits(data->window,&_config_filetypes_window,0);

	// Read filetype list
	SetWindowBusy(data->window);
	filetype_read_list(data->memory,&data->list_list);

	// Build display list
	filetype_build_list(data);
	ClearWindowBusy(data->window);

	// Name to edit?
	if (name) filetype_edit_name(data,name);

	// Event loop
	FOREVER
	{
		struct IntuiMessage *msg;
		IPCMessage *imsg;
		int quit_flag=0;

		// Any IPC messages?
		while ((imsg=(IPCMessage *)GetMsg(ipc->command_port)))
		{
			// Look at command
			switch (imsg->command)
			{
				// Quit
				case IPC_QUIT:
					quit_flag=1;
					quit_msg=imsg;
					imsg=0;
					data->change=0;
					break;


				// Activate
				case IPC_ACTIVATE:
					if (data->window)
					{
						// Bring window to front
						WindowToFront(data->window);
						ActivateWindow(data->window);

						// Edit name supplied?
						if (imsg->data) filetype_edit_name(data,(char *)imsg->data);
					}
					break;


				// Process saying goodbye
				case IPC_GOODBYE:
					{
						FiletypeNode *node;

						// Handle goodbye
						if ((node=(FiletypeNode *)IPC_GetGoodbye(imsg)))
						{
							// Node no longer has an editor
							node->editor=0;
						}

						// All process gone and pending quit?
						if (pending_quit && (IsListEmpty(&data->proc_list.list)))
						{
							quit_flag=1;
							pending_quit=2;
						}
					}
					break;


				// Got a filetype back from the editor
				case FILETYPEEDIT_RETURN:
					if (filetype_receive_edit(
						data,
						(Cfg_Filetype *)imsg->flags,
						(FiletypeNode *)imsg->data))
					{
						data->change=1;
						imsg->command=1;
					}
					else imsg->command=0;
					break;
			}

			// Reply message
			IPC_Reply(imsg);

			// Check quit flag
			if (quit_flag) break;
		}

		// Intuimessages
		if (data->window)
		{
			while ((msg=GetWindowMsg(data->window->UserPort)))
			{
				struct IntuiMessage msg_copy;
				UWORD id;

				// Copy message and reply
				msg_copy=*msg;
				ReplyWindowMsg(msg);

				if (pending_quit) continue;

				// Look at message
				switch (msg_copy.Class)
				{
					// Close window
					case IDCMP_CLOSEWINDOW:
						quit_flag=1;
						undo_flag=1;
						break;


					// Gadget
					case IDCMP_GADGETUP:

						id=((struct Gadget *)msg_copy.IAddress)->GadgetID;
						switch (id)
						{
							// Cancel
							case GAD_FILETYPES_CANCEL:
								undo_flag=1;

							// Use
							case GAD_FILETYPES_USE:
								quit_flag=1;
								break;


							// Filetype selected
							case GAD_FILETYPES_LIST:
								{
									Att_Node *node;

									// Enable buttons
									filetype_able_buttons(data,FALSE);

									// Get selection
									if (!(node=Att_FindNode(data->filetype_list,msg_copy.Code)))
										break;

									// Double-click?
									if (node==data->sel_filetype &&
										DoubleClick(
											data->seconds,data->micros,
											msg_copy.Seconds,msg_copy.Micros))
									{
										// Launch editor for this filetype
										filetype_edit(data,(FiletypeNode *)data->sel_filetype->data,0);
									}

									// New selection
									else
									{
										data->sel_filetype=node;
										data->seconds=msg_copy.Seconds;
										data->micros=msg_copy.Micros;
									}
								}
								break;


							// Add a new filetype
							case GAD_FILETYPES_DUPLICATE:
								if (!data->sel_filetype) break;
							case GAD_FILETYPES_ADD:
								{
									Cfg_FiletypeList *list;
									Cfg_Filetype *type=0;

									// Allocate a new filetype list
									if ((list=AllocMemH(data->memory,sizeof(Cfg_FiletypeList))))
									{
										// Initialise list
										NewList(&list->filetype_list);

										// Copy existing filetype?
										if ((((struct Gadget *)msg_copy.IAddress)->GadgetID==
											GAD_FILETYPES_DUPLICATE))
										{
											// Copy filetype
											type=CopyFiletype(
												((FiletypeNode *)data->sel_filetype->data)->type,
												data->memory);
										}

										// Allocate a new filetype
										else if ((type=NewFiletype(data->memory)))
										{
											// Initialise name
											strcpy(type->type.name,GetString(locale,MSG_UNTITLED));
										}

										// Get a filetype?
										if (type)
										{
											// Add filetype list to main list
											AddTail(&data->list_list,&list->node);

											// Add filetype to list
											AddTail(&list->filetype_list,&type->node);

											// Set list pointer
											type->list=list;
											list->flags=FTLISTF_CHANGED;
										}

										// Failed
										else FreeMemH(list);
									}

									// Got new filetype?
									if (type)
									{
										Att_Node *node;

										// Remove existing list
										SetGadgetChoices(
											data->objlist,
											GAD_FILETYPES_LIST,
											(APTR)~0);

										// Add entry for this filetype
										node=filetype_add_entry(data,type);

										// Handle new nodes
										filetype_new_node(data,node);
									}
								}
								break;


							// Edit filetype
							case GAD_FILETYPES_EDIT:

								// Valid selection?
								if (data->sel_filetype)
								{
									// Launch editor for this filetype
									filetype_edit(data,(FiletypeNode *)data->sel_filetype->data,0);
								}
								break;


							// Remove/Store
							case GAD_FILETYPES_REMOVE:
							case GAD_FILETYPES_STORE:

								// Valid selection?
								if (data->sel_filetype)
								{
									short ret;

									// Remove filetype
									if ((ret=
										filetype_remove(
											data,
											data->sel_filetype,
											(id==GAD_FILETYPES_STORE)))==1)
									{
										data->change=1;
										data->sel_filetype=0;
									}

									// Quit?
									else if (ret==-1)
									{
										quit_flag=1;
									}
								}
								break;
						}
						break;


					// Key press
					case IDCMP_RAWKEY:

						// Help?
						if (msg_copy.Code==0x5f &&
							!(msg_copy.Qualifier&VALID_QUALIFIERS))
						{
							// Set busy pointer
							SetWindowBusy(data->window);

							// Send help command
							IPC_Command(data->owner_ipc,IPC_HELP,(1<<31),"File Types",0,REPLY_NO_PORT);

							// Clear busy pointer
							ClearWindowBusy(data->window);
						}
						break;
				}

				// Check quit flag
				if (quit_flag) break;
			}
		}

		// Check quit flag
		if (quit_flag)
		{
			if (!pending_quit)
			{
				SetWindowBusy(data->window);
				if (!(IPC_ListQuit(&data->proc_list,0,!undo_flag,FALSE)))
					pending_quit=2;
				else
					pending_quit=1;
			}
		}

		// Set to break?
		if (pending_quit==2)
		{
			// Save filetypes?
			if (data->change && !undo_flag)
			{
				if (!(ret=filetype_save(data)))
				{
					// Abort save/quit
					ClearWindowBusy(data->window);
					pending_quit=0;
					continue;
				}
			}
			break;
		}

		// Wait for an event
		Wait(1<<ipc->command_port->mp_SigBit|
			((data->window)?1<<data->window->UserPort->mp_SigBit:0));
	}

	// Save window position
	if (data->window)
	{
		struct IBox pos;
		pos.Left=data->window->LeftEdge;
		pos.Top=data->window->TopEdge;
		pos.Width=data->window->Width-data->window->BorderLeft-data->window->BorderRight;
		pos.Height=data->window->Height-data->window->BorderTop-data->window->BorderBottom;
		SavePos("dopus/windows/filetypes",(struct IBox *)&pos,data->window->RPort->TxHeight);
	}

	// Close up
	CloseConfigWindow(data->window);

	// Free data
	Att_RemList(data->filetype_list,REMLIST_FREEDATA);
	FreeMemHandle(data->memory);
	FreeVec(data);

	// Reply quit message
	IPC_Reply(quit_msg);
	return ret;
}
Example #12
0
void ExecuteAction(std::wstring action, WPARAM wParam, LPARAM lParam) {
  LOG(LevelDebug, action);

  std::wstring body;
  size_t pos = action.find('(');
  if (pos != action.npos) {
    body = action.substr(pos + 1, action.find_last_of(')') - (pos + 1));
    action.resize(pos);
  }
  Trim(body);
  Trim(action);
  if (action.empty())
    return;

  //////////////////////////////////////////////////////////////////////////////
  // Taiga

  // CheckUpdates()
  //   Checks for a new version of the program.
  if (action == L"CheckUpdates") {
    ui::ShowDialog(ui::kDialogUpdate);

  // Exit(), Quit()
  //   Exits from Taiga.
  } else if (action == L"Exit" || action == L"Quit") {
    ui::DlgMain.Destroy();

  //////////////////////////////////////////////////////////////////////////////
  // Services

  // Synchronize()
  //   Synchronizes local and remote lists.
  } else if (action == L"Synchronize") {
    sync::Synchronize();

  // SearchAnime()
  //   wParam is a BOOL value that defines local search.
  } else if (action == L"SearchAnime") {
    if (body.empty())
      return;
    bool local_search = wParam != FALSE;
    if (!local_search) {
      auto service = taiga::GetCurrentService();
      if (service->RequestNeedsAuthentication(sync::kSearchTitle)) {
        if (taiga::GetCurrentUsername().empty() ||
            taiga::GetCurrentPassword().empty()) {
          ui::OnSettingsAccountEmpty();
          return;
        }
      }
    }
    ui::DlgMain.navigation.SetCurrentPage(ui::kSidebarItemSearch);
    ui::DlgMain.edit.SetText(body);
    ui::DlgSearch.Search(body, local_search);

  // ViewAnimePage
  //   Opens up anime page on the active service.
  //   lParam is an anime ID.
  } else if (action == L"ViewAnimePage") {
    int anime_id = static_cast<int>(lParam);
    switch (taiga::GetCurrentServiceId()) {
      case sync::kMyAnimeList:
        sync::myanimelist::ViewAnimePage(anime_id);
        break;
      case sync::kHummingbird:
        sync::hummingbird::ViewAnimePage(anime_id);
        break;
    }

  // ViewUpcomingAnime
  //   Opens up upcoming anime page on MAL.
  } else if (action == L"ViewUpcomingAnime") {
    switch (taiga::GetCurrentServiceId()) {
      case sync::kMyAnimeList:
        sync::myanimelist::ViewUpcomingAnime();
        break;
      case sync::kHummingbird:
        sync::hummingbird::ViewUpcomingAnime();
        break;
    }

  // MalViewPanel()
  // MalViewProfile()
  // MalViewHistory()
  //   Opens up MyAnimeList user pages.
  } else if (action == L"MalViewPanel") {
    sync::myanimelist::ViewPanel();
  } else if (action == L"MalViewProfile") {
    sync::myanimelist::ViewProfile();
  } else if (action == L"MalViewHistory") {
    sync::myanimelist::ViewHistory();

  // HummingbirdViewProfile()
  // HummingbirdViewDashboard()
  // HummingbirdViewRecommendations()
  //   Opens up Hummingbird user pages.
  } else if (action == L"HummingbirdViewProfile") {
    sync::hummingbird::ViewProfile();
  } else if (action == L"HummingbirdViewDashboard") {
    sync::hummingbird::ViewDashboard();
  } else if (action == L"HummingbirdViewRecommendations") {
    sync::hummingbird::ViewRecommendations();

  //////////////////////////////////////////////////////////////////////////////

  // Execute(path)
  //   Executes a file or folder.
  } else if (action == L"Execute") {
    Execute(body);

  // URL(address)
  //   Opens a web page.
  //   lParam is an anime ID.
  } else if (action == L"URL") {
    int anime_id = static_cast<int>(lParam);
    auto anime_item = AnimeDatabase.FindItem(anime_id);
    if (anime_item) {
      std::wstring title = anime_item->GetTitle();
      ReplaceString(body, L"%title%", EncodeUrl(title));
    }
    ExecuteLink(body);

  //////////////////////////////////////////////////////////////////////////////
  // UI

  // About()
  //   Shows about window.
  } else if (action == L"About") {
    ui::ShowDialog(ui::kDialogAbout);

  // Info([anime_id])
  //   Shows anime information window.
  //   lParam is an anime ID.
  } else if (action == L"Info") {
    int anime_id = body.empty() ? static_cast<int>(lParam) : ToInt(body);
    ui::ShowDlgAnimeInfo(anime_id);

  // MainDialog()
  } else if (action == L"MainDialog") {
    ui::ShowDialog(ui::kDialogMain);

  // Settings()
  //   Shows settings window.
  //   wParam is the initial section.
  //   lParam is the initial page.
  } else if (action == L"Settings") {
    ui::ShowDlgSettings(wParam, lParam);

  // SearchTorrents(source)
  //   Searches torrents from specified source URL.
  //   lParam is an anime ID.
  } else if (action == L"SearchTorrents") {
    int anime_id = static_cast<int>(lParam);
    if (body.empty())
      body = Settings[taiga::kTorrent_Discovery_SearchUrl];
    ui::DlgTorrent.Search(body, anime_id);

  // ToggleSidebar()
  } else if (action == L"ToggleSidebar") {
    bool hide_sidebar = Settings.Toggle(taiga::kApp_Option_HideSidebar);
    ui::DlgMain.treeview.Show(!hide_sidebar);
    ui::DlgMain.UpdateControlPositions();
    ui::Menus.UpdateView();

  // TorrentAddFilter()
  //   Shows add new filter window.
  //   wParam is a BOOL value that represents modal status.
  //   lParam is the handle of the parent window.
  } else if (action == L"TorrentAddFilter") {
    if (!ui::DlgFeedFilter.IsWindow()) {
      ui::DlgFeedFilter.Create(IDD_FEED_FILTER,
          reinterpret_cast<HWND>(lParam), wParam != FALSE);
    } else {
      ActivateWindow(ui::DlgFeedFilter.GetWindowHandle());
    }

  // ViewContent(page)
  //   Selects a page from sidebar.
  } else if (action == L"ViewContent") {
    int page = ToInt(body);
    ui::DlgMain.navigation.SetCurrentPage(page);

  //////////////////////////////////////////////////////////////////////////////
  // Library

  // AddToList(status)
  //   Adds an anime to list with given status.
  //   wParam is a BOOL value that defines lParam.
  //   lParam is an anime ID, or a pointer to a vector of anime IDs.
  } else if (action == L"AddToList") {
    int status = ToInt(body);
    if (!wParam) {
      int anime_id = static_cast<int>(lParam);
      AnimeDatabase.AddToList(anime_id, status);
    } else {
      const auto& anime_ids = *reinterpret_cast<std::vector<int>*>(lParam);
      for (const auto& anime_id : anime_ids) {
        AnimeDatabase.AddToList(anime_id, status);
      }
    }

  // ClearHistory()
  //   Deletes all history items.
  } else if (action == L"ClearHistory") {
    if (ui::OnHistoryClear())
      History.Clear();

  //////////////////////////////////////////////////////////////////////////////
  // Tracker

  // AddFolder()
  //   Opens up a dialog to add new library folder.
  } else if (action == L"AddFolder") {
    std::wstring path;
    if (win::BrowseForFolder(ui::GetWindowHandle(ui::kDialogMain),
                             L"Add a Library Folder", L"", path)) {
      Settings.library_folders.push_back(path);
      if (Settings.GetBool(taiga::kLibrary_WatchFolders))
        FolderMonitor.Enable();
      ui::ShowDlgSettings(ui::kSettingsSectionLibrary, ui::kSettingsPageLibraryFolders);
    }

  // ScanEpisodes(), ScanEpisodesAll()
  //   Checks episode availability.
  } else if (action == L"ScanEpisodes") {
    int anime_id = static_cast<int>(lParam);
    ScanAvailableEpisodes(false, anime_id, 0);
  } else if (action == L"ScanEpisodesAll") {
    ScanAvailableEpisodes(false);

  //////////////////////////////////////////////////////////////////////////////
  // Settings

  // ToggleRecognition()
  //   Enables or disables anime recognition.
  } else if (action == L"ToggleRecognition") {
    bool enable_recognition = Settings.Toggle(taiga::kApp_Option_EnableRecognition);
    if (enable_recognition) {
      ui::ChangeStatusText(L"Automatic anime recognition is now enabled.");
      CurrentEpisode.Set(anime::ID_UNKNOWN);
    } else {
      ui::ChangeStatusText(L"Automatic anime recognition is now disabled.");
      auto anime_item = AnimeDatabase.FindItem(CurrentEpisode.anime_id);
      CurrentEpisode.Set(anime::ID_NOTINLIST);
      if (anime_item)
        EndWatching(*anime_item, CurrentEpisode);
    }

  // ToggleSharing()
  //   Enables or disables automatic sharing.
  } else if (action == L"ToggleSharing") {
    bool enable_sharing = Settings.Toggle(taiga::kApp_Option_EnableSharing);
    ui::Menus.UpdateTools();
    if (enable_sharing) {
      ui::ChangeStatusText(L"Automatic sharing is now enabled.");
    } else {
      ui::ChangeStatusText(L"Automatic sharing is now disabled.");
    }

  // ToggleSynchronization()
  //   Enables or disables automatic list synchronization.
  } else if (action == L"ToggleSynchronization") {
    bool enable_sync = Settings.Toggle(taiga::kApp_Option_EnableSync);
    ui::Menus.UpdateTools();
    if (enable_sync) {
      ui::ChangeStatusText(L"Automatic synchronization is now enabled.");
    } else {
      ui::ChangeStatusText(L"Automatic synchronization is now disabled.");
    }

  //////////////////////////////////////////////////////////////////////////////
  // Sharing

  // AnnounceToHTTP(force)
  //   Sends an HTTP request.
  } else if (action == L"AnnounceToHTTP") {
    Announcer.Do(taiga::kAnnounceToHttp, nullptr, body == L"true");

  // AnnounceToMIRC(force)
  //   Sends message to specified channels in mIRC.
  } else if (action == L"AnnounceToMIRC") {
    Announcer.Do(taiga::kAnnounceToMirc, nullptr, body == L"true");

  // AnnounceToSkype(force)
  //   Changes Skype mood text.
  //   Requires authorization.
  } else if (action == L"AnnounceToSkype") {
    Announcer.Do(taiga::kAnnounceToSkype, nullptr, body == L"true");

  // AnnounceToTwitter(force)
  //   Changes Twitter status.
  } else if (action == L"AnnounceToTwitter") {
    Announcer.Do(taiga::kAnnounceToTwitter, nullptr, body == L"true");

  //////////////////////////////////////////////////////////////////////////////

  // EditAll([anime_id])
  //   Shows a dialog to edit details of an anime.
  //   lParam is an anime ID.
  } else if (action == L"EditAll") {
    int anime_id = body.empty() ? static_cast<int>(lParam) : ToInt(body);
    ui::ShowDlgAnimeEdit(anime_id);

  // EditDelete()
  //   Removes an anime from list.
  //   lParam is a pointer to a vector of anime IDs.
  } else if (action == L"EditDelete") {
    const auto& anime_ids = *reinterpret_cast<std::vector<int>*>(lParam);
    if (ui::OnLibraryEntriesEditDelete(anime_ids)) {
      for (const auto& anime_id : anime_ids) {
        HistoryItem history_item;
        history_item.anime_id = anime_id;
        history_item.mode = taiga::kHttpServiceDeleteLibraryEntry;
        History.queue.Add(history_item);
      }
    }

  // EditEpisode()
  //   Changes watched episode value of an anime.
  //   lParam is a pointer to a vector of anime IDs.
  } else if (action == L"EditEpisode") {
    const auto& anime_ids = *reinterpret_cast<std::vector<int>*>(lParam);
    int value = ui::OnLibraryEntriesEditEpisode(anime_ids);
    if (value > -1) {
      for (const auto& anime_id : anime_ids) {
        anime::ChangeEpisode(anime_id, value);
      }
    }

  // DecrementEpisode()
  //   lParam is an anime ID.
  } else if (action == L"DecrementEpisode") {
    int anime_id = static_cast<int>(lParam);
    anime::DecrementEpisode(anime_id);
  // IncrementEpisode()
  //   lParam is an anime ID.
  } else if (action == L"IncrementEpisode") {
    int anime_id = static_cast<int>(lParam);
    anime::IncrementEpisode(anime_id);

  // EditScore(value)
  //   Changes anime score.
  //   Value must be between 0-10 and different from current score.
  //   lParam is a pointer to a vector of anime IDs.
  } else if (action == L"EditScore") {
    const auto& anime_ids = *reinterpret_cast<std::vector<int>*>(lParam);
    for (const auto& anime_id : anime_ids) {
      HistoryItem history_item;
      history_item.anime_id = anime_id;
      history_item.score = ToInt(body);
      history_item.mode = taiga::kHttpServiceUpdateLibraryEntry;
      History.queue.Add(history_item);
    }

  // EditStatus(value)
  //   Changes anime status of user.
  //   Value must be 1, 2, 3, 4 or 5, and different from current status.
  //   lParam is a pointer to a vector of anime IDs.
  } else if (action == L"EditStatus") {
    const auto& anime_ids = *reinterpret_cast<std::vector<int>*>(lParam);
    for (const auto& anime_id : anime_ids) {
      HistoryItem history_item;
      history_item.status = ToInt(body);
      auto anime_item = AnimeDatabase.FindItem(anime_id);
      if (!anime_item)
        continue;
      switch (*history_item.status) {
        case anime::kCompleted:
          history_item.episode = anime_item->GetEpisodeCount();
          if (*history_item.episode == 0)
            history_item.episode.Reset();
          if (!anime::IsValidDate(anime_item->GetMyDateStart()) &&
              anime_item->GetEpisodeCount() == 1)
              history_item.date_start = GetDate();
          if (!anime::IsValidDate(anime_item->GetMyDateEnd()))
            history_item.date_finish = GetDate();
          break;
      }
      history_item.anime_id = anime_id;
      history_item.mode = taiga::kHttpServiceUpdateLibraryEntry;
      History.queue.Add(history_item);
    }

  // EditTags(tags)
  //   Changes anime tags.
  //   Tags must be separated by a comma.
  //   lParam is a pointer to a vector of anime IDs.
  } else if (action == L"EditTags") {
    const auto& anime_ids = *reinterpret_cast<std::vector<int>*>(lParam);
    std::wstring tags;
    if (ui::OnLibraryEntriesEditTags(anime_ids, tags)) {
      for (const auto& anime_id : anime_ids) {
        HistoryItem history_item;
        history_item.anime_id = anime_id;
        history_item.tags = tags;
        history_item.mode = taiga::kHttpServiceUpdateLibraryEntry;
        History.queue.Add(history_item);
      }
    }

  //////////////////////////////////////////////////////////////////////////////

  // OpenFolder()
  //   Searches for anime folder and opens it.
  //   lParam is an anime ID.
  } else if (action == L"OpenFolder") {
    int anime_id = static_cast<int>(lParam);
    auto anime_item = AnimeDatabase.FindItem(anime_id);
    if (!anime_item || !anime_item->IsInList())
      return;
    if (!anime::ValidateFolder(*anime_item))
      ScanAvailableEpisodes(false, anime_item->GetId(), 0);
    if (anime_item->GetFolder().empty()) {
      if (ui::OnAnimeFolderNotFound()) {
        std::wstring default_path, path;
        if (!Settings.library_folders.empty())
          default_path = Settings.library_folders.front();
        if (win::BrowseForFolder(ui::GetWindowHandle(ui::kDialogMain),
                                 L"Select Anime Folder",
                                 default_path, path)) {
          anime_item->SetFolder(path);
          Settings.Save();
        }
      }
    }
    ui::ClearStatusText();
    if (!anime_item->GetFolder().empty()) {
      Execute(anime_item->GetFolder());
    }

  //////////////////////////////////////////////////////////////////////////////

  // PlayEpisode(value)
  //   Searches for an episode of an anime and plays it.
  //   lParam is an anime ID.
  } else if (action == L"PlayEpisode") {
    int number = ToInt(body);
    int anime_id = static_cast<int>(lParam);
    anime::PlayEpisode(anime_id, number);

  // PlayLast()
  //   Searches for the last watched episode of an anime and plays it.
  //   lParam is an anime ID.
  } else if (action == L"PlayLast") {
    int anime_id = static_cast<int>(lParam);
    anime::PlayLastEpisode(anime_id);

  // PlayNext([anime_id])
  //   Searches for the next episode of an anime and plays it.
  //   lParam is an anime ID.
  } else if (action == L"PlayNext") {
    int anime_id = body.empty() ? static_cast<int>(lParam) : ToInt(body);
    if (anime::IsValidId(anime_id)) {
      anime::PlayNextEpisode(anime_id);
    } else {
      anime::PlayNextEpisodeOfLastWatchedAnime();
    }

  // PlayRandom()
  //   Searches for a random episode of an anime and plays it.
  //   lParam is an anime ID.
  } else if (action == L"PlayRandom") {
    int anime_id = body.empty() ? static_cast<int>(lParam) : ToInt(body);
    anime::PlayRandomEpisode(anime_id);

  // PlayRandomAnime()
  //   Searches for a random episode of a random anime and plays it.
  } else if (action == L"PlayRandomAnime") {
    anime::PlayRandomAnime();

  //////////////////////////////////////////////////////////////////////////////

  // Season_Load(file)
  //   Loads season data.
  } else if (action == L"Season_Load") {
    if (SeasonDatabase.Load(body)) {
      SeasonDatabase.Review();
      ui::DlgSeason.RefreshList();
      ui::DlgSeason.RefreshStatus();
      ui::DlgSeason.RefreshToolbar();
      if (SeasonDatabase.IsRefreshRequired())
        if (ui::OnSeasonRefreshRequired())
          ui::DlgSeason.RefreshData();
    }

  // Season_GroupBy(group)
  //   Groups season data.
  } else if (action == L"Season_GroupBy") {
    ui::DlgSeason.group_by = ToInt(body);
    ui::DlgSeason.RefreshList();
    ui::DlgSeason.RefreshToolbar();

  // Season_SortBy(sort)
  //   Sorts season data.
  } else if (action == L"Season_SortBy") {
    ui::DlgSeason.sort_by = ToInt(body);
    ui::DlgSeason.RefreshList();
    ui::DlgSeason.RefreshToolbar();

  // Season_RefreshItemData()
  //   Refreshes an individual season item data.
  //   lParam is a pointer to a vector of anime IDs.
  } else if (action == L"Season_RefreshItemData") {
    const auto& anime_ids = *reinterpret_cast<std::vector<int>*>(lParam);
    for (const auto& anime_id : anime_ids) {
      ui::DlgSeason.RefreshData(anime_id);
    }

  // Season_ViewAs(mode)
  //   Changes view mode.
  } else if (action == L"Season_ViewAs") {
    ui::DlgSeason.SetViewMode(ToInt(body));
    ui::DlgSeason.RefreshList();
    ui::DlgSeason.RefreshToolbar();

  // Unknown
  } else {
    LOG(LevelWarning, L"Unknown action: " + action);
  }
}
void SAVEDS PaletteBox(void)
{
	PaletteBoxData *data;
	struct Window *window;
	IPCData *ipc;

	// Do startup
	if (!(ipc=Local_IPC_ProcStartup((ULONG *)&data,0)))
	{
		Forbid();
		return;
	}

	// Get pen count
	data->pen_count=data->screen_data.pen_count;

	// Open window
	if ((window=palette_box_open(data,data->stuff.stuff1.object_def,data->pen_array,data->pen_array)))
	{
		// Event loop
		FOREVER
		{
			struct IntuiMessage *msg;
			IPCMessage *imsg;
			short break_flag=0;

			// IPC messages
			while ((imsg=(IPCMessage *)GetMsg(ipc->command_port)))
			{
				switch (imsg->command)
				{
					// Quit
					case IPC_QUIT:
						break_flag=1;
						break;

					// Activate
					case IPC_ACTIVATE:
						if (window)
						{
							WindowToFront(window);
							ActivateWindow(window);
						}
						break;

					// Hide
					case IPC_HIDE:
						CloseConfigWindow(window);
						window=0;
						break;

					// Show
					case IPC_SHOW:
						data->newwin.parent=(void *)imsg->data;
						if (!(window=palette_box_open(data,data->stuff.stuff1.object_def,data->pen_array,data->pen_array)))
							break_flag=1;
						break;
				}

				IPC_Reply(imsg);
			}

			// Intuition messages
			if (window)
			{
				while ((msg=GetWindowMsg(window->UserPort)))
				{
					struct IntuiMessage msg_copy;
					msg_copy=*msg;
					ReplyWindowMsg(msg);

					// Close
					if (msg_copy.Class==IDCMP_CLOSEWINDOW)
						break_flag=1;

					// Gadget
					else
					if (msg_copy.Class==IDCMP_GADGETUP)
					{
						short fg,bg;

						// Get foreground and background colours
						fg=GetGadgetValue(OBJLIST(window),GAD_PALETTE_FOREGROUND);
						bg=GetGadgetValue(OBJLIST(window),GAD_PALETTE_BACKGROUND);

						// Fix pens
						if (((struct Library*)IntuitionBase)->lib_Version>=39)
						{
							if (fg>=4 && fg<8) fg=248+fg;
							else
							if (fg>7) fg-=4;
							if (bg>=4 && bg<8) bg=248+bg;
							else
							if (bg>7) bg-=4;
						}
						data->fgpen=fg;
						data->bgpen=bg;

						// Send new colours
						IPC_Command(
							data->owner_ipc,
							BUTTONEDIT_NEW_COLOURS,
							data->fgpen,
							(APTR)data->bgpen,
							0,
							0);
					}

					// Key
					else
					if (msg_copy.Class==IDCMP_RAWKEY)
					{
						// Help?
						if (msg_copy.Code==0x5f &&
							!(msg_copy.Qualifier&VALID_QUALIFIERS))
						{
							// Set busy pointer
							SetWindowBusy(window);

							// Send help command
							IPC_Command(data->main_ipc,IPC_HELP,(1<<31),"Select Colours",0,REPLY_NO_PORT);

							// Clear busy pointer
							ClearWindowBusy(window);
						}
					}
				}
			}

			if (break_flag) break;

			Wait(1<<ipc->command_port->mp_SigBit|
				((window)?1<<window->UserPort->mp_SigBit:0));
		}

		CloseConfigWindow(window);
	}
Example #14
0
void desktop_drop(BackdropInfo *info,DOpusAppMessage *msg,UWORD qual)
{
	BackdropObject *drop_obj;
	short ok=0,x,y;
	char *name,*source_path;
	short arg,action=DESKTOP_POPUP_LEFTOUT;
	struct ArgArray *array=0;
	struct ArgArrayEntry *aae;
	BOOL check;

	// Lock backdrop list
	lock_listlock(&info->objects,0);

	// See if we dropped stuff on an object
	if ((drop_obj=backdrop_get_object(info,msg->da_Msg.am_MouseX,msg->da_Msg.am_MouseY,0)))
	{
		// Is shift/alt down?
		if ((qual&(IEQUALIFIER_LSHIFT|IEQUALIFIER_LALT))==(IEQUALIFIER_LSHIFT|IEQUALIFIER_LALT))
		{
			char pathname[256];

			// Get path of first file
			GetWBArgPath(&msg->da_Msg.am_ArgList[0],pathname,256);

			// Replace the image
			backdrop_replace_icon_image(info,pathname,drop_obj);

			// Reply the message
			ReplyAppMessage(msg);
		}

		// Handle drop on an object
		else
		if (desktop_drop_on_object(info,&msg,drop_obj,qual))
		{
			// Reply the message
			ReplyAppMessage(msg);
		}

		// Not dropped
		else drop_obj=0;
	}

	// Unlock backdrop list
	unlock_listlock(&info->objects);

	// Dropped on an object?
	if (drop_obj) return;

	// Get buffer
	if (!(name=AllocVec(1024,MEMF_CLEAR))) return;
	source_path=name+512;

	// Popup menu?
	if (environment->env->env_flags&ENVF_DESKTOP_FOLDER)
	{
		UWORD res;

		// Activate the underlying menu
		ActivateWindow(info->window);

		// Default action set?
		if (environment->env->desktop_popup_default>DESKTOP_POPUP_NONE &&
			!(qual&(IEQUALIFIER_LSHIFT|IEQUALIFIER_RSHIFT)))
		{
			// Use default action
			action=environment->env->desktop_popup_default;
		}

		// Ask user what they want to do
		else
		if ((res=DoPopUpMenu(info->window,&GUI->desktop_menu->ph_Menu,0,SELECTDOWN))==(UWORD)-1 || res==MENU_DESKTOP_CANCEL)
		{
			// Cancelled	
			FreeVec(name);
			return;
		}

		// Help?
		else
		if (res&POPUP_HELPFLAG)
		{
			// Do help
			help_menu_help(res&~POPUP_HELPFLAG,0);

			// Cancelled	
			FreeVec(name);
			return;
		}

		// Get action
		else
		if (res==MENU_DESKTOP_COPY) action=DESKTOP_POPUP_COPY;
		else
		if (res==MENU_DESKTOP_MOVE) action=DESKTOP_POPUP_MOVE;
	}
		
	// Set busy pointer
	SetBusyPointer(info->window);

	// DOpus message?
	check=CheckAppMessage(msg);

	// Go through arguments
	for (arg=0;arg<msg->da_Msg.am_NumArgs;arg++)
	{
		// What operation?
		switch (action)
		{
			// Leave out?
			case DESKTOP_POPUP_LEFTOUT:

				// Get path name
				GetWBArgPath(&msg->da_Msg.am_ArgList[arg],name,512);

				// Ignore if it's an icon or a disk
				if (!(isicon(name)) && name[strlen(name)-1]!=':')
				{
					short len,perm=0;
					BackdropObject *icon;

					// Permanent?
					if (GUI->flags2&GUIF2_BENIFY)
						perm=1;

					// Get position
					x=msg->da_Msg.am_MouseX;
					y=msg->da_Msg.am_MouseY;

					// Drop from DOpus?
					if (check)
					{
						// Adjust position for icon offset
						x+=msg->da_DragOffset.x+msg->da_DropPos[arg].x;
						y+=msg->da_DragOffset.y+msg->da_DropPos[arg].y;
					}

					// Strip trailing /
					len=strlen(name)-1;
					if (name[len]=='/') name[len]=0;

					// Leave this out
					if ((icon=backdrop_leave_out(info,name,(perm)?BLOF_PERMANENT:0,x,y)))
					{
						// Position it
						backdrop_place_object(info,icon);

						// Save for permanent leftout
						if (perm) backdrop_save_leftouts(info);
						ok=1;
					}
				}
				break;

			// Copy/Move
			case DESKTOP_POPUP_COPY:
			case DESKTOP_POPUP_MOVE:
				{	
					BOOL dir=0;

					// Create ArgArray if needed
					if (!array &&
						!(array=NewArgArray())) break;

					// Get path name
					GetWBArgPath(&msg->da_Msg.am_ArgList[arg],name,512);

					// Set flag if a directory
					if (!msg->da_Msg.am_ArgList[arg].wa_Name ||
						!*msg->da_Msg.am_ArgList[arg].wa_Name) dir=1;

					// Get source path
					if (!*source_path)
					{
						char *ptr;
	
						// Copy from name
						strcpy(source_path,name);

						// Strip last part
						if ((ptr=FilePart(source_path))) *ptr=0;
					}

					// Create argument
					if ((aae=NewArgArrayEntry(array,FilePart(name))))
					{
						// Set directory flag
						if (dir) aae->ae_Flags|=AEF_DIR;

						// Set OK flag
						ok=1;
					}
				}
				break;
		}
	}

	// Successful?
	if (ok)
	{
		// Left-outs?
		if (action==DESKTOP_POPUP_LEFTOUT)
		{
			// Refresh
			backdrop_show_objects(info,BDSF_RECALC);
		}

		// Otherwise, launch function
		else
		{
			// Launch the function
			function_launch(
				FUNCTION_RUN_FUNCTION_EXTERNAL,
				(action==DESKTOP_POPUP_COPY)?def_function_copy:def_function_move,
				0,
				FUNCF_ICONS|FUNCF_RESCAN_DESKTOP|FUNCF_DRAG_DROP|FUNCF_COPY_NO_MOVE,
				0,0,
				source_path,environment->env->desktop_location,
				array,
				0,
				(Buttons *)CopyAppMessage(msg,global_memory_pool));
		}
	}

	// Otherwise, free array
	else FreeArgArray(array);

	// Free buffer
	FreeVec(name);

	// Clear busy pointer
	ClearPointer(info->window);

	// Reply the message
	ReplyAppMessage(msg);
}
Example #15
0
void DrawMessageWindow (MessageWindow* messageWindow, char *title, char **msg, int length)
{
    FcitxLightUI* lightui = messageWindow->owner;
    Display *dpy = lightui->dpy;
    int i = 0;
    if (title)
    {
        if (messageWindow->title)
            free(messageWindow->title);
        messageWindow->title = strdup(title);
    }
    else
        if (!messageWindow->title)
            return;

    title = messageWindow->title;
    FcitxLog(DEBUG, "%s", title);

    XTextProperty   tp;
    Xutf8TextListToTextProperty(dpy, &title, 1, XUTF8StringStyle, &tp);
    XSetWMName(dpy, messageWindow->window, &tp);
    XFree(tp.value);

    if (msg)
    {
        if (messageWindow->msg)
        {
            for (i =0 ;i<messageWindow->length; i++)
                free(messageWindow->msg[i]);
            free(messageWindow->msg);
        }
        messageWindow->length = length;
        messageWindow->msg = malloc(sizeof(char*) * length);
        for (i = 0; i < messageWindow->length; i++)
            messageWindow->msg[i] = strdup(msg[i]);
    }
    else
    {
        if (!messageWindow->msg)
            return;
    }
    msg = messageWindow->msg;
    length = messageWindow->length;

    if (!msg || length == 0)
        return;

    messageWindow->height = MESSAGE_WINDOW_MARGIN * 2 + length *(messageWindow->fontSize + MESSAGE_WINDOW_LINESPACE);
    messageWindow->width = 0;

    for (i = 0; i< length ;i ++)
    {
        int width;
        if (width > messageWindow->width)
            messageWindow->width = width;
    }

    messageWindow->width += MESSAGE_WINDOW_MARGIN * 2;
    XResizeWindow(dpy, messageWindow->window, messageWindow->width, messageWindow->height);

    int x, y;
    x = MESSAGE_WINDOW_MARGIN;
    y = MESSAGE_WINDOW_MARGIN;
    for (i = 0; i< length ;i ++)
    {
        y += messageWindow->fontSize + MESSAGE_WINDOW_LINESPACE;
    }

    ActivateWindow(dpy, lightui->iScreen, messageWindow->window);
}
Example #16
0
void ami_open_tree(struct tree *tree,int type)
{
	struct treeview_window *twin;
	BOOL msel = TRUE,nothl = TRUE,launchdisable=FALSE;
	static WORD gen=0;
	char *wintitle;
	char folderclosed[100],folderopen[100],item[100];

	if(tree->handle)
	{
		twin = (struct treeview_window *)tree->handle;
		WindowToFront(twin->win);
		ActivateWindow(twin->win);
		return;
	}

	twin = AllocVec(sizeof(struct treeview_window),MEMF_PRIVATE | MEMF_CLEAR);
	twin->listbrowser_list = AllocVec(sizeof(struct List),MEMF_PRIVATE | MEMF_CLEAR);

	static struct ColumnInfo columninfo[] =
	{
    	{ 80,"Name", CIF_DRAGGABLE | CIF_SORTABLE},
    	{ 20,"URL", CIF_DRAGGABLE },
//    	{ 5,"Visits", CIF_DRAGGABLE },
    	{ -1, (STRPTR)~0, -1 }
	};

	if(tree->single_selection) msel = FALSE;

	ami_get_theme_filename(&folderclosed,"theme_list_folder_closed");
	ami_get_theme_filename(&folderopen,"theme_list_folder_open");

	switch(type)
	{
		case AMI_TREE_HOTLIST:
			nothl = FALSE;
			wintitle = (char *)messages_get("Hotlist");
			ami_get_theme_filename(&item,"theme_list_bookmark");
		break;
		case AMI_TREE_COOKIES:
			nothl = TRUE;
			launchdisable=TRUE;
			wintitle = (char *)messages_get("Cookies");
			ami_get_theme_filename(&item,"theme_list_cookie");
		break;
		case AMI_TREE_HISTORY:
			nothl = TRUE;
			wintitle = (char *)messages_get("GlobalHistory");
			ami_get_theme_filename(&item,"theme_list_history");
		break;
		case AMI_TREE_SSLCERT:
			nothl = TRUE;
			wintitle = (char *)messages_get("SSLCerts");
			ami_get_theme_filename(&item,"theme_list_sslcert");
		break;
	}

	NewList(twin->listbrowser_list);

	tree->handle = (void *)twin;
	twin->tree = tree;
	ami_add_elements(twin,twin->tree->root,&gen);

	twin->objects[OID_MAIN] = WindowObject,
      	    WA_ScreenTitle,nsscreentitle,
           	WA_Title,wintitle,
           	WA_Activate, TRUE,
           	WA_DepthGadget, TRUE,
           	WA_DragBar, TRUE,
           	WA_CloseGadget, TRUE,
           	WA_SizeGadget, TRUE,
			WA_CustomScreen,scrn,
			WINDOW_SharedPort,sport,
			WINDOW_UserData,twin,
			WINDOW_IconifyGadget, TRUE,
			WINDOW_Position, WPOS_CENTERSCREEN,
			WINDOW_ParentGroup, twin->gadgets[GID_MAIN] = VGroupObject,
				LAYOUT_AddChild, twin->gadgets[GID_TREEBROWSER] = ListBrowserObject,
					GA_ID, GID_TREEBROWSER,
					GA_RelVerify, TRUE,
					GA_ReadOnly,FALSE,
					LISTBROWSER_ColumnInfo, &columninfo,
//					LISTBROWSER_ColumnTitles, TRUE,
					LISTBROWSER_Hierarchical,TRUE,
					LISTBROWSER_Editable,TRUE,
//	LISTBROWSER_TitleClickable,TRUE,
					LISTBROWSER_AutoFit, TRUE,
					LISTBROWSER_HorizontalProp, TRUE,
					LISTBROWSER_Labels, twin->listbrowser_list,
//					LISTBROWSER_MultiSelect,msel,
					LISTBROWSER_ShowSelected,TRUE,
					LISTBROWSER_ShowImage,BitMapObject,
						BITMAP_SourceFile,folderclosed,
						BITMAP_Screen,scrn,
						BITMAP_Masking,TRUE,
						BitMapEnd,
					LISTBROWSER_HideImage,BitMapObject,
						BITMAP_SourceFile,folderopen,
						BITMAP_Screen,scrn,
						BITMAP_Masking,TRUE,
						BitMapEnd,
					LISTBROWSER_LeafImage,BitMapObject,
						BITMAP_SourceFile,item,
						BITMAP_Screen,scrn,
						BITMAP_Masking,TRUE,
						BitMapEnd,
        			ListBrowserEnd,
				CHILD_NominalSize,TRUE,
				LAYOUT_AddChild, HGroupObject,
					LAYOUT_AddChild, twin->gadgets[GID_OPEN] = ButtonObject,
						GA_ID,GID_OPEN,
						GA_Text,messages_get("TreeLaunch"),
						GA_RelVerify,TRUE,
						GA_Disabled,launchdisable,
					ButtonEnd,
					LAYOUT_AddChild, twin->gadgets[GID_NEWF] = ButtonObject,
						GA_ID,GID_NEWF,
						BUTTON_AutoButton,BAG_POPDRAWER,
						GA_RelVerify,TRUE,
						GA_Disabled,nothl,
					ButtonEnd,
					LAYOUT_AddChild, twin->gadgets[GID_NEWB] = ButtonObject,
						GA_ID,GID_NEWB,
						BUTTON_AutoButton,BAG_POPFILE,
						GA_RelVerify,TRUE,
						GA_Disabled,nothl,
					ButtonEnd,
					LAYOUT_AddChild, twin->gadgets[GID_LEFT] = ButtonObject,
						GA_ID,GID_LEFT,
						BUTTON_AutoButton,BAG_LFARROW,
						GA_RelVerify,TRUE,
						GA_Disabled,nothl, //(!tree->movable),
					ButtonEnd,
					LAYOUT_AddChild, twin->gadgets[GID_UP] = ButtonObject,
						GA_ID,GID_UP,
						BUTTON_AutoButton,BAG_UPARROW,
						GA_RelVerify,TRUE,
						GA_Disabled,nothl, //(!tree->movable),
					ButtonEnd,
					LAYOUT_AddChild, twin->gadgets[GID_DOWN] = ButtonObject,
						GA_ID,GID_DOWN,
						BUTTON_AutoButton,BAG_DNARROW,
						GA_RelVerify,TRUE,
						GA_Disabled,nothl, //(!tree->movable),
					ButtonEnd,
					LAYOUT_AddChild, twin->gadgets[GID_DEL] = ButtonObject,
						GA_ID,GID_DEL,
						GA_Text,messages_get("TreeDelete"),
						GA_RelVerify,TRUE,
					ButtonEnd,
				EndGroup,
				CHILD_WeightedHeight,0,
			EndGroup,
		EndWindow;

	twin->win = (struct Window *)RA_OpenWindow(twin->objects[OID_MAIN]);

	twin->node = AddObject(window_list,AMINS_TVWINDOW);
	twin->node->objstruct = twin;
}
Example #17
0
int main(int argc, char **argv)
#endif
{
	ll_init_apr();

	// Set up llerror logging
	{
		LLError::initForApplication(".");
		LLError::setDefaultLevel(LLError::LEVEL_INFO);
//		LLError::setTagLevel("Plugin", LLError::LEVEL_DEBUG);
//		LLError::logToFile("slplugin.log");
	}

#if LL_WINDOWS
	if( strlen( lpCmdLine ) == 0 )
	{
		LL_ERRS("slplugin") << "usage: " << "SLPlugin" << " launcher_port" << LL_ENDL;
	};

	U32 port = 0;
	if(!LLStringUtil::convertToU32(lpCmdLine, port))
	{
		LL_ERRS("slplugin") << "port number must be numeric" << LL_ENDL;
	};

	// Insert our exception handler into the system so this plugin doesn't
	// display a crash message if something bad happens. The host app will
	// see the missing heartbeat and log appropriately.
	initExceptionHandler();
#elif LL_DARWIN || LL_LINUX
	if(argc < 2)
	{
		LL_ERRS("slplugin") << "usage: " << argv[0] << " launcher_port" << LL_ENDL;
	}

	U32 port = 0;
	if(!LLStringUtil::convertToU32(argv[1], port))
	{
		LL_ERRS("slplugin") << "port number must be numeric" << LL_ENDL;
	}

	// Catch signals that most kinds of crashes will generate, and exit cleanly so the system crash dialog isn't shown.
	signal(SIGILL, &crash_handler);		// illegal instruction
# if LL_DARWIN
	signal(SIGEMT, &crash_handler);		// emulate instruction executed
# endif // LL_DARWIN
	signal(SIGFPE, &crash_handler);		// floating-point exception
	signal(SIGBUS, &crash_handler);		// bus error
	signal(SIGSEGV, &crash_handler);	// segmentation violation
	signal(SIGSYS, &crash_handler);		// non-existent system call invoked
#endif

#if LL_DARWIN
	setupCocoa();
	createAutoReleasePool();
#endif

	LLPluginProcessChild *plugin = new LLPluginProcessChild();

	plugin->init(port);

#if LL_DARWIN
		deleteAutoReleasePool();
#endif

	LLTimer timer;
	timer.start();

#if LL_WINDOWS
	checkExceptionHandler();
#endif

#if LL_DARWIN
	// If the plugin opens a new window (such as the Flash plugin's fullscreen player), we may need to bring this plugin process to the foreground.
	// Use this to track the current frontmost window and bring this process to the front if it changes.
	WindowRef front_window = NULL;
	WindowGroupRef layer_group = NULL;
	int window_hack_state = 0;
	CreateWindowGroup(kWindowGroupAttrFixedLevel, &layer_group);
	if(layer_group)
	{
		// Start out with a window layer that's way out in front (fixes the problem with the menubar not getting hidden on first switch to fullscreen youtube)
		SetWindowGroupName(layer_group, CFSTR("SLPlugin Layer"));
		SetWindowGroupLevel(layer_group, kCGOverlayWindowLevel);		
	}
#endif

#if LL_DARWIN
	EventTargetRef event_target = GetEventDispatcherTarget();
#endif
	while(!plugin->isDone())
	{
#if LL_DARWIN
		createAutoReleasePool();
#endif
		timer.reset();
		plugin->idle();
#if LL_DARWIN
		{
			// Some plugins (webkit at least) will want an event loop.  This qualifies.
			EventRef event;
			if(ReceiveNextEvent(0, 0, kEventDurationNoWait, true, &event) == noErr)
			{
				SendEventToEventTarget (event, event_target);
				ReleaseEvent(event);
			}
			
			// Check for a change in this process's frontmost window.
			if(FrontWindow() != front_window)
			{
				ProcessSerialNumber self = { 0, kCurrentProcess };
				ProcessSerialNumber parent = { 0, kNoProcess };
				ProcessSerialNumber front = { 0, kNoProcess };
				Boolean this_is_front_process = false;
				Boolean parent_is_front_process = false;
				{
					// Get this process's parent
					ProcessInfoRec info;
					info.processInfoLength = sizeof(ProcessInfoRec);
					info.processName = NULL;
					info.processAppSpec = NULL;
					if(GetProcessInformation( &self, &info ) == noErr)
					{
						parent = info.processLauncher;
					}
					
					// and figure out whether this process or its parent are currently frontmost
					if(GetFrontProcess(&front) == noErr)
					{
						(void) SameProcess(&self, &front, &this_is_front_process);
						(void) SameProcess(&parent, &front, &parent_is_front_process);
					}
				}
								
				if((FrontWindow() != NULL) && (front_window == NULL))
				{
					// Opening the first window
					
					if(window_hack_state == 0)
					{
						// Next time through the event loop, lower the window group layer
						window_hack_state = 1;
					}

					if(layer_group)
					{
						SetWindowGroup(FrontWindow(), layer_group);
					}
					
					if(parent_is_front_process)
					{
						// Bring this process's windows to the front.
						(void) SetFrontProcess( &self );
					}

					ActivateWindow(FrontWindow(), true);					
				}
				else if((FrontWindow() == NULL) && (front_window != NULL))
				{
					// Closing the last window
					
					if(this_is_front_process)
					{
						// Try to bring this process's parent to the front
						(void) SetFrontProcess(&parent);
					}
				}
				else if(window_hack_state == 1)
				{
					if(layer_group)
					{
						// Set the window group level back to something less extreme
						SetWindowGroupLevel(layer_group, kCGNormalWindowLevel);
					}
					window_hack_state = 2;
				}

				front_window = FrontWindow();

			}
		}
#endif
		F64 elapsed = timer.getElapsedTimeF64();
		F64 remaining = plugin->getSleepTime() - elapsed;

		if(remaining <= 0.0f)
		{
			// We've already used our full allotment.
//			LL_INFOS("slplugin") << "elapsed = " << elapsed * 1000.0f << " ms, remaining = " << remaining * 1000.0f << " ms, not sleeping" << LL_ENDL;

			// Still need to service the network...
			plugin->pump();
		}
		else
		{

//			LL_INFOS("slplugin") << "elapsed = " << elapsed * 1000.0f << " ms, remaining = " << remaining * 1000.0f << " ms, sleeping for " << remaining * 1000.0f << " ms" << LL_ENDL;
//			timer.reset();

			// This also services the network as needed.
			plugin->sleep(remaining);

//			LL_INFOS("slplugin") << "slept for "<< timer.getElapsedTimeF64() * 1000.0f << " ms" <<  LL_ENDL;
		}

#if LL_WINDOWS
	// More agressive checking of interfering exception handlers.
	// Doesn't appear to be required so far - even for plugins
	// that do crash with a single call to the intercept
	// exception handler such as QuickTime.
	//checkExceptionHandler();
#endif

#if LL_DARWIN
		deleteAutoReleasePool();
#endif
	}

	delete plugin;

	ll_cleanup_apr();

	return 0;
}
void InitializeWindowAndInput(const char* windowTitle, int width, int height)
{
	InitGlobalInput();
	GenerateWindow(Input_WndProc, windowTitle, width, height);
	ActivateWindow();
}
// Get search data
static int search_get_data(
	FunctionHandle *handle,
	SearchData *data)
{
	NewConfigWindow new_win;
	struct Window *window;
	ObjectList *objlist;
	Lister *lister;
	short cancel=1;

	// Fill out new window
	if ((lister=function_lister_current(&handle->source_paths)))
	{
		new_win.parent=lister->window;
		new_win.flags=0;
	}
	else
	{
		new_win.parent=GUI->screen_pointer;
		new_win.flags=WINDOW_SCREEN_PARENT;
	}
	new_win.dims=&search_window;
	new_win.title=GetString(&locale,MSG_ENTER_SEARCH_STRING);
	new_win.locale=&locale;
	new_win.port=0;
	new_win.flags|=WINDOW_NO_CLOSE|WINDOW_VISITOR|WINDOW_AUTO_KEYS|WINDOW_REQ_FILL;
	new_win.font=0;

	// Open window
	if (!(window=OpenConfigWindow(&new_win)) ||
		!(objlist=AddObjectList(window,search_objects)))
	{
		CloseConfigWindow(window);
		return 0;
	}

	// Initial settings
	SetGadgetValue(objlist,GAD_SEARCH_TEXT,(ULONG)data->search_text);
	SetGadgetValue(objlist,GAD_SEARCH_CASE,data->search_flags&SEARCH_NOCASE);
	SetGadgetValue(objlist,GAD_SEARCH_WILD,data->search_flags&SEARCH_WILDCARD);
	SetGadgetValue(objlist,GAD_SEARCH_ONLYWORD,data->search_flags&SEARCH_ONLYWORDS);
	SetGadgetValue(objlist,GAD_SEARCH_RESULT,data->search_result);

	// Activate text field
	ActivateStrGad(GADGET(GetObject(objlist,GAD_SEARCH_TEXT)),window);

	// Event loop
	FOREVER
	{
		struct IntuiMessage *msg;
		BOOL break_flag=0;

		// Check for abort
		if (function_check_abort(handle))
			break;

		// Activate?
		if (handle->flags2&FUNCF_ACTIVATE_ME)
		{
			ActivateWindow(window);
			WindowToFront(window);
			handle->flags2&=~FUNCF_ACTIVATE_ME;
		}

		// Any Intuition messages?
		while ((msg=GetWindowMsg(window->UserPort)))
		{
			struct IntuiMessage copy_msg;

			// Copy message and reply
			copy_msg=*msg;
			ReplyWindowMsg(msg);

			// Gadget?
			if (copy_msg.Class==IDCMP_GADGETUP)
			{
				UWORD gadgetid;

				// Get gadget id
				gadgetid=((struct Gadget *)copy_msg.IAddress)->GadgetID;

				// Look at gadget ID
				switch (gadgetid)
				{
					// Okay
					case GAD_SEARCH_TEXT:
					case GAD_SEARCH_OKAY:

						// Store flags
						data->search_flags=0;
						if (GetGadgetValue(objlist,GAD_SEARCH_CASE))
							data->search_flags|=SEARCH_NOCASE;
						if (GetGadgetValue(objlist,GAD_SEARCH_WILD))
							data->search_flags|=SEARCH_WILDCARD;
						if (GetGadgetValue(objlist,GAD_SEARCH_ONLYWORD))
							data->search_flags|=SEARCH_ONLYWORDS;
						data->search_result=GetGadgetValue(objlist,GAD_SEARCH_RESULT);

						// Get search text
						strcpy(data->search_text,(char *)GetGadgetValue(objlist,GAD_SEARCH_TEXT));
						cancel=0;

					// Cancel
					case GAD_SEARCH_CANCEL:
						break_flag=1;
						break;
				}
			}
		}

		// Check break flag
		if (break_flag) break;

		// Wait for an event
		Wait(1<<window->UserPort->mp_SigBit|1<<handle->ipc->command_port->mp_SigBit);
	}

	// Close window
	CloseConfigWindow(window);

	// Return
	return !cancel;
}
void FiletypeEditor(void)
{
	filetype_ed_data *data=0;
	IPCData *ipc;
	short success=0,pending_quit=0;
	BOOL change_flag=0;

	// Do startup
	if (!(ipc=Local_IPC_ProcStartup((ULONG *)&data, (APTR)&_filetypeed_init)))
		return;

	// Create App stuff
	if ((data->app_port=CreateMsgPort()))
	{
		data->app_window=AddAppWindowA(0,0,data->window,data->app_port,0);
	}

	// Get icon image
	if (data->type->icon_path)
	{
#ifdef USE_DRAWICONSTATE
		{
			char *path_copy;
			data->icon_image=NULL;
			if ((path_copy=AllocMemH(0,strlen(data->type->icon_path)+1)))
			{
				// icon_path is guaranteed to have a .info at the end
				stccpy(path_copy,data->type->icon_path,strlen(data->type->icon_path)-4);
				data->icon_image=GetCachedDiskObject(path_copy,0);
				FreeMemH(path_copy);
			}
		}
#else
		data->icon_image=OpenImage(data->type->icon_path,0);
#endif
		// Show icon image
		filetypeed_show_icon(data);
	}

	// Launch class editor immediately?
	if (data->edit_flag) filetypeed_edit_definition(data);

	// Message loop
	FOREVER
	{
		IPCMessage *msg;
		struct IntuiMessage *imsg;
		short break_flag=0;

		// Check drag
		if (config_drag_check(&data->drag))
		{
			// End drag
			filetypeed_end_drag(data,0);
		}

		// Task message?
		while ((msg=(IPCMessage *)GetMsg(ipc->command_port)))
		{
			switch (msg->command)
			{
				// Close message?
				case IPC_QUIT:
					if (!pending_quit)
					{
						success=msg->flags;
						break_flag=1;
					}
					break;


				// Activate
				case IPC_ACTIVATE:
					if (data->window)
					{
						WindowToFront(data->window);
						ActivateWindow(data->window);
					}
					break;


				// Editor saying goodbye
				case IPC_GOODBYE:
					{
						ULONG which;

						// What's just gone?
						which=IPC_GetGoodbye(msg);

						// Class editor?
						if (which==(ULONG)-1) data->class_editor=0;

						// Icon menu editor?
						else
						if (which>15)
						{
							Att_Node *node;

							// Go through icon list
							for (node=(Att_Node *)data->icon_list->list.lh_Head;
								node->node.ln_Succ;
								node=(Att_Node *)node->node.ln_Succ)
							{
								// Match function
								if (((func_node *)node->data)->func==(Cfg_Function *)which)
								{
									// Clear editor pointer
									((func_node *)node->data)->editor=0;

									// Check for invalid function
									if (filetypeed_check_iconmenu(data,node,FALSE))
										change_flag=1;
									break;
								}
							}
						}

						// Normal filetype editor
						else data->editor[which]=0;
					}
					break;


				// Editor returning a function
				case FUNCTIONEDIT_RETURN:
					{
						short ret;

						if ((ret=filetypeed_receive_edit(
							data,
							(FunctionReturn *)msg->data)))
						{
							change_flag=1;
							filetypeed_update_actions(data);
							if (ret==2) filetypeed_update_iconmenu(data);
						}
					}
					break;


				// Class editor returning
				case CLASSEDIT_RETURN:
					filetypeed_receive_class(data,(Cfg_Filetype *)msg->data);
					change_flag=1;
					break;


				// Get a copy of a button
				case BUTTONEDIT_CLIP_BUTTON:

					// Handle this button
					if (filetypeed_get_button(data,(Cfg_Button *)msg->data,(Point *)msg->data_free))
						change_flag=1;
					break;
			}

			// Reply the message
			IPC_Reply(msg);
		}

		// Intuimessage
		if (data->window)
		{
			while ((imsg=GetWindowMsg(data->window->UserPort)))
			{
				struct IntuiMessage msg_copy;
				struct Gadget *gadget;
				struct TagItem *tags;

				// Copy message
				msg_copy=*imsg;

				// Don't reply to IDCMPUPDATE messages just yet
				if (imsg->Class!=IDCMP_IDCMPUPDATE)
				{
					ReplyWindowMsg(imsg);
					imsg=0;
				}

				// Get gadget and tag pointers
				gadget=(struct Gadget *)msg_copy.IAddress;
				tags=(struct TagItem *)gadget;

				// Look at message
				switch (msg_copy.Class)
				{
					// Close window
					case IDCMP_CLOSEWINDOW:
						if (!pending_quit) break_flag=1;
						break;


					// Gadget
					case IDCMP_GADGETUP:
						switch (gadget->GadgetID)
						{
							// Use
							case GAD_FILETYPEED_USE:
								success=1;

							// Cancel
							case GAD_FILETYPEED_CANCEL:
								if (!pending_quit) break_flag=1;
								break;


							// Select a function
							case GAD_FILETYPEED_ACTION_LIST:
								{
									Att_Node *node;

									// Get selected node
									if (!(node=Att_FindNode(data->action_list,msg_copy.Code)))
										break;

									// Enable edit action button
									DisableObject(data->objlist,GAD_FILETYPES_EDIT_ACTION,FALSE);

									// Double-click?
									if (!(DoubleClick(data->last_sec,data->last_mic,msg_copy.Seconds,msg_copy.Micros)) ||
										node!=data->last_sel)
									{
										data->last_sec=msg_copy.Seconds;
										data->last_mic=msg_copy.Micros;
										data->last_sel=node;
										data->last_icon=0;
										break;
									}
								}

								// Fall through

							case GAD_FILETYPES_EDIT_ACTION:

								// No current selection?
								if (!data->last_sel) break;

								// Is editor already up for this action?	
								if (data->editor[data->last_sel->data])
									IPC_Command(data->editor[data->last_sel->data],IPC_ACTIVATE,0,0,0,0);

								// Need to launch editor
								else filetypeed_edit_action(data,data->last_sel->data,data->last_sel->node.ln_Name);
								break;


							// Delete action
							case GAD_FILETYPES_DEL_ACTION:

								// No current selection?
								if (!data->last_sel) break;

								// Is editor up for this action?	
								if (data->editor[data->last_sel->data])
									IPC_Command(data->editor[data->last_sel->data],IPC_QUIT,0,0,0,0);

								// Delete it
								if (filetypeed_del_action(data,data->last_sel->data))
									change_flag=1;
								break;


							// Edit filetype definition
							case GAD_FILETYPEED_EDIT_CLASS:

								// Is class editor already up for this action?	
								if (data->class_editor)
									IPC_Command(data->class_editor,IPC_ACTIVATE,0,0,0,0);

								// Need to launch editor
								else filetypeed_edit_definition(data);
								break;


							// Select icon
							case GAD_FILETYPEED_SELECT_ICON:
								if (filetypeed_pick_icon(data))
									change_flag=1;
								break;


							// Add to icon menu
							case GAD_FILETYPES_ADD_ICON_MENU:
								filetypeed_add_iconmenu(data);
								break;


							// Select an icon menu
							case GAD_FILETYPES_ICON_MENU:
								{
									Att_Node *last=data->last_icon;

									// Handle selection
									if (!(filetypeed_sel_icon(data,msg_copy.Code))) break;

									// Double-click?
									if (data->last_icon!=last ||
										!(DoubleClick(
											data->last_sec,
											data->last_mic,
											msg_copy.Seconds,
											msg_copy.Micros)))
									{
										data->last_sec=msg_copy.Seconds;
										data->last_mic=msg_copy.Micros;
										data->last_sel=0;
										break;
									}
								}

								// Fall through

							case GAD_FILETYPES_EDIT_ICON_MENU:

								// No current selection?
								if (!data->last_icon) break;

								// Edit it
								filetypeed_edit_iconmenu(data,data->last_icon);
								break;


							// Delete from icon menu
							case GAD_FILETYPES_DEL_ICON_MENU:

								// No current selection?
								if (!data->last_icon) break;

								// Delete function
								if (filetypeed_check_iconmenu(data,data->last_icon,TRUE))
									change_flag=1;
								break;
						}
						break;


					// BOOPSI message
					case IDCMP_IDCMPUPDATE:
						{
							short item;

							// Icon list?
							if (GetTagData(GA_ID,0,tags)!=GAD_FILETYPES_ICON_MENU) break;

							// Get item
							if ((item=GetTagData(DLV_DragNotify,-1,tags))!=-1)
							{
								// Handle selection
								filetypeed_sel_icon(data,item);

								// Start the drag
								config_drag_start(&data->drag,data->icon_list,item,tags,TRUE);
							}
						}
						break;


					// Ticks
					case IDCMP_INTUITICKS:
						++data->drag.tick_count;
						break;


					// Mouse move
					case IDCMP_MOUSEMOVE:

						// Handle drag move
						config_drag_move(&data->drag);
						break;


					// Mouse buttons
					case IDCMP_MOUSEBUTTONS:

						// Valid drag info?
						if (data->drag.drag)
						{
							short ok=-1;

							// Dropped ok?
							if (msg_copy.Code==SELECTUP)
							{
								// Remember last position
								data->drag.drag_x=data->window->WScreen->MouseX;
								data->drag.drag_y=data->window->WScreen->MouseY;
								ok=1;
							}

							// Aborted
							else
							if (msg_copy.Code==MENUDOWN) ok=0;

							// End drag?
							if (ok!=-1 && filetypeed_end_drag(data,ok)) change_flag=1;
						}
						break;


					// Key press
					case IDCMP_RAWKEY:

						// Help?
						if (msg_copy.Code==0x5f &&
							!(msg_copy.Qualifier&VALID_QUALIFIERS))
						{
							// Set busy pointer
							SetWindowBusy(data->window);

							// Send help command
							IPC_Command(data->func_startup.main_owner,IPC_HELP,(1<<31),"File Type Editor",0,REPLY_NO_PORT);

							// Clear busy pointer
							ClearWindowBusy(data->window);
						}
						break;
				}

				// Reply to outstanding messages
				if (imsg) ReplyWindowMsg(imsg);
			}

			// Check break flag
			if (break_flag || pending_quit)
			{
				// See if all the editors are gone
				if (IsListEmpty(&data->proc_list.list))
					break;

				// Send quit?
				if (break_flag)
				{
					IPC_ListQuit(&data->proc_list,0,success,FALSE);
					SetWindowBusy(data->window);
				}
				pending_quit=1;
			}
		}

		// AppMessage
		if (data->app_window)
		{
			struct AppMessage *msg;

			while ((msg=(struct AppMessage *)GetMsg(data->app_port)))
			{
				// Got an argument?
				if (msg->am_NumArgs>0)
				{
					char name[256];
					short len;
					APTR image;

					// Get full name
					NameFromLock(msg->am_ArgList[0].wa_Lock,name,256);
					if (msg->am_ArgList[0].wa_Name &&
						*msg->am_ArgList[0].wa_Name)
						AddPart(name,msg->am_ArgList[0].wa_Name,256);

					// Add .info
					if ((len=strlen(name))<6 ||
						stricmp(name+len-5,".info")!=0) strcat(name,".info");

					// Try to get image
#ifdef USE_DRAWICONSTATE
					{
						char *path_copy;
						image=NULL;
						if ((path_copy=AllocMemH(0,strlen(name)+1)))
						{
							// icon_path is guaranteed to have a .info at the end
							stccpy(path_copy,name,strlen(name)-4);
							image=GetCachedDiskObject(path_copy,0);
							FreeMemH(path_copy);
						}
					}
#else
					image=OpenImage(name,0);
#endif

					if (image)
					{
						// Store path
						FreeMemH(data->type->icon_path);
						if ((data->type->icon_path=AllocMemH(0,strlen(name)+1)))
							strcpy(data->type->icon_path,name);

						// Free existing image
#ifdef USE_DRAWICONSTATE
						FreeCachedDiskObject(data->icon_image);
#else
						CloseImage(data->icon_image);
#endif
						data->icon_image=image;

						// Show new image
						filetypeed_show_icon(data);
						change_flag=1;
					}
				}

				// Reply message
				ReplyMsg((struct Message *)msg);
			}
		}

		Wait(1<<ipc->command_port->mp_SigBit|
			1<<data->drag.timer->port->mp_SigBit|
			((data->window)?(1<<data->window->UserPort->mp_SigBit):0)|
			((data->app_window)?(1<<data->app_port->mp_SigBit):0));
	}

	// End any drag in progress
	filetypeed_end_drag(data,0);

	// Need to send button back?
	if (success==1 && change_flag)
	{
		if (IPC_Command(
			data->owner_ipc,
			FILETYPEEDIT_RETURN,
			(ULONG)data->type,
			data->node,
			0,
			REPLY_NO_PORT))
		{
			data->node=0;
		}
	}

	// Free edit filetype
	FreeFiletype(data->type);

	// Remove AppWindow
	RemoveAppWindow(data->app_window);

	// Close window
	CloseConfigWindow(data->window);

	// Close app port
	if (data->app_port)
	{
		struct Message *msg;
		while ((msg=GetMsg(data->app_port)))
			ReplyMsg(msg);
		DeleteMsgPort(data->app_port);
	}

	// Say goodbye
	IPC_Goodbye(ipc,data->owner_ipc,(success==-1)?0:(ULONG)data->node);

	// Free icon image
#ifdef USE_DRAWICONSTATE
	FreeCachedDiskObject(data->icon_image);
#else
	CloseImage(data->icon_image);
#endif

	// Close timer
	FreeTimer(data->drag.timer);

	// Free data
	IPC_Free(ipc);
	Att_RemList(data->action_list,0);
	Att_RemList(data->icon_list,REMLIST_FREEDATA);
	FreeVec(data);
}
Example #21
0
short LIBFUNC L_DoSimpleRequest(
	REG(a0, struct Window *parent),
	REG(a1, struct DOpusSimpleRequest *simple),
	REG(a6, struct Library *libbase))
{
	APTR memory;
	simplereq_data *data;
	UWORD gadgetid=0;

	#ifdef __amigaos4__
	libbase = (struct Library *)dopuslibbase_global;
	#endif

	// Allocate memory handle
	if (!(memory=L_NewMemHandle(0,0,MEMF_CLEAR)))
		return 1;

	// Allocate data
	if (!(data=(simplereq_data *)L_AllocMemH(memory,sizeof(simplereq_data))))
	{
		L_FreeMemHandle(memory);
		return 1;
	}

	// Initialise
	data->simple=simple;
	data->parent=parent;
	data->string_buffer=simple->string_buffer;
	data->gadgets=simple->gadgets;
	data->libbase=(struct MyLibrary *)libbase;
	data->signal=-1;
	data->memory=memory;

	// Center window; over mouse?
	if (simple->flags&SRF_MOUSE_POS)
	{
		data->req_dims.char_dim.Left=POS_MOUSE_CENTER;
		data->req_dims.char_dim.Top=POS_MOUSE_CENTER;
	}

	// Over parent
	else
	{
		data->req_dims.char_dim.Left=POS_CENTER;
		data->req_dims.char_dim.Top=POS_CENTER;
	}

	// Construct requester
	if (!(simple_build(data)))
	{
		// Failed
		L_FreeMemHandle(memory);
		return 1;
	}

	// IPC port supplied?
	if (simple->flags&SRF_IPC && simple->ipc)
	{
		data->ipc=simple->ipc;
		data->waitbits=1<<data->ipc->command_port->mp_SigBit;
	}

	// Signal supplied?
	else
	if (simple->flags&SRF_SIGNAL)
	{
		data->signal=(short)simple->ipc;
		data->waitbits=1<<data->signal;
	}

	// Otherwise
	else
	{
		data->waitbits=IPCSIG_QUIT;
		SetSignal(0,IPCSIG_QUIT);
	}

	// Open requester
	if (_simplereq_open(data,parent))
	{
		// Wait on requester
		FOREVER
		{
			struct IntuiMessage *msg;
			IPCMessage *imsg;
			short break_flag=0;
			ULONG waitres;

			// IPC message?
			if (data->ipc)
			{
				while ((imsg=(IPCMessage *)GetMsg(data->ipc->command_port)))
				{
					if (imsg->command==IPC_HIDE)
						_simplereq_close(data);
					else
					if (imsg->command==IPC_SHOW)
					{
						if (!(_simplereq_open(data,imsg->data)))
							break_flag=1;
					}
					else
					if (imsg->command==IPC_ACTIVATE)
					{
						if (data->window)
						{
							WindowToFront(data->window);
							ActivateWindow(data->window);
						}
					}
					else
					if (imsg->command==IPC_QUIT || imsg->command==IPC_ABORT)
					{
						break_flag=1;
						gadgetid=(UWORD)-1;
					}
					L_IPC_Reply(imsg);
				}
			}

			// Intuition message?
			if (data->window)
			{
				while ((msg=L_GetWindowMsg(data->window->UserPort, (APTR)libbase)))
				{
					struct IntuiMessage copy_msg;

					// Copy message and reply
					copy_msg=*msg;
					L_ReplyWindowMsg(msg);

					// Check message type
					if (copy_msg.Class==IDCMP_GADGETUP)
					{
						// Get gadget ID
						gadgetid=((struct Gadget *)copy_msg.IAddress)->GadgetID;

						// Checkbox?
						if (gadgetid==GAD_CHECK_ID)
						{
							// Store value
							if (simple->check_ptr) *simple->check_ptr=copy_msg.Code;
						}

						// Tab on a string gadget?
						else
						if (gadgetid==GAD_STRING2_ID ||
							(gadgetid==GAD_STRING_ID &&
								(copy_msg.Code==0x9 ||
								copy_msg.Code==0x45 ||
								copy_msg.Qualifier&(IEQUALIFIER_LSHIFT|IEQUALIFIER_RSHIFT))))
							continue;

						// Popup gadget?
						else
						if (gadgetid==GAD_POPUP_ID)
						{
							char buf[400],file[40],*ptr;
							struct TagItem tags[4];

							// Get initial path and file
							strcpy(buf,(char *)L_GetGadgetValue(data->objlist,GAD_STRING_ID,data->libbase));
							if ((ptr=FilePart(buf)))
							{
								stccpy(file,ptr,40);
								*ptr=0;
							}
							else file[0]=0;

							// Initialise tags
							tags[0].ti_Tag=ASLFR_Window;
							tags[0].ti_Data=(ULONG)data->window;
							tags[1].ti_Tag=ASLFR_InitialFile;
							tags[1].ti_Data=(ULONG)file;
							tags[2].ti_Tag=ASLFR_InitialDrawer;
							tags[2].ti_Data=(ULONG)buf;
							tags[3].ti_Tag=TAG_END;

							// Show requester
							if (simple->filereq &&
								AslRequest(simple->filereq,tags))
							{
								// Build new path
								strcpy(buf,((struct FileRequester *)simple->filereq)->fr_Drawer);
								AddPart(buf,((struct FileRequester *)simple->filereq)->fr_File,400);

								// Show in string gadget
								L_SetGadgetValue(data->objlist,GAD_STRING_ID,(long)buf);
								L_ActivateStrGad(GADGET(L_GetObject(data->objlist,GAD_STRING_ID)),data->window);
							}
							continue;
						}

						// Set break flag
						else break_flag=1;
					}

					// Key press
					else
					if (copy_msg.Class==IDCMP_VANILLAKEY)
					{
						// Y = yes
						if (copy_msg.Code=='y' || copy_msg.Code=='Y')
						{
							gadgetid=1;
							break_flag=1;
						}

						// N = no
						else
						if (copy_msg.Code=='n' || copy_msg.Code=='N')
						{
							gadgetid=0;
							break_flag=1;
						}
					}
				}
			}

			// Check break flag
			if (break_flag) break;

			// Wait for a message
			waitres=Wait(data->waitbits|
						((data->window)?(1<<data->window->UserPort->mp_SigBit):0));

			// Quit?
			if (waitres&IPCSIG_QUIT)
			{
				gadgetid=0;
				break;
			}

			// Signal?
			else
			if (data->signal!=-1 && (waitres&(1<<data->signal)))
			{
				gadgetid=(UWORD)-5;
				break;
			}
		}
	}

	// Close requester
	_simplereq_close(data);

	// Free memory
	L_FreeMemHandle(memory);

	// Return gadget code
	return gadgetid;
}
Example #22
0
/**************************************************************************
 *	Update functions
 */
void SystemUpdate(void)
{
	if (isNotepadCreated == FALSE)
		return;

	OutputDebugString(_T("SystemUpdate\n"));

	UINT		oldSC		= currentSC;
	UINT		newDocCnt	= 0;
	TCHAR		pszNewPath[MAX_PATH];

	/* update open files */
	UpdateCurrentHScintilla();
	::SendMessage(nppData._nppHandle, NPPM_GETFULLCURRENTPATH, 0, (LPARAM)pszNewPath);
	INT newOpenDoc1 = (INT)::SendMessage(nppData._nppHandle, NPPM_GETCURRENTDOCINDEX, 0, MAIN_VIEW);
	INT newOpenDoc2 = (INT)::SendMessage(nppData._nppHandle, NPPM_GETCURRENTDOCINDEX, 0, SUB_VIEW);

	if ((newOpenDoc1 != openDoc1) || (newOpenDoc2 != openDoc2) || 
		(_tcscmp(pszNewPath, currentPath) != 0) || (oldSC != currentSC))
	{
		/* set new file */
		_tcscpy(currentPath, pszNewPath);
		openDoc1 = newOpenDoc1;
		openDoc2 = newOpenDoc2;

		INT			i = 0;
		INT			docCnt1;
		INT			docCnt2;
		LPCTSTR		*fileNames1;
		LPCTSTR		*fileNames2;
		BOOL		isAllocOk = TRUE;
		
		/* update doc information */
		docCnt1		= (INT)::SendMessage(nppData._nppHandle, NPPM_GETNBOPENFILES, 0, (LPARAM)PRIMARY_VIEW);
		docCnt2		= (INT)::SendMessage(nppData._nppHandle, NPPM_GETNBOPENFILES, 0, (LPARAM)SECOND_VIEW);
		fileNames1	= (LPCTSTR*)new LPTSTR[docCnt1];
		fileNames2	= (LPCTSTR*)new LPTSTR[docCnt2];

		if ((fileNames1 != NULL) && (fileNames2 != NULL))
		{
			for (i = 0; (i < docCnt1) && (isAllocOk == TRUE); i++) {
				fileNames1[i] = (LPTSTR)new TCHAR[MAX_PATH];
				if (fileNames1[i] == NULL)
					isAllocOk = FALSE;
			}
			for (i = 0; (i < docCnt2) && (isAllocOk == TRUE); i++) {
				fileNames2[i] = (LPTSTR)new TCHAR[MAX_PATH];
				if (fileNames2[i] == NULL)
					isAllocOk = FALSE;
			}

			if (isAllocOk == TRUE)
			{
				::SendMessage(nppData._nppHandle, NPPM_GETOPENFILENAMESPRIMARY, (WPARAM)fileNames1, (LPARAM)docCnt1);
				hexEdit1.UpdateDocs(fileNames1, docCnt1, openDoc1);

				::SendMessage(nppData._nppHandle, NPPM_GETOPENFILENAMESSECOND, (WPARAM)fileNames2, (LPARAM)docCnt2);
				hexEdit2.UpdateDocs(fileNames2, docCnt2, openDoc2);

				/* update edit */
				if (currentSC == MAIN_VIEW)
					pCurHexEdit = &hexEdit1;
				else
					pCurHexEdit = &hexEdit2;

				ActivateWindow();
				setMenu();
			}

			if (fileNames1 != NULL)
			{
				for (i = 0; i < docCnt1; i++)
					if (fileNames1[i] != NULL)
						delete [] fileNames1[i];
				delete [] fileNames1;
			}
			if (fileNames2 != NULL)
			{
				for (i = 0; i < docCnt2; i++)
					if (fileNames2[i] != NULL)
						delete [] fileNames2[i];
				delete [] fileNames2;
			}
		}
	}
	DialogUpdate();
}
Example #23
0
BOOL ami_search_event(void)
{
	/* return TRUE if window destroyed */
	ULONG result;
	uint16 code;
	search_flags_t flags;

	while((result = RA_HandleInput(fwin->objects[OID_MAIN],&code)) != WMHI_LASTMSG)
	{
       	switch(result & WMHI_CLASSMASK) // class
	{
	case WMHI_GADGETUP:
		switch(result & WMHI_GADGETMASK)
		{
			case GID_SEARCHSTRING:
				browser_window_search_clear(fwin->gwin->bw);
						
				RefreshSetGadgetAttrs((struct Gadget *)fwin->objects[GID_PREV],
					fwin->win, NULL,
					GA_Disabled, FALSE,
					TAG_DONE);

				RefreshSetGadgetAttrs((struct Gadget *)fwin->objects[GID_NEXT],
					fwin->win, NULL,
					GA_Disabled, FALSE,
					TAG_DONE);
	
				/* fall through */

			case GID_NEXT:
				search_insert = true;
				flags = SEARCH_FLAG_FORWARDS |
					ami_search_flags();
				browser_window_search(
						fwin->gwin->bw,
						NULL,
						flags, ami_search_string());
				ActivateWindow(fwin->gwin->shared->win);
			break;

			case GID_PREV:
				search_insert = true;
				flags = ~SEARCH_FLAG_FORWARDS &
					ami_search_flags();
				browser_window_search(
						fwin->gwin->bw,
						NULL,
						flags, ami_search_string());
				ActivateWindow(fwin->gwin->shared->win);
			break;
		}
		break;

	case WMHI_CLOSEWINDOW:
		ami_search_close();
		return TRUE;
		break;
	}
	}
	return FALSE;
}
void FunctionEditor(void)
{
	struct IntuiMessage *gmsg,msg;
	int break_flag=0;
	UWORD gadgetid=0;
	ULONG waitbits;
	FuncEdData *data;
	IPCData *ipc;
	NewConfigWindow newwin;
	FunctionStartup *startup=0;
	IPCMessage *submsg;
	int success=0;
	BOOL open_window=1;
	BPTR lock;
	ConfigWindow windims;

	// Do startup
	if (!(ipc=Local_IPC_ProcStartup((ULONG *)&startup, (APTR)&funced_init)))
	{
		funced_cleanup(startup->data);
		return;
	}

	// Get data pointer
	data=startup->data;

	// Lock RAM: and CD to it
	if ((lock=Lock("ram:",ACCESS_READ)))
		lock=CurrentDir(lock);

	// Copy dimensions
	if (startup->flags&FUNCEDF_CENTER)
		windims=_function_editor_window_center;
	else
	if (startup->flags&FUNCEDF_LABEL)
		windims=_function_editor_label_window;
	else
		windims=_function_editor_window;

	// Fill in new window
	newwin.parent=startup->window;
	newwin.dims=&windims;
	newwin.title=(startup->title[0])?startup->title:(char *)GetString(startup->locale,MSG_FUNCED_TITLE);
	newwin.locale=startup->locale;
	newwin.port=0;
	newwin.flags=WINDOW_VISITOR|WINDOW_AUTO_KEYS|WINDOW_REQ_FILL;//|WINDOW_SIZE_BOTTOM;
	newwin.font=0;

	// Build flag list
	funced_build_flaglist(data);
	waitbits=1<<ipc->command_port->mp_SigBit|1<<data->drag.timer->port->mp_SigBit;

	// Event loop
	FOREVER
	{
		// Check drag
		if (config_drag_check(&data->drag))
		{
			// End drag
			functioned_end_drag(data,0);
		}

		// Task message?
		while ((submsg=(IPCMessage *)GetMsg(ipc->command_port)))
		{
			// Close message?
			if (submsg->command==IPC_QUIT)
			{
				// Keep changes?
				success=submsg->flags;

				// Set break flag
				break_flag=1;
			}

			// Activate
			else
			if (submsg->command==IPC_ACTIVATE && data->window)
			{
				WindowToFront(data->window);
				ActivateWindow(data->window);
			}

			// Hide
			else
			if (submsg->command==IPC_HIDE && data->window)
			{
				// Store changes in function
				funced_store_edits(data);

				// End any drag in progress
				functioned_end_drag(data,0);

				// Remove AppWindow
				RemoveAppWindow(data->appwindow);
				data->appwindow=0;

				// Close window
				CloseConfigWindow(data->window);

				// Zero stuff
				data->window=0;
				data->objlist=0;
				waitbits=1<<ipc->command_port->mp_SigBit;
			}

			// Show
			else
			if (submsg->command==IPC_SHOW && !data->window)
			{
				// Set flag to open window
				open_window=1;
				newwin.parent=(struct Window *)submsg->data;
			}

			// Passed-along app message
			else
			if (submsg->command==CFG_APPMESSAGE_PASS)
			{
				funced_appmsg(data,submsg->data);
				ReplyMsg((struct Message *)submsg->data);
			}

			// Update our identity
			else
			if (submsg->command==CFG_NEW_ID)
			{
				data->function->function.func_type=submsg->flags;
				startup->object_flags=(ULONG)submsg->data;
			}

			// Copy a function
			else
			if (submsg->command==FUNCTIONEDIT_COPY_LINE)
			{
				FunctionEntry *entry,*next;

				// Copy function
				functioned_copy_line(
					data,
					(FunctionEntry *)submsg->data,
					0,
					(Point *)submsg->data_free);

				// Free function
				entry=(FunctionEntry *)submsg->data;
				while (entry)
				{
					// Get next
					next=(FunctionEntry *)entry->node;

					// Free entry
					FreeVec(entry);
					entry=next;
				}
			}

			// Clip button
			else
			if (submsg->command==BUTTONEDIT_CLIP_BUTTON)
			{
				Cfg_ButtonFunction *func;

				// Show busy pointer
				SetWindowBusy(data->window);

				// Stop editing
				funced_end_edit(data,data->edit_node,0,0);
				data->edit_node=0;

				// Get first function
				if ((func=(Cfg_ButtonFunction *)
					FindFunctionType(
						(struct List *)&((Cfg_Button *)submsg->data)->function_list,
						FTYPE_LEFT_BUTTON)))
				{
					FunctionEntry dummy;
					Cfg_Instruction *ins;

					// Go through instructions
					for (ins=(Cfg_Instruction *)func->instructions.mlh_Head;
						ins->node.mln_Succ;
						ins=(Cfg_Instruction *)ins->node.mln_Succ)
					{
						// Fill out dummy entry
						dummy.type=ins->type;
						if (ins->string) strcpy(dummy.buffer,ins->string);
						else dummy.buffer[0]=0;

						// Copy function line
						data->edit_node=funced_new_entry(data,0,&dummy);
					}

					// Start editing last line
					funced_start_edit(data);

					// Get flags
					data->function->function.flags=func->function.flags;
					data->function->function.code=func->function.code;
					data->function->function.qual=func->function.qual;
					data->function->function.qual_mask=func->function.qual_mask;
					data->function->function.qual_same=func->function.qual_same;

					// Update flag list
					funced_update_flaglist(data);

					// Update key
					funced_show_key(data);
				}

				// Free button
				FreeButton((Cfg_Button *)submsg->data);

				// Clear busy pointer
				ClearWindowBusy(data->window);
			}

			// Reply the message
			IPC_Reply(submsg);
		}

		// Open window?
		if (open_window)
		{
			// Open window
			if (!(data->window=OpenConfigWindow(&newwin)) ||
				!(data->p_objlist=AddObjectList(
					data->window,
					(startup->flags&FUNCEDF_IMAGE)?_function_editor_image_objects:
						((startup->flags&FUNCEDF_LABEL)?_function_editor_label_objects:
														_function_editor_normal_objects))) ||
				!(data->objlist=AddObjectList(data->window,_function_editor_objects)))
				break;

			// Add use or save button
			AddObjectList(data->window,(startup->flags&FUNCEDF_SAVE)?_function_editor_objects_save:_function_editor_objects_use);

			// Store window for drag
			data->drag.window=data->window;

			// Set window ID
			SetWindowID(data->window,0,WINDOW_FUNCTION_EDITOR,(struct MsgPort *)ipc);

			// Add menus
			AddWindowMenus(data->window,_funced_menus);

			// Make this an AppWindow
			data->appwindow=AddAppWindowA(0,0,data->window,data->appport,0);

			// Get waitbits
			waitbits|=1<<data->window->UserPort->mp_SigBit;
			if (data->appwindow) waitbits|=1<<data->appport->mp_SigBit;

			// Disable key?
			if (startup->flags&FUNCEDF_NO_KEY)
			{
				DisableObject(data->objlist,GAD_FUNCED_KEY,TRUE);
			}

			// Initialise gadgets with function data.
			funced_init_gads(data);
			open_window=0;
		}

		// Intuimessage
		if (data->window)
		{
			while ((gmsg=GetWindowMsg(data->window->UserPort)))
			{
				Att_Node *node;

				// Copy message and reply (unless IDCMPUPDATE)
				msg=*gmsg;
				if (gmsg->Class!=IDCMP_IDCMPUPDATE)
				{
					ReplyWindowMsg(gmsg);
					gmsg=0;
				}

				// Get GadgetID
				if (msg.Class==IDCMP_GADGETDOWN ||
					msg.Class==IDCMP_GADGETUP)
					gadgetid=((struct Gadget *)msg.IAddress)->GadgetID;

				// Look at message
				switch (msg.Class)
				{
					// Key press
					case IDCMP_VANILLAKEY:

						// If editing something, activate string gadget
						if (data->edit_node)
							ActivateStrGad(GADGET(GetObject(data->objlist,GAD_FUNCED_EDIT)),data->window);
						break;


					// Close window
					case IDCMP_CLOSEWINDOW:

						// Set break flag
						break_flag=1;
						break;


					// Mouse move
					case IDCMP_MOUSEMOVE:

						// Handle drag move
						config_drag_move(&data->drag);
						break;


					// Inactive window does menu down
					case IDCMP_INACTIVEWINDOW:
						msg.Code=MENUDOWN;

					// Mouse buttons
					case IDCMP_MOUSEBUTTONS:

						// Valid drag info?
						if (data->drag.drag)
						{
							short ok=-1;

							// Dropped ok?
							if (msg.Code==SELECTUP)
							{
								// Is shift down?
								if (msg.Qualifier&(IEQUALIFIER_LSHIFT|IEQUALIFIER_RSHIFT))
									data->drag_shift=1;
								else data->drag_shift=0;

								// Remember last position
								data->drag.drag_x=data->window->WScreen->MouseX;
								data->drag.drag_y=data->window->WScreen->MouseY;
								ok=1;
							}

							// Aborted
							else
							if (msg.Code==MENUDOWN)
							{
								// Set abort
								ok=0;
							}

							// End drag?
							if (ok!=-1) functioned_end_drag(data,ok);
						}
						break;


					// Menu
					case IDCMP_MENUPICK:

						{
							struct MenuItem *item;

							// Get item
							if (!(item=ItemAddress(data->window->MenuStrip,msg.Code)))
								break;

							// Treat as gadget
							gadgetid=MENUID(item);
						}

					// Gadget
					case IDCMP_GADGETUP:
					case IDCMP_GADGETDOWN:

						// Look at gadget ID
						switch (gadgetid)
						{
							// Hotkey
							case GAD_FUNCED_KEY:
								{
									IX ix;
									char *ptr;

									// Get key, see if it's invalid
									if ((ptr=(char *)GetGadgetValue(data->objlist,GAD_FUNCED_KEY)) && *ptr)
									{
										// Try to parse
										if (ParseIX(ptr,&ix))
										{
											// Flash screen
											DisplayBeep(data->window->WScreen);

											// Activate key field again
											ActivateStrGad(GADGET(GetObject(data->objlist,GAD_FUNCED_KEY)),data->window);
										}
										else
										{
											data->function->function.code=ix.ix_Code;
											data->function->function.qual=QualValid(ix.ix_Qualifier);
											data->function->function.qual_mask=ix.ix_QualMask;
											data->function->function.qual_same=ix.ix_QualSame;
										}
									}
								}
								break;


							// Flag selected
							case GAD_FUNCED_FLAGS:

								// Get selected node
								node=Att_FindNode(data->flag_list,msg.Code);

								// Set flag
								data->function->function.flags^=node->data;

								// Check change
								funced_check_flag(&data->function->function.flags,node->data);

								// Update flag list
								funced_update_flaglist(data);
								break;


							// Edit a line
							case GAD_FUNCED_LISTER:

								// Get selected node
								node=Att_FindNode(data->func_display_list,msg.Code);

								// Is this the node we're already editing?
								if (node==data->edit_node) break;

								// If we're editing another one, store its contents
								if (data->edit_node)
									funced_end_edit(data,data->edit_node,0,0);

								// Start editing this entry
								data->edit_node=node;
								funced_start_edit(data);
								break;


							// Return pressed in edit line
							case GAD_FUNCED_EDIT:

								// See if we were editing something
								if (data->edit_node)
								{
									// Stop editing
									funced_end_edit(data,data->edit_node,END_DISABLE,msg.Qualifier);
									data->edit_node=0;
								}
								break;


							// New entry
							case GAD_FUNCED_NEW_ENTRY:
							case GAD_FUNCED_INSERT_ENTRY:

								// Create new entry
								functioned_copy_line(data,0,gadgetid,0);
								break;


							// Delete entry
							case GAD_FUNCED_DELETE_ENTRY:
								// Check we were editing something
								if (!data->edit_node) break;

								// Stop editing (signal delete)
								funced_end_edit(data,data->edit_node,END_DISABLE|END_DELETE,0);
								data->edit_node=0;
								break;


							// Function type
							case GAD_FUNCED_FUNCTION_TYPE:
								// Check we were editing something
								if (!data->edit_node) break;

								// Store type
								((FunctionEntry *)data->edit_node->data)->type=msg.Code;

								// Disable popup button if no functions
								DisableObject(
									data->objlist,
									GAD_FUNCED_EDIT_GLASS,
									(msg.Code==INST_COMMAND && !data->startup->func_list));
								break;


							// Glass gadget
							case GAD_FUNCED_EDIT_GLASS:

								// Check we were editing something
								if (data->edit_node)
								{
									char buffer[256];

									// Put up requester
									if (!(funced_command_req(
										data,
										buffer,
										((FunctionEntry *)data->edit_node->data)->type)))
										break;

									// Insert string in edit line
									funced_edit_insertstring(
										data->objlist,
										GAD_FUNCED_EDIT,
										buffer,
										DOpusBase,(struct Library *)IntuitionBase);
								}
								break;


							// Argument list
							case GAD_FUNCED_EDIT_ARGUMENT:

								// Check we were editing something
								if (data->edit_node)
								{
									char buffer[80];

									// Put up requester
									if (!(funced_command_req(
										data,
										buffer,
										-1))) break;

									// Insert string in edit line
									funced_edit_insertstring(
										data->objlist,
										GAD_FUNCED_EDIT,
										buffer,
										DOpusBase,(struct Library *)IntuitionBase);
								}
								break;


							// Export
							case MENU_FUNCED_EXPORT_ASCII:
							case MENU_FUNCED_EXPORT_CMD:

								// Got file requester?
								if (WINREQUESTER(data->window))
								{
									struct TagItem tags[6];
									struct FileRequester *req=WINREQUESTER(data->window);

									// Show busy pointer
									SetWindowBusy(data->window);

									// File requester tags
									tags[0].ti_Tag=ASLFR_Window;
									tags[0].ti_Data=(ULONG)data->window;
									tags[1].ti_Tag=ASLFR_TitleText;
									tags[1].ti_Data=(ULONG)GetString(startup->locale,MSG_FUNCED_SELECT_FILE);
									tags[2].ti_Tag=ASLFR_Flags1;
									tags[2].ti_Data=FRF_DOSAVEMODE|FRF_PRIVATEIDCMP;
									tags[3].ti_Tag=ASLFR_Flags2;
									tags[3].ti_Data=FRF_REJECTICONS;
									tags[4].ti_Tag=(gadgetid==MENU_FUNCED_EXPORT_CMD)?ASLFR_InitialDrawer:TAG_DONE;
									tags[4].ti_Data=(ULONG)"DOpus5:Commands";
									tags[5].ti_Tag=TAG_DONE;

									// Show filerequester
									if (AslRequest(req,tags))
									{
										// Build filename
										strcpy(data->buffer,req->fr_Drawer);
										AddPart(data->buffer,req->fr_File,256);

										// Store changes in function
										funced_store_edits(data);

										// Do export
										if (gadgetid==MENU_FUNCED_EXPORT_CMD)
											function_export_cmd(data->buffer,0,data->function);
										else
											L_FunctionExportASCII(data->buffer,0,data->function,startup->a4);
									}

									// Remove busy pointer
									ClearWindowBusy(data->window);
								}
								break;


							// Cut/Copy
							case MENU_FUNCED_CUT:
							case MENU_FUNCED_COPY:
								{
									APTR iff;

									// Set busy pointer
									SetWindowBusy(data->window);

									// Open clipboard
									if ((iff=IFFOpen((char *)0,IFF_CLIP_WRITE,ID_OPUS)))
									{
										// Stop editing
										funced_end_edit(data,data->edit_node,END_DISABLE,0);
										data->edit_node=0;

										// Store changes in function
										funced_store_edits(data);

										// Save function
										SaveFunction(iff,data->function);

										// Close clipboard
										IFFClose(iff);
									}

									// Just copy, not cut?
									if (gadgetid==MENU_FUNCED_COPY)
									{
										// Clear busy pointer
										ClearWindowBusy(data->window);
										break;
									}

									// Fall through, paste null function
								}

							// Paste
							case MENU_FUNCED_PASTE:
								{
									Cfg_Function *func=0;

									// Set busy pointer
									SetWindowBusy(data->window);

									// End any edit
									funced_end_edit(data,data->edit_node,END_DISABLE,0);
									data->edit_node=0;

									// Paste?
									if (gadgetid==MENU_FUNCED_PASTE)
									{
										APTR iff;

										// Open clipboard
										if ((iff=IFFOpen((char *)0,IFF_CLIP_READ,ID_OPUS)))
										{
											// Find function
											if (IFFNextChunk(iff,ID_FUNC))
											{
												// Read function
												func=ReadFunction(iff,0,0,0);
											}

											// Close clipboard
											IFFClose(iff);
										}

										// No valid function?
										if (!func)
										{
											// Flash error
											DisplayBeep(data->window->WScreen);
											ClearWindowBusy(data->window);
											break;
										}
									}

									// Detach existing list
									SetGadgetChoices(data->objlist,GAD_FUNCED_FLAGS,(APTR)~0);

									// Clear function list
									Att_RemList(data->function_list,REMLIST_SAVELIST|REMLIST_FREEDATA);

									// Free existing instructions
									FreeInstructionList(data->function);

									// Rebuild display list
									funced_build_display(data);

									// Clear flags
									data->function->function.flags=0;
									funced_update_flaglist(data);

									// Clear key
									data->function->function.code=0xffff;
									SetGadgetValue(data->objlist,GAD_FUNCED_KEY,0);

									// Clear label
									if (startup->flags&FUNCEDF_LABEL)
									{
										data->label[0]=0;
										SetGadgetValue(data->p_objlist,GAD_FUNCED_LABEL,0);
									}

									// Paste function in?
									if (func)
									{
										short type;

										// Save type
										type=data->function->function.func_type;

										// Copy function in
										CopyFunction(func,0,data->function);
										data->function->function.func_type=type;

										// Free copied function
										FreeFunction(func);

										// Initialise gadgets
										funced_init_gads(data);
									}
	
									// Clear busy pointer
									ClearWindowBusy(data->window);
								}
								break;


							// Use
							case GAD_FUNCED_USE:
								success=1;

							// Cancel
							case GAD_FUNCED_CANCEL:
								break_flag=1;
								break;
						}
						break;


					// Key press
					case IDCMP_RAWKEY:

						// Help?
						if (msg.Code==0x5f &&
							!(msg.Qualifier&VALID_QUALIFIERS))	
						{
							// Set busy pointer
							SetWindowBusy(data->window);

							// Send help command
							IPC_Command(startup->main_owner,IPC_HELP,(1<<31),"Function Editor",0,REPLY_NO_PORT);

							// Clear busy pointer
							ClearWindowBusy(data->window);
						}
						break;


					// BOOPSI message
					case IDCMP_IDCMPUPDATE:
						{
							struct TagItem *tags=(struct TagItem *)msg.IAddress;
							short item;

							// Check ID
							if (GetTagData(GA_ID,0,tags)!=GAD_FUNCED_LISTER)
								break;

							// Get item
							if ((item=GetTagData(DLV_DragNotify,-1,tags))!=-1)
							{
								// Start the drag
								config_drag_start(&data->drag,data->func_display_list,item,tags,TRUE);
							}
						}
						break;


					// Ticks
					case IDCMP_INTUITICKS:
						++data->drag.tick_count;
						break;
				}

				// Reply to any outstanding message
				if (gmsg) ReplyWindowMsg(gmsg);
			}
		}

		// AppMessage
		if (data->appwindow)
		{
			struct AppMessage *msg;

			while ((msg=(struct AppMessage *)GetMsg(data->appport)))
			{
				// Make sure window is active
				ActivateWindow(data->window);

				// Handle message
				funced_appmsg(data,msg);
				ReplyMsg((struct Message *)msg);
			}
		}

		// Check break flag
		if (break_flag) break;

		// Wait for message
		Wait(waitbits);
	}

	// Restore CD
	if (lock) UnLock(CurrentDir(lock));

	// Edit successful?
	if (success)
	{
		FunctionReturn ret;

		// Store changes in function
		funced_store_edits(data);

		// Fill out return data
		ret.object=startup->object;
		ret.object_flags=startup->object_flags;
		ret.function=data->function;

		// Send new function back
		IPC_Command(startup->owner_ipc,FUNCTIONEDIT_RETURN,0,&ret,0,REPLY_NO_PORT);
	}

	// End any drag in progress
	functioned_end_drag(data,0);

	// Free edit function
	FreeFunction(data->function);

	// Close window
	RemoveAppWindow(data->appwindow);
	CloseConfigWindow(data->window);

	// Close application port
	if (data->appport)
	{
		struct Message *msg;
		while ((msg=GetMsg(data->appport)))
			ReplyMsg(msg);
		DeleteMsgPort(data->appport);
	}

	// Say goodbye
	IPC_Goodbye(ipc,startup->owner_ipc,startup->object_flags);

	// Delete IPC data
	Forbid();
	IPC_Free(ipc);

	// Free data
	funced_cleanup(data);
	FreeVec(startup);
}
Example #25
0
/**
 * Change the displayed search status.
 *
 * \param gwin gui window to open search for.
 */
void ami_search_open(struct gui_window *gwin)
{
	search_insert = true;

	if(fwin)
	{
		browser_window_search_clear(fwin->gwin->bw);
		fwin->gwin->shared->searchwin = NULL;
		fwin->gwin = gwin;
		gwin->shared->searchwin = fwin;
		WindowToFront(fwin->win);
		ActivateWindow(fwin->win);
		return;
	}

	fwin = ami_misc_allocvec_clear(sizeof(struct find_window), 0);

	fwin->objects[OID_MAIN] = WindowObj,
      	WA_ScreenTitle, ami_gui_get_screen_title(),
       	WA_Title,messages_get("FindTextNS"),
       	WA_Activate, TRUE,
       	WA_DepthGadget, TRUE,
       	WA_DragBar, TRUE,
       	WA_CloseGadget, TRUE,
       	WA_SizeGadget, TRUE,
		WA_PubScreen,scrn,
		WINDOW_SharedPort,sport,
		WINDOW_UserData,fwin,
		WINDOW_IconifyGadget, FALSE,
		WINDOW_LockHeight,TRUE,
         	WINDOW_Position, WPOS_CENTERSCREEN,
           	WINDOW_ParentGroup, fwin->objects[GID_MAIN] = LayoutVObj,
				LAYOUT_AddChild, fwin->objects[GID_SEARCHSTRING] = StringObj,
					GA_ID,GID_SEARCHSTRING,
					GA_TabCycle,TRUE,
					GA_RelVerify,TRUE,
				StringEnd,
				CHILD_WeightedHeight,0,
				LAYOUT_AddChild, fwin->objects[GID_CASE] = CheckBoxObj,
					GA_ID,GID_CASE,
					GA_Text,messages_get("CaseSens"),
					GA_Selected,FALSE,
					GA_TabCycle,TRUE,
					GA_RelVerify,TRUE,
				CheckBoxEnd,
				LAYOUT_AddChild, fwin->objects[GID_SHOWALL] = CheckBoxObj,
					GA_ID,GID_SHOWALL,
					GA_Text,messages_get("ShowAll"),
					GA_Selected,FALSE,
					GA_TabCycle,TRUE,
					GA_RelVerify,TRUE,
				CheckBoxEnd,

				LAYOUT_AddChild, LayoutHObj,
					LAYOUT_AddChild, fwin->objects[GID_PREV] = ButtonObj,
						GA_ID,GID_PREV,
						GA_RelVerify,TRUE,
						GA_Text,messages_get("Prev"),
						GA_TabCycle,TRUE,
						GA_Disabled,TRUE,
					ButtonEnd,
					CHILD_WeightedHeight,0,
					LAYOUT_AddChild, fwin->objects[GID_NEXT] = ButtonObj,
						GA_ID,GID_NEXT,
						GA_RelVerify,TRUE,
						GA_Text,messages_get("Next"),
						GA_TabCycle,TRUE,
						GA_Disabled,TRUE,
					ButtonEnd,
				LayoutEnd,
				CHILD_WeightedHeight,0,
			EndGroup,
		EndWindow;

	fwin->win = (struct Window *)RA_OpenWindow(fwin->objects[OID_MAIN]);
	fwin->gwin = gwin;
	fwin->node = AddObject(window_list,AMINS_FINDWINDOW);
	fwin->node->objstruct = fwin;
	gwin->shared->searchwin = fwin;
	
	ActivateLayoutGadget((struct Gadget *)fwin->objects[GID_MAIN], fwin->win,
			NULL, (ULONG)fwin->objects[GID_SEARCHSTRING]);
}
Example #26
0
int LIBFUNC L_Module_Entry(
	REG(a0, struct List *files),
	REG(a1, struct Screen *screen),
	REG(a2, IPCData *ipc),
	REG(a3, IPCData *main_ipc),
	REG(d0, ULONG mod_id),
	REG(d1, ULONG mod_data))
{
	config_path_data *data;
	short success=1;

	// Allocate data
	if (!(data=AllocVec(sizeof(config_path_data),MEMF_CLEAR)) ||
		!(data->path_list=Att_NewList(0)))
	{
		FreeVec(data);
		return 0;
	}

	// Store data pointers
	data->paths=files;
	data->ipc=ipc;
	data->main_ipc=main_ipc;
	data->memory=(APTR)mod_id;
	data->def_format=(ListFormat *)mod_data;

	// AppPort
	data->appport=CreateMsgPort();

	// Open commodities library
	/*data->cxbase=OpenLibrary("commodities.library",0);
	#ifdef __amigaos4__
	ICommodities=(struct CommoditiesIFace *)GetInterface(data->cxbase,"main",1,NULL); 
	#endif	*/
	
	// Build path list
	config_paths_build_list(data);

	// Open window
	if (!(config_paths_open(data,screen)))
		return 0;

	// Event loop
	FOREVER
	{
		IPCMessage *imsg;
		struct IntuiMessage *msg;
		int quit_flag=0;

		// IPC messages?
		while ((imsg=(IPCMessage *)GetMsg(ipc->command_port)))
		{
			// Quit?
			if (imsg->command==IPC_QUIT)
			{
				quit_flag=1;
				success=0;
			}

			// Hide?
			else if (imsg->command==IPC_HIDE)
			{
				RemoveAppWindow(data->appwindow);
				data->appwindow=0;
				CloseConfigWindow(data->window);	
				data->window=0;
			}

			// Show?
			else if (imsg->command==IPC_SHOW)
			{
				if (!(config_paths_open(data,imsg->data)))
				{
					quit_flag=1;
					success=0;
				}
			}

			// Activate
			else if (imsg->command==IPC_ACTIVATE)
			{
				if (data->window)
				{
					WindowToFront(data->window);
					ActivateWindow(data->window);
				}
			}

			// Reply
			IPC_Reply(imsg);
		}

		// Any messages to the window?
		if (data->window)
		{
			while ((msg=GetWindowMsg(data->window->UserPort)))
			{
				struct IntuiMessage msg_copy;
				UWORD gadgetid;

				// Copy message and reply
				msg_copy=*msg;
				ReplyWindowMsg(msg);

				// Look at message
				switch (msg_copy.Class)
				{
					// Close window
					case IDCMP_CLOSEWINDOW:
						quit_flag=1;
						success=0;
						break;


					// Gadget
					case IDCMP_GADGETUP:
					case IDCMP_GADGETDOWN:

						// Get GadgetID
						gadgetid=((struct Gadget *)msg_copy.IAddress)->GadgetID;

						// Look at gadget
						switch (gadgetid)
						{
							// Cancel
							case GAD_PATHFORMAT_CANCEL:
								success=0;

							// Use
							case GAD_PATHFORMAT_SAVE:
								quit_flag=1;
								break;


							// Add an entry
							case GAD_PATHFORMAT_ADD:
								config_paths_add(data,TRUE);
								break;


							// Change path name
							case GAD_PATHFORMAT_PATH:
								config_paths_change(data);
								break;


							// Select an entry
							case GAD_PATHFORMAT_PATHS:
								{
									Att_Node *node;

									// Find selected entry
									node=Att_FindNode(data->path_list,msg_copy.Code);

									// Double-click?
									if (DoubleClick(data->seconds,data->micros,msg_copy.Seconds,msg_copy.Micros) &&
										node==data->path_sel)
									{
										// Edit it	
										config_paths_edit(data);
										break;
									}

									// Store double-click time
									data->seconds=msg_copy.Seconds;
									data->micros=msg_copy.Micros;

									// Not already selected?
									if (node!=data->path_sel)
									{
										// Select it
										config_paths_select(data,node,FALSE);
									}
								}
								break;


							// Key
							case GAD_PATHFORMAT_KEY:
								config_paths_get_key(data);
								break;


							// Open new lister
							case GAD_PATHFORMAT_NEW_LISTER:

								// Valid selection?
								if (data->path_sel)
								{
									position_rec *pos=(position_rec *)data->path_sel->data;

									// Open new lister?
									if (msg_copy.Code)
									{
										// Set flag
										pos->flags|=POSITIONF_OPEN_NEW;
	
										// Clear type flags
										pos->flags&=~(POSITIONF_ICON|POSITIONF_ICON_ACTION);

										// Icon action?
										if (msg_copy.Code==MODE_ACTION)
											pos->flags|=POSITIONF_ICON|POSITIONF_ICON_ACTION;

										// Icon?
										else
										if (msg_copy.Code==MODE_ICON)
											pos->flags|=POSITIONF_ICON;
									}

									// No lister
									else pos->flags&=~POSITIONF_OPEN_NEW;
								}
								break;


							// Remove
							case GAD_PATHFORMAT_REMOVE:
								config_paths_remove(data,TRUE);
								break;


							// Edit
							case GAD_PATHFORMAT_EDIT:
								config_paths_edit(data);
								break;
						}
						break;


					// Key press
					case IDCMP_RAWKEY:

						// Help?
						if (msg_copy.Code==0x5f &&
							!(msg_copy.Qualifier&VALID_QUALIFIERS))
						{
							// Valid main IPC?
							if (main_ipc)
							{
								// Set busy pointer
								SetWindowBusy(data->window);

								// Send help request
								IPC_Command(main_ipc,IPC_HELP,(1<<31),"Paths",0,(struct MsgPort *)-1);

								// Clear busy pointer
								ClearWindowBusy(data->window);
							}
						}
						break;
				}

				// Check quit flag
				if (quit_flag) break;
			}
		}

		// Check quit flag
		if (quit_flag) break;

		// App messages?
		if (data->appport)
		{
			struct AppMessage *msg;

			// Get messages
			while ((msg=(struct AppMessage *)GetMsg(data->appport)))
			{
				// Get first argument
				if (msg->am_NumArgs>0)
				{
					// Is it a directory?
					if (!msg->am_ArgList[0].wa_Name || !*msg->am_ArgList[0].wa_Name)
					{
						char buf[256];

						// Expand path name	
						if (NameFromLock(msg->am_ArgList[0].wa_Lock,buf,256))
						{
							Att_Node *node;

							// Fix trailing /
							AddPart(buf,"",256);

							// Check it's not already in the list
							if (!(node=(Att_Node *)FindNameI((struct List *)data->path_list,buf)))
							{
								// Add a new entry
								config_paths_add(data,FALSE);

								// Copy path to path field
								SetGadgetValue(data->objlist,GAD_PATHFORMAT_PATH,(ULONG)buf);

								// Accept the new path
								config_paths_change(data);
							}

							// It is, select this entry
							else config_paths_select(data,node,FALSE);
						}
					}
				}

				// Reply message
				ReplyMsg((struct Message *)msg);
			}
		}

		// Wait for input
		Wait(
			((data->window)?(1<<data->window->UserPort->mp_SigBit):0)|
			((data->appport)?(1<<data->appport->mp_SigBit):0)|
			1<<ipc->command_port->mp_SigBit);
	}

	// Free stuff
	config_paths_cleanup(data);
	return success;
}
Example #27
0
///
/// HandleIDMCP
PERROR HandleIDCMP( FRAME *frame, struct Objects *o, struct Values *v, struct PPTBase *PPTBase )
{
    ULONG sig, sigmask, sigport = 0L;
    struct Library *ColorWheelBase = o->ColorWheelBase;
    struct IntuitionBase *IntuitionBase = PPTBase->lb_Intuition;
    BOOL V39 = FALSE;

    if( PPTBase->lb_Gfx->LibNode.lib_Version >= 39 && ColorWheelBase )
        V39 = TRUE;

    if(StartInput(frame, GINP_PICK_POINT, NULL) == PERR_OK)
        sigport = (1 << PPTBase->mport->mp_SigBit);

    GetAttr( WINDOW_SigMask, o->Win, &sigmask );
    for(;;) {

        sig = Wait( sigport|sigmask|SIGBREAKF_CTRL_C|SIGBREAKF_CTRL_F );

        if( sig & SIGBREAKF_CTRL_C ) {
            SetErrorCode( frame, PERR_BREAK );
            DisposeObject( o->Win );
            StopInput(frame);
            return PERR_BREAK;
        }

        if( sig & SIGBREAKF_CTRL_F ) {
            WindowToFront( o->win );
            ActivateWindow( o->win );
        }

        if( sig & sigport ) {
            struct gPointMessage *gp;

            gp = (struct gPointMessage*)GetMsg(PPTBase->mport);

            /*
             *  Ignore all other types of messages, except pickpoints.
             */

            if( gp->msg.code == PPTMSG_PICK_POINT ) {
                D(bug("User picked point (%d,%d)\n",gp->x,gp->y));

                if( frame->pix->colorspace == CS_RGB ) {
                    RGBPixel *cp;

                    cp = (RGBPixel *)GetPixelRow( frame, gp->y );
                    SetGadgetAttrs( GAD(o->Red), o->win, NULL, SLIDER_Level, cp[gp->x].r, TAG_DONE );
                    SetGadgetAttrs( GAD(o->Green), o->win, NULL, SLIDER_Level, cp[gp->x].g, TAG_DONE );
                    SetGadgetAttrs( GAD(o->Blue), o->win, NULL, SLIDER_Level, cp[gp->x].b, TAG_DONE );
                } else {
                    ARGBPixel *cp;

                    cp = (ARGBPixel *)GetPixelRow( frame, gp->y );
                    SetGadgetAttrs( GAD(o->Trans), o->win, NULL, SLIDER_Level, cp[gp->x].a, TAG_DONE );
                    SetGadgetAttrs( GAD(o->Red), o->win, NULL, SLIDER_Level, cp[gp->x].r, TAG_DONE );
                    SetGadgetAttrs( GAD(o->Green), o->win, NULL, SLIDER_Level, cp[gp->x].g, TAG_DONE );
                    SetGadgetAttrs( GAD(o->Blue), o->win, NULL, SLIDER_Level, cp[gp->x].b, TAG_DONE );
                }

                v->background = FALSE;
            }

            ReplyMsg( (struct Message *)gp );
        }

        if( sig & sigmask ) {
            ULONG rc, tmp;
            struct ColorWheelRGB rgb;
            struct ColorWheelHSB hsb;

            while(( rc = HandleEvent( o->Win )) != WMHI_NOMORE ) {
                switch(rc) {
                    case WMHI_CLOSEWINDOW:
                    case GID_CANCEL:
                        D(bug("User cancelled\n"));
                        SetErrorCode( frame, PERR_CANCELED );
                        DisposeObject( o->Win );
                        StopInput(frame);
                        return PERR_CANCELED;

                    /*
                     *  Can't happen if running under <V39, but let's be
                     *  sure anyway
                     */

                    case GID_GRADIENTSLIDER:
                        if( V39 ) {
                            GetAttr(GRAD_CurVal, o->RealGradient, &tmp);
                            // D(bug("New value: %d\n",tmp));
                            GetAttr( WHEEL_HSB, o->Wheel, (ULONG *)&hsb );
                            hsb.cw_Brightness = (0xFFFF - tmp) * 0x00010001;
                            ConvertHSBToRGB( &hsb, &rgb );
                            SetGadgetAttrs( GAD(o->Red), o->win, NULL, SLIDER_Level, rgb.cw_Red>>24, TAG_DONE );
                            SetGadgetAttrs( GAD(o->Green), o->win, NULL, SLIDER_Level, rgb.cw_Green>>24, TAG_DONE );
                            SetGadgetAttrs( GAD(o->Blue), o->win, NULL, SLIDER_Level, rgb.cw_Blue>>24, TAG_DONE );
                            v->background = FALSE;
                        }
                        break;

                    /*
                     *  Ditto
                     */

                    case GID_WHEEL:
                        if( V39 ) {
                            GetAttr( WHEEL_RGB, o->Wheel, (ULONG *) &rgb );
                            SetGadgetAttrs( GAD(o->Red), o->win, NULL, SLIDER_Level, rgb.cw_Red>>24, TAG_DONE );
                            SetGadgetAttrs( GAD(o->Green), o->win, NULL, SLIDER_Level, rgb.cw_Green>>24, TAG_DONE );
                            SetGadgetAttrs( GAD(o->Blue), o->win, NULL, SLIDER_Level, rgb.cw_Blue>>24, TAG_DONE );
                            v->background = FALSE;
                        }
                        break;

                    case GID_RED:
                        if( V39 ) {
                            GetAttr( SLIDER_Level, o->Red, (ULONG *)&tmp );
                            GetAttr( WHEEL_RGB, o->Wheel, (ULONG *) &rgb );
                            rgb.cw_Red = tmp * 0x01010101;
                            SetGadgetAttrs( GAD(o->Wheel), o->win, NULL, WHEEL_RGB, &rgb, TAG_DONE );
                            v->background = FALSE;
                        }
                        break;

                    case GID_GREEN:
                        if( V39 ) {
                            GetAttr( SLIDER_Level, o->Green, (ULONG *)&tmp );
                            GetAttr( WHEEL_RGB, o->Wheel, (ULONG *) &rgb );
                            rgb.cw_Green = tmp * 0x01010101;
                            SetGadgetAttrs( GAD(o->Wheel), o->win, NULL, WHEEL_RGB, &rgb, TAG_DONE );
                            v->background = FALSE;
                        }
                        break;

                    case GID_BLUE:
                        if( V39 ) {
                            GetAttr( SLIDER_Level, o->Blue, (ULONG *)&tmp );
                            GetAttr( WHEEL_RGB, o->Wheel, (ULONG *) &rgb );
                            rgb.cw_Blue = tmp * 0x01010101;
                            SetGadgetAttrs( GAD(o->Wheel), o->win, NULL, WHEEL_RGB, &rgb, TAG_DONE );
                            v->background = FALSE;
                        }
                        break;

                    case GID_BACKGROUND:
                        GetBackGround( frame, v, PPTBase );

                        if( V39 ) {
                            rgb.cw_Red   = v->r * 0x01010101;
                            rgb.cw_Green = v->g * 0x01010101;
                            rgb.cw_Blue  = v->b * 0x01010101;
                            SetGadgetAttrs( GAD(o->Wheel), o->win, NULL, WHEEL_RGB, &rgb, TAG_DONE );
                            DoMethod( o->Win, WM_REPORT_ID, GID_WHEEL, 0L ); // A bug in OS?
                        } else {
                            SetGadgetAttrs( GAD(o->Red), o->win, NULL, SLIDER_Level,v->r, TAG_DONE );
                            SetGadgetAttrs( GAD(o->Green), o->win, NULL, SLIDER_Level,v->g, TAG_DONE );
                            SetGadgetAttrs( GAD(o->Blue), o->win, NULL, SLIDER_Level,v->b, TAG_DONE );
                        }

                        break;

                    case GID_BLACK:
                        rgb.cw_Red = rgb.cw_Green = rgb.cw_Blue = 0L;
                        if( V39 ) {
                            SetGadgetAttrs( GAD(o->Wheel), o->win, NULL, WHEEL_RGB, &rgb, TAG_DONE );
                            DoMethod( o->Win, WM_REPORT_ID, GID_WHEEL, 0L ); // A bug in OS?
                        } else {
                            SetGadgetAttrs( GAD(o->Red), o->win, NULL, SLIDER_Level,rgb.cw_Red>>24, TAG_DONE );
                            SetGadgetAttrs( GAD(o->Green), o->win, NULL, SLIDER_Level,rgb.cw_Green>>24, TAG_DONE );
                            SetGadgetAttrs( GAD(o->Blue), o->win, NULL, SLIDER_Level,rgb.cw_Blue>>24, TAG_DONE );
                        }
                        v->background = FALSE;
                        break;

                    case GID_WHITE:
                        rgb.cw_Red = rgb.cw_Green = rgb.cw_Blue = 0xFFFFFFFF;
                        if (V39 ) {
                            SetGadgetAttrs( GAD(o->Wheel), o->win, NULL, WHEEL_RGB, &rgb, TAG_DONE );
                            DoMethod( o->Win, WM_REPORT_ID, GID_WHEEL, 0L ); // A bug in OS?
                        } else {
                            SetGadgetAttrs( GAD(o->Red), o->win, NULL, SLIDER_Level,rgb.cw_Red>>24, TAG_DONE );
                            SetGadgetAttrs( GAD(o->Green), o->win, NULL, SLIDER_Level,rgb.cw_Green>>24, TAG_DONE );
                            SetGadgetAttrs( GAD(o->Blue), o->win, NULL, SLIDER_Level,rgb.cw_Blue>>24, TAG_DONE );
                        }
                        v->background = FALSE;
                        break;

                    case GID_OK:
                        D(bug("User hit OK\n"));
                        DoGadgets( frame, o, v, PPTBase );
                        GetAttr( WINDOW_Bounds, o->Win, (ULONG *)&v->window );
                        DisposeObject( o->Win );
                        StopInput(frame);
                        return PERR_OK;
                }
            }
        } /* if(sig&sigmask) */
    }
Window::Window(const Rect & rect, int fulls)
{ 
   m_rect = rect;
   m_win = 0;
   m_init = false;
   m_ctx = 0;
  
   //
   // Create the Carbon window:
   OSStatus s;

   if ( fulls ) {
      s = CreateNewWindow(kOverlayWindowClass,
         kWindowStandardHandlerAttribute | kWindowCompositingAttribute,
         &m_rect, &m_win);
      if(s != noErr) {
         fprintf(stderr,"failed to create window at %i,%i,%i,%i\n",m_rect.left,m_rect.top,m_rect.right,m_rect.bottom);
         abort();
      }

      // Hide Cursor
      CGCaptureAllDisplays();
      CGDisplayHideCursor(kCGDirectMainDisplay); 
      CGReleaseAllDisplays();
    
   }
   else
   {
      // just a little offset when opening the window
      s = CreateNewWindow(kDocumentWindowClass,
         kWindowStandardDocumentAttributes | kWindowStandardHandlerAttribute| kWindowInWindowMenuAttribute,
         &m_rect, &m_win);
      if(s != noErr) {
         fprintf(stderr,"failed to create window at %i,%i,%i,%i\n",m_rect.left,m_rect.top,m_rect.right,m_rect.bottom);
         abort();
      }

      // Put a title
      SetWindowTitleWithCFString (m_win, CFSTR("SAGE GStream Receiver"));
   }

   SetWindowActivationScope(m_win,kWindowActivationScopeAll);
   ShowWindow(m_win);
   ActivateWindow(m_win, true);


   if ( ! fulls ) {
      Rect arect;
      short hGlobal, vGlobal;
      GetWindowBounds(m_win, kWindowStructureRgn, &arect);
      MoveWindow (m_win, arect.left, (arect.top < 0) ? 40 : arect.top+50, true);
   }

   // Create context
   m_ctx = aglCreateContext(agl_fmt,0);
   if(m_ctx == 0) {
      fprintf(stderr,"failed to create OpenGL context\n");
      abort();
   }

   // Set the global context, shared by other windows:
   if(agl_ctx == 0) {
      agl_ctx = m_ctx;
   }

   //
   // All your window are belong to us:
   GLboolean e;
   e = aglSetDrawable(m_ctx,GetWindowPort(m_win));
   if(!e) {
      fprintf(stderr,"failed aglSetDrawable\n");
      abort();
   }

   // Initialize the OpenGL
   aglSetCurrentContext(m_ctx);
   glViewport(0,0,m_rect.right - m_rect.left,m_rect.bottom - rect.top);
    
    /* glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    glOrtho(m_rect.left,m_rect.right,m_rect.top,m_rect.bottom,-1,1);
    
    glMatrixMode(GL_MODELVIEW);
    glLoadIdentity();
    */
    
   glClearColor(0,0,0,1);
   glClear(GL_COLOR_BUFFER_BIT);

   aglSwapBuffers(m_ctx);
}
Example #29
0
int GetConvArgs( FRAME *frame, struct TagItem *tags, struct PPTBase *xd, struct convargs *cargs )
{
    Object *Win, *wtgroup, *weights[7][7], *Bias, *Frq, *Name, *Div;
    ULONG sigmask, sig, rc;
    int quit = FALSE, res = PERR_OK,i,j;
    struct Window *win;
    struct IntuitionBase *IntuitionBase = xd->lb_Intuition;
    struct ExecBase *SysBase = xd->lb_Sys;
    struct Library *BGUIBase = xd->lb_BGUI;
    char *name = "Unknown";

#ifdef DEBUG_MODE
    PDebug("\tCreating window object\n");
#endif

    Win = WindowObject,
        WINDOW_Screen,    xd->g->maindisp->scr,
        WINDOW_Title,     frame->nd.ln_Name,
        WINDOW_Font,      xd->g->userprefs->mainfont,
        WINDOW_ScreenTitle, "Convolute Tool",
        WINDOW_ScaleWidth, 20,
        WINDOW_MenuStrip, Menus,
        TAG_SKIP,         (cargs->winpos.Height == 0) ? 1 : 0,
        WINDOW_Bounds,    &(cargs->winpos),
        WINDOW_NoBufferRP, TRUE,
        WINDOW_MasterGroup,
            VGroupObject, Spacing(4), HOffset(6), VOffset(4),
                StartMember,
                    Name = InfoFixed("Name:","",NULL,1),
                EndMember,
                StartMember,
                    HGroupObject, Spacing(4), HOffset(4),
                        StartMember,
                            /* Grid */
                            wtgroup = VGroupObject,
                                StartMember,
                                    HGroupObject,
                                        StartMember,
                                            weights[0][0] = Integer(NULL,0,3,GID_W00),
                                        EndMember,
                                        StartMember,
                                            weights[0][1] = Integer(NULL,0,3,GID_W01),
                                        EndMember,
                                        StartMember,
                                            weights[0][2] = Integer(NULL,0,3,GID_W02),
                                        EndMember,
                                        StartMember,
                                            weights[0][3] = Integer(NULL,0,3,GID_W03),
                                        EndMember,
                                        StartMember,
                                            weights[0][4] = Integer(NULL,0,3,GID_W04),
                                        EndMember,
                                        StartMember,
                                            weights[0][5] = Integer(NULL,0,3,GID_W05),
                                        EndMember,
                                        StartMember,
                                            weights[0][6] = Integer(NULL,0,3,GID_W06),
                                        EndMember,
                                    EndObject,
                                EndMember,
                                StartMember,
                                    HGroupObject,
                                        StartMember,
                                            weights[1][0] = Integer(NULL,0,3,GID_W10),
                                        EndMember,
                                        StartMember,
                                            weights[1][1] = Integer(NULL,0,3,GID_W11),
                                        EndMember,
                                        StartMember,
                                            weights[1][2] = Integer(NULL,0,3,GID_W12),
                                        EndMember,
                                        StartMember,
                                            weights[1][3] = Integer(NULL,0,3,GID_W13),
                                        EndMember,
                                        StartMember,
                                            weights[1][4] = Integer(NULL,0,3,GID_W14),
                                        EndMember,
                                        StartMember,
                                            weights[1][5] = Integer(NULL,0,3,GID_W15),
                                        EndMember,
                                        StartMember,
                                            weights[1][6] = Integer(NULL,0,3,GID_W16),
                                        EndMember,
                                    EndObject,
                                EndMember,
                                StartMember,
                                    HGroupObject,
                                        StartMember,
                                            weights[2][0] = Integer(NULL,0,3,GID_W20),
                                        EndMember,
                                        StartMember,
                                            weights[2][1] = Integer(NULL,0,3,GID_W21),
                                        EndMember,
                                        StartMember,
                                            weights[2][2] = Integer(NULL,0,3,GID_W22),
                                        EndMember,
                                        StartMember,
                                            weights[2][3] = Integer(NULL,0,3,GID_W23),
                                        EndMember,
                                        StartMember,
                                            weights[2][4] = Integer(NULL,0,3,GID_W24),
                                        EndMember,
                                        StartMember,
                                            weights[2][5] = Integer(NULL,0,3,GID_W25),
                                        EndMember,
                                        StartMember,
                                            weights[2][6] = Integer(NULL,0,3,GID_W26),
                                        EndMember,
                                    EndObject,
                                EndMember,
                                StartMember,
                                    HGroupObject,
                                        StartMember,
                                            weights[3][0] = Integer(NULL,0,3,GID_W30),
                                        EndMember,
                                        StartMember,
                                            weights[3][1] = Integer(NULL,0,3,GID_W31),
                                        EndMember,
                                        StartMember,
                                            weights[3][2] = Integer(NULL,0,3,GID_W32),
                                        EndMember,
                                        StartMember,
                                            weights[3][3] = Integer(NULL,1,3,GID_W33),
                                        EndMember,
                                        StartMember,
                                            weights[3][4] = Integer(NULL,0,3,GID_W34),
                                        EndMember,
                                        StartMember,
                                            weights[3][5] = Integer(NULL,0,3,GID_W35),
                                        EndMember,
                                        StartMember,
                                            weights[3][6] = Integer(NULL,0,3,GID_W36),
                                        EndMember,
                                    EndObject,
                                EndMember,
                                StartMember,
                                    HGroupObject,
                                        StartMember,
                                            weights[4][0] = Integer(NULL,0,3,GID_W40),
                                        EndMember,
                                        StartMember,
                                            weights[4][1] = Integer(NULL,0,3,GID_W41),
                                        EndMember,
                                        StartMember,
                                            weights[4][2] = Integer(NULL,0,3,GID_W42),
                                        EndMember,
                                        StartMember,
                                            weights[4][3] = Integer(NULL,0,3,GID_W43),
                                        EndMember,
                                        StartMember,
                                            weights[4][4] = Integer(NULL,0,3,GID_W44),
                                        EndMember,
                                        StartMember,
                                            weights[4][5] = Integer(NULL,0,3,GID_W45),
                                        EndMember,
                                        StartMember,
                                            weights[4][6] = Integer(NULL,0,3,GID_W46),
                                        EndMember,
                                    EndObject,
                                EndMember,
                                StartMember,
                                    HGroupObject,
                                        StartMember,
                                            weights[5][0] = Integer(NULL,0,3,GID_W50),
                                        EndMember,
                                        StartMember,
                                            weights[5][1] = Integer(NULL,0,3,GID_W51),
                                        EndMember,
                                        StartMember,
                                            weights[5][2] = Integer(NULL,0,3,GID_W52),
                                        EndMember,
                                        StartMember,
                                            weights[5][3] = Integer(NULL,0,3,GID_W53),
                                        EndMember,
                                        StartMember,
                                            weights[5][4] = Integer(NULL,0,3,GID_W54),
                                        EndMember,
                                        StartMember,
                                            weights[5][5] = Integer(NULL,0,3,GID_W55),
                                        EndMember,
                                        StartMember,
                                            weights[5][6] = Integer(NULL,0,3,GID_W56),
                                        EndMember,
                                    EndObject,
                                EndMember,
                                StartMember,
                                    HGroupObject,
                                        StartMember,
                                            weights[6][0] = Integer(NULL,0,3,GID_W60),
                                        EndMember,
                                        StartMember,
                                            weights[6][1] = Integer(NULL,0,3,GID_W61),
                                        EndMember,
                                        StartMember,
                                            weights[6][2] = Integer(NULL,0,3,GID_W62),
                                        EndMember,
                                        StartMember,
                                            weights[6][3] = Integer(NULL,0,3,GID_W63),
                                        EndMember,
                                        StartMember,
                                            weights[6][4] = Integer(NULL,0,3,GID_W64),
                                        EndMember,
                                        StartMember,
                                            weights[6][5] = Integer(NULL,0,3,GID_W65),
                                        EndMember,
                                        StartMember,
                                            weights[6][6] = Integer(NULL,0,3,GID_W66),
                                        EndMember,
                                    EndObject,
                                EndMember,
                                StartMember,
                                    HGroupObject, Spacing(4),
                                        StartMember,
                                            Bias = Integer("Bias:",0,4,GID_BIAS),
                                        EndMember,
                                        StartMember,
                                            Div = Integer("Div:",1,4,GID_DIV),
                                        EndMember,
                                    EndObject,
                                EndMember,
                            EndObject, Weight(75),
                        EndMember,
                        StartMember,
                            VGroupObject, Spacing(4),
                                StartMember,
                                    XenButton("Load",GID_LOAD),
                                EndMember,
                                StartMember,
                                    XenButton("Save",GID_SAVE),
                                EndMember,
                                StartMember,
                                    XenButton("Clear",GID_CLEAR),
                                EndMember,
                                StartMember,
                                    XenButton("Convolute!",GID_OK),
                                EndMember,
                                StartMember,
                                    XenButton("Cancel",GID_CANCEL),
                                EndMember,
                            EndObject, Weight(10),
                        EndMember,
                    EndObject,
                EndMember,
            EndObject, /* MasterVGroup */
        EndObject; /* Window */

    if(Win) {
#ifdef DEBUG_MODE
        PDebug("\tSucceeded in creating window\n");
#endif

        for(i = 0; i < 7; i++) {
            for(j = 0; j < 7; j++) {
                SetGadgetAttrs( (struct Gadget *)weights[i][j], NULL, NULL,
                                STRINGA_LongVal, cargs->weights[i][j], TAG_DONE );
            }
        }
        SetGadgetAttrs( (struct Gadget *)Bias, NULL, NULL, STRINGA_LongVal, cargs->bias, TAG_DONE);
        SetGadgetAttrs( (struct Gadget *)Div, NULL, NULL, STRINGA_LongVal, cargs->div, TAG_DONE);
        SetGadgetAttrs( (struct Gadget *)Name, NULL, NULL, INFO_TextFormat, cargs->name, TAG_DONE);

        if( win = WindowOpen( Win ) ) {
#ifdef DEBUG_MODE
            PDebug("\tOpened window OK\n");
#endif
            Frq = FileReqObject,
                    ASLFR_Window, win,
                    ASLFR_SleepWindow, TRUE,
                    ASLFR_InitialDrawer, "PROGDIR:modules/convolutions",
                    ASLFR_InitialPattern,"~(#?.info)",
                  EndObject;
            GetAttr( WINDOW_SigMask, Win, &sigmask );

            while(!quit) {
                sig = Wait(sigmask | SIGBREAKF_CTRL_C | SIGBREAKF_CTRL_F);

                /*
                 *  Break signal
                 */

                if( sig & SIGBREAKF_CTRL_C ) {
                    quit = TRUE;
                    res = PERR_BREAK;
                }

                if( sig & SIGBREAKF_CTRL_F ) {
                    WindowToFront( win );
                    ActivateWindow( win );
                }

                /*
                 *  Gadget message
                 */

                if( sig & sigmask ) {
                    while(( rc = HandleEvent( Win )) != WMHI_NOMORE ) {
                        struct TagItem clrtable[] = { STRINGA_LongVal, 0, TAG_END };
                        struct TagItem nonametable[] = { INFO_TextFormat, (ULONG)"unnamed", TAG_END };
                        struct TagItem settable[] = {STRINGA_LongVal, 0, TAG_END };
                        struct TagItem frqloadtable[] = {ASLFR_DoSaveMode, FALSE, TAG_END };
                        struct TagItem newnametable[] = {INFO_TextFormat, NULL, TAG_END };
                        struct TagItem frqsavetable[] = {ASLFR_DoSaveMode, TRUE, TAG_END };
                        struct TagItem nametable[] = {INFO_TextFormat, NULL, TAG_END };
                        int id;

                        switch(rc) {
                            case WMHI_CLOSEWINDOW:
                            case GID_CANCEL:
                                res = PERR_CANCELED;
                                quit = TRUE;
                                WindowClose(Win);
                                break;

                            case GID_CLEAR:
                                WindowBusy(Win);
                                clrtable[0].ti_Data = 0;
                                SetGadgetAttrsA( (struct Gadget *)Bias, win, NULL, clrtable);
                                for(i = 0; i < 7; i++) {
                                    for(j = 0; j < 7; j++) {
                                        SetGadgetAttrsA( (struct Gadget *)weights[i][j], win,
                                                         NULL, clrtable );
                                        cargs->weights[i][j] = 0;
                                    }
                                }
                                clrtable[0].ti_Data = 1; /* For Divisor & Middle value. */

                                SetGadgetAttrsA( (struct Gadget *)weights[3][3], win,
                                                 NULL, clrtable );
                                cargs->weights[3][3] = 1;

                                clrtable[0].ti_Data = 1; /* For Divisor */
                                SetGadgetAttrsA( (struct Gadget *)Div, win, NULL, clrtable);
                                SetGadgetAttrsA( (struct Gadget *) Name, win, NULL, nonametable);
                                WindowReady(Win);
                                break;

                            case GID_LOAD:
                                SetAttrsA( Frq, frqloadtable );
                                if(DoRequest( Frq ) == FRQ_OK) {
                                    GetAttr( FRQ_Path, Frq, (ULONG *)&name );
                                    WindowBusy(Win);
                                    if(LoadConvFilter( xd, name, cargs ) == PERR_OK ) {
                                        for(i = 0; i < 7; i++) {
                                            for(j = 0; j < 7; j++) {
                                                settable[0].ti_Data = cargs->weights[i][j];
                                                SetGadgetAttrsA( (struct Gadget *)weights[i][j], win,
                                                    NULL, settable );
                                            }
                                        }
                                        settable[0].ti_Data = cargs->bias;
                                        SetGadgetAttrsA( (struct Gadget *)Bias, win, NULL, settable);
                                        settable[0].ti_Data = cargs->div;
                                        SetGadgetAttrsA( (struct Gadget *)Div, win, NULL, settable);
                                        GetAttr( FRQ_File, Frq, (ULONG *) &newnametable[0].ti_Data );
                                        SetGadgetAttrsA( (struct Gadget *) Name, win, NULL, newnametable);
                                    }
                                    WindowReady(Win);
                                }
                                break;

                            case GID_SAVE:
                                SetAttrsA( Frq, frqsavetable );
                                if(DoRequest(Frq) == FRQ_OK) {
                                    WindowBusy(Win);
                                    GetAttr( FRQ_Path, Frq, (ULONG *)&name );
                                    for(i = 0; i < 7; i++) {
                                        for(j = 0; j < 7; j++) {
                                            GetAttr( STRINGA_LongVal, weights[i][j], (ULONG *) &(cargs->weights[i][j]) );
                                        }
                                    }
                                    GetAttr( STRINGA_LongVal, Bias, (ULONG *) &(cargs->bias));
                                    GetAttr( STRINGA_LongVal, Div, (ULONG *) &(cargs->div));
                                    SaveConvFilter( xd, name, cargs );
                                    GetAttr( FRQ_File, Frq, &nametable[0].ti_Data );
                                    SetGadgetAttrsA( (struct Gadget *) Name, win, NULL, nametable);
                                    WindowReady(Win);
                                }
                                break;

                            case GID_OK:
                                GetAttr( STRINGA_LongVal, Bias, (ULONG *) &(cargs->bias));
                                GetAttr( STRINGA_LongVal, Div, (ULONG *) &(cargs->div));
                                GetAttr( WINDOW_Bounds, Win, (ULONG *) &(cargs->winpos) );
                                if( cargs->div != 0 ) {
                                    WindowClose(Win);
                                    for(i = 0; i < 7; i++) {
                                        for(j = 0; j < 7; j++) {
                                            GetAttr( STRINGA_LongVal, weights[i][j], (ULONG *) &(cargs->weights[i][j]) );
                                        }
                                    }
                                    GetAttr( STRINGA_LongVal, Bias, (ULONG *) &(cargs->bias));
                                    GetAttr( STRINGA_LongVal, Div, (ULONG *) &(cargs->div));
                                    strncpy( cargs->name, name, 40 );
                                    res = PERR_OK;
                                    quit = TRUE;
                                }
                                break;

                            default:

                                if(rc >= OPR(0) && rc <= OPR(1000)) { /* It's a default opr */
                                    WindowBusy(Win);
                                    for(id = 0; presets[id].id != rc && presets[id].id != 0L; id++); /* Fetch correct area. */
                                    if(presets[id].id) {
                                        for(i = 0; i < 7; i++) {
                                            for(j = 0; j < 7; j++) {
                                                settable[0].ti_Data = cargs->weights[i][j] = presets[id].weights[i][j];
                                                SetGadgetAttrsA( (struct Gadget *)weights[i][j], win,
                                                    NULL, settable );
                                            }
                                        }
                                        settable[0].ti_Data = cargs->bias = presets[id].bias;
                                        SetGadgetAttrsA( (struct Gadget *)Bias, win, NULL, settable);
                                        settable[0].ti_Data = cargs->div = presets[id].div;
                                        SetGadgetAttrsA( (struct Gadget *)Div,  win, NULL, settable);
                                        newnametable[0].ti_Data = name = (ULONG)presets[id].name;
                                        SetGadgetAttrsA( (struct Gadget *)Name, win, NULL, newnametable);
                                    }
#ifdef DEBUG_MODE
                                    else {
                                        PDebug("Serious software error!!!\n");
                                    }
#endif
                                    WindowReady(Win);
                                }
                                break;

                        } /* switch */
                    } /* while */
                } /* sig & sigmask */

            } /* while(!quit) */

            DisposeObject(Win);
            DisposeObject(Frq);
        } else {
#ifdef DEBUG_MODE
            PDebug("\tFailed to get window\n");
#endif
            DisposeObject(Win);
            return PERR_WONTOPEN;
        }
    } else {
#ifdef DEBUG_MODE
        PDebug("\tFailed to get window object\n");
#endif
        return PERR_WONTOPEN;
    }

    return res;
}
Example #30
0
EFFECTEXEC(frame,tags,PPTBase,EffectBase)
{
    ULONG sig, rc, *args;
    BOOL quit = FALSE, reallyrexx = FALSE;
    FRAME *newframe = NULL, *with = NULL;
    struct gFixRectMessage gfr = {0};
    ULONG fc, wc;
    struct Values *av;

    D(bug(MYNAME": Exec()\n"));

    /*
     *  Defaults
     */
    v.ratio = 128;
    v.method = Direct;
    v.bounds.Top = v.bounds.Left = ~0;
    v.bounds.Width = 200; v.bounds.Height = 100;
    v.tile = FALSE;

    if( av = GetOptions(MYNAME) ) {
        v = *av;
    }

    /*
     *  Copy to local variables
     */

    BGUIBase        = PPTBase->lb_BGUI;
    IntuitionBase   = (struct IntuitionBase *)PPTBase->lb_Intuition;
    DOSBase         = PPTBase->lb_DOS;
    SysBase         = PPTBase->lb_Sys;

    /*
     *  Parse AREXX message, which has to exist.
     *  BUG: If necessary, should wait for D&D from the main window.
     *  BUG: Should make sanity checks!
     */

    args = (ULONG *) TagData( PPTX_RexxArgs, tags );

    if( args ) {

        /* WITH */
        if( args[0] ) {
            with = FindFrame( (ID) PEEKL(args[0]) );
            if(!with) {
                SetErrorMsg(frame,"Unknown frame ID for WITH parameter");
                return NULL;
            }
        }

        /* TOP */
        if( args[1] ) {
            gfr.y = (WORD) PEEKL(args[1]);
            reallyrexx = TRUE;
        }

        /* LEFT */
        if( args[2] ) {
            gfr.x = (WORD) PEEKL(args[2]);
            reallyrexx = TRUE;
        }

        /* METHOD */
        if( args[3] ) {
            int i;

            for( i = 0; method_labels[i]; i++ ) {
                if(stricmp( method_labels[i], (char *)args[3] ) == 0 ) {
                    v.method = i;
                    reallyrexx = TRUE;
                    break;
                }
            }
        }

        /* RATIO */
        if( v.method == Mix ) {
            if( args[4] ) {
                v.ratio = PEEKL( args[4] );
            } else {
                SetErrorCode(frame,PERR_INVALIDARGS);
            }
        }

        /* TILE */
        if( args[5] ) {
            v.tile = TRUE;
        } else {
            v.tile = FALSE;
        }

    } else {
        SetErrorMsg(frame,"Image compositing can be used with Drag&Drop (or REXX) only");
        return NULL;
    }

    /*
     *  Make some sanity checks
     */

    if( frame->pix->width < with->pix->width ||
        frame->pix->height < with->pix->height ) {
            SetErrorMsg(frame,"You cannot composite a larger picture on a smaller one!");
            return NULL;
        }

    fc = frame->pix->colorspace;
    wc = with->pix->colorspace;

    if( ! (wc == fc || (fc == CS_ARGB && wc == CS_RGB) || (fc == CS_RGB && wc == CS_ARGB ))) {
        SetErrorMsg(frame, "Only images of the same color space can be composited");
        return NULL;
    }

    gfr.dim.Left   = 0;
    gfr.dim.Top    = 0;
    gfr.dim.Height = with->pix->height;
    gfr.dim.Width  = with->pix->width;

    /*
     *  Open window and start parsing
     */

    if( reallyrexx == FALSE ) {
        if( GimmeWindow(frame, with, PPTBase) ) {
            ULONG sigmask, gimask = 0L;

            GetAttr( WINDOW_SigMask, Win, &sigmask );

            StartInput(frame, GINP_FIXED_RECT, (struct PPTMessage *) &gfr);

            gimask = (1 << PPTBase->mport->mp_SigBit);

            while( !quit ) {
                sig = Wait( sigmask|gimask|SIGBREAKF_CTRL_C|SIGBREAKF_CTRL_F );

                if( sig & SIGBREAKF_CTRL_C ) {
                    D(bug("BREAK!\n"));
                    SetErrorCode( frame, PERR_BREAK );
                    quit = TRUE;
                    break;
                }

                if( sig & SIGBREAKF_CTRL_F ) {
                    WindowToFront(win);
                    ActivateWindow(win);
                }

                if( sig & gimask ) {
                    struct gFixRectMessage *pmsg;

                    if(pmsg = (struct gFixRectMessage *)GetMsg( PPTBase->mport )) {
                        if( pmsg->msg.code == PPTMSG_FIXED_RECT ) {
                            D(bug("User picked a point @ (%d,%d)\n",pmsg->x, pmsg->y));
                            gfr.x = pmsg->x; gfr.y = pmsg->y;
                            // SetGadgetAttrs( ( struct Gadget *)OKButton, win, NULL, GA_Disabled, FALSE );
                        }
                        ReplyMsg( (struct Message *)pmsg );
                    }
                }

                if( sig & sigmask ) {
                    while( (rc = HandleEvent( Win )) != WMHI_NOMORE ) {
                        ULONG t;

                        switch(rc) {
                            case GID_OK:
                                GetAttr( CYC_Active, Method, (ULONG *)&v.method );
                                GetAttr( SLIDER_Level, Ratio, &v.ratio );

                                /*
                                 *  Save the window attributes for later retrieval.
                                 */

                                GetAttr( WINDOW_Bounds, Win, (ULONG *) &v.bounds );
                                GetAttr( GA_Selected, Tile, &t );

                                StopInput( frame );
                                v.tile = (BOOL) t;

                                WindowClose(Win);
                                newframe = DoComposite( frame, with, &gfr, v.method,
                                                        (WORD) v.ratio, v.tile, PPTBase );
                                quit = TRUE;
                                break;

                            case GID_CANCEL:
                                quit = TRUE;
                                StopInput( frame );
                                break;
                        }
                    }
                }
            }
        }
    } else {
        /* gfr is already set up */
        newframe = DoComposite( frame, with, &gfr,
                                v.method, (WORD) v.ratio, v.tile,
                                PPTBase );
    }

    if(Win) DisposeObject(Win);

    if( newframe ) {
        PutOptions( MYNAME, &v, sizeof(struct Values) );
    }

    D(bug("Returning %08X...\n",newframe));
    return newframe;
}