repo
string
commit
string
message
string
diff
string
rgee/HFOSS-Dasher
e5ee6fe14f733b19b203200038f53f42160a90c8
Made file loading actually work consistently. Added alternative usage pattern for Word Generators. Updated documentation on both Game Module and Word Generators
diff --git a/Src/DasherCore/FileWordGenerator.cpp b/Src/DasherCore/FileWordGenerator.cpp index fe9fbd6..60601c8 100644 --- a/Src/DasherCore/FileWordGenerator.cpp +++ b/Src/DasherCore/FileWordGenerator.cpp @@ -1,55 +1,67 @@ #include "FileWordGenerator.h" using namespace Dasher; bool CFileWordGenerator::Generate() { if(!m_sFileHandle.is_open()) m_sFileHandle.open("test_text.txt"); m_uiPos = 0; m_sGeneratedString.clear(); if(m_sFileHandle.good()) { std::getline(m_sFileHandle, m_sGeneratedString); + FindNextWord(); return true; } else { return false; } } std::string CFileWordGenerator::GetPath() { return m_sPath; } std::string CFileWordGenerator::GetFilename() { return m_sPath.substr(m_sPath.rfind("/")); } std::string CFileWordGenerator::GetNextWord() { + std::string result = m_sCurrentWord; + FindNextWord(); + + return result; +} + +void CFileWordGenerator::FindNextWord() { std::string result; // We are at the end of the buffer. if(m_uiPos >= m_sGeneratedString.length()) { // Attempt to reload the buffer. if(!Generate()) { // If file IO fails, return empty. result = ""; - return result; + m_sCurrentWord = result; } } size_t found = m_sGeneratedString.substr(m_uiPos).find(" "); // If there are no space characters. if(found != string::npos) { result = m_sGeneratedString.substr(m_uiPos, found); m_uiPos += (found + 1); } else { result = m_sGeneratedString.substr(m_uiPos); } - - return result; + m_sCurrentWord = result; +} + +CWordGeneratorBase& CFileWordGenerator::operator++() { + GetNextWord(); + return *this; } diff --git a/Src/DasherCore/FileWordGenerator.h b/Src/DasherCore/FileWordGenerator.h index f024b4e..1c73923 100644 --- a/Src/DasherCore/FileWordGenerator.h +++ b/Src/DasherCore/FileWordGenerator.h @@ -1,108 +1,139 @@ #ifndef __FileWordGenerator_h__ #define __FileWordGenerator_h__ #include <string> #include <iostream> #include <fstream> using namespace std; #include "WordGeneratorBase.h" #include "DasherInterfaceBase.h" namespace Dasher { /** * This class implements the Word Generator interface. This means * that after construction, your primary method of retrieving words * will be calling GetNextWord(). For specifics on Word Generators, * see CWordGeneratorBase. * * This class specifically reads words from a given file. Files ARE * kept open for the lifetime of this object and the size of the file * should not pose an issue. * * However, if you read in a file that has unreasonably long lines, * the behavior is undefined as you may cause the file to be read in all * at once. */ class CFileWordGenerator : public CWordGeneratorBase { public: - CFileWordGenerator(std::string path, int regen) - // This path is set manually for now debug/dev purposes. -rgee - : m_sPath("~/Desktop/test_text.txt"), - CWordGeneratorBase(regen) + CFileWordGenerator(std::string sPath, int iRegen) + : m_sPath(sPath), + m_sCurrentWord(""), + CWordGeneratorBase(iRegen) {Generate();} - CFileWordGenerator(std::string path) - : m_sPath("~/Desktop/test_text.txt"), + CFileWordGenerator(std::string sPath) + : m_sPath(sPath), + m_sCurrentWord(""), CWordGeneratorBase(0) {Generate();} virtual ~CFileWordGenerator() { m_sFileHandle.close(); } /** - * The generator function. In this implementation, it reads from a file to produce strings. - * In this implementation, failure means file io has failed for some - * reason. + * The generator function. In this implementation, it reads from a + * file to produce strings.In this implementation, failure means file + * io has failed for some reason. * @see CWordGeneratorBase::Generate */ virtual bool Generate(); /** * Returns the next word that was read * @return The next word in the word generator model if there is one. * Otherwise, returns an empty string. */ virtual std::string GetNextWord(); /** * File path getter * @return The path to the file this generator reads from. */ std::string GetPath(); /** * File name getter * @return The actual name of the file being read from */ std::string GetFilename(); - /** - * Checks if there are any words left to produce. - * @return true if there are words left, false otherwise + * Prefix increment operator. + * + * Moves the generator one word ahead. */ - bool WordsLeft() { return m_bWordsLeft; } + virtual CWordGeneratorBase& operator++(); + + private: +/* --------------------------------------------------------------------- + * Private Methods + * --------------------------------------------------------------------- + */ + + /** + * Find the next word in the generated string buffer. + * This does NOT return that string, which is why this is not a public + * facing method. It only updates the current string to be presented. + * + * @warning Ensure that this is called whenever m_sGeneratedString is + * remade or whenever the current word is actually presented + * to a client. + */ + void FindNextWord(); + + +/* --------------------------------------------------------------------- + * Member Variables + * --------------------------------------------------------------------- + */ + + /** + * The current word we're looking at. This is the next word that + * will be returned when GetNextWord is called. + */ + std::string m_sCurrentWord; + /** * The string that has been generated. */ std::string m_sGeneratedString; /** * The path to the file this generator reads from. */ std::string m_sPath; /** * The position we're currently reading from in the string. */ size_t m_uiPos; /** * Flag for whether there are words left in this model. */ bool m_bWordsLeft; /** * The input stream that acts as the handle to the underlying file. */ ifstream m_sFileHandle; }; } #endif diff --git a/Src/DasherCore/GameModule.cpp b/Src/DasherCore/GameModule.cpp index cefbdba..81a5bc9 100644 --- a/Src/DasherCore/GameModule.cpp +++ b/Src/DasherCore/GameModule.cpp @@ -1,116 +1,131 @@ #include "GameModule.h" using namespace Dasher; void CGameModule::HandleEvent(Dasher::CEvent *pEvent) { switch(pEvent->m_iEventType) { case EV_EDIT: { CEditEvent* evt = static_cast<CEditEvent*>(pEvent); switch(evt->m_iEditType) { // Added a new character (Stepped one node forward) case 1: // Check if the typed character is correct - if(!evt->m_sText.compare(m_sTargetString.substr(m_stCurrentStringPos + 1, 1))) { + if(CharacterFound(evt)) { // Check if we've reached the end of a chunk - if((m_stCurrentStringPos) == m_sTargetString.length()) { + if((m_stCurrentStringPos) == m_sTargetString.length() - 2) { GenerateChunk(); } else { ++m_stCurrentStringPos; } } break; // Removed a character (Stepped one node back) case 0: g_pLogger->Log("Removed a character: " + evt->m_sText); break; default: break; } break; } case EV_TEXTDRAW: { CTextDrawEvent *evt = static_cast<CTextDrawEvent*>(pEvent); // Check whether the text that was drawn is the current target character. - if(!m_sTargetString.substr(m_stCurrentStringPos + 1, 1).compare(evt->m_sDisplayText)) { - + if(CharacterFound(evt)) { //the x and y coordinates (in Dasher coords) of the target node evt->m_pDasherView->Screen2Dasher(evt->m_iX, evt->m_iY, m_iTargetX, m_iTargetY); } } break; default: break; } return; } +bool CGameModule::CharacterFound(CEditEvent* pEvent) { + if(m_stCurrentStringPos == 0) { + return (!pEvent->m_sText.compare(m_sTargetString.substr(m_stCurrentStringPos, 1))); + } else { + return (!pEvent->m_sText.compare(m_sTargetString.substr(m_stCurrentStringPos + 1, 1))); + } +} + +bool CGameModule::CharacterFound(CTextDrawEvent* pEvent) { + if(m_stCurrentStringPos == 0) { + return (!pEvent->m_sDisplayText.compare(m_sTargetString.substr(m_stCurrentStringPos, 1))); + } else { + return (!pEvent->m_sDisplayText.compare(m_sTargetString.substr(m_stCurrentStringPos + 1, 1))); + } +} + bool CGameModule::DecorateView(CDasherView *pView) { screenint screenTargetX, screenTargetY; pView->Dasher2Screen(m_iTargetX, m_iTargetY, screenTargetX, screenTargetY); // Top Line screenint x[2] = {screenTargetX + m_iCrosshairExtent, screenTargetX - m_iCrosshairExtent}; screenint y[2] = {screenTargetY - m_iCrosshairExtent, screenTargetY - m_iCrosshairExtent}; pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Right Line x = {screenTargetX - m_iCrosshairExtent, screenTargetX - m_iCrosshairExtent}; y = {screenTargetY - m_iCrosshairExtent, screenTargetY + m_iCrosshairExtent}; pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Left Line x = {screenTargetX + m_iCrosshairExtent, screenTargetX + m_iCrosshairExtent}; y = {screenTargetY - m_iCrosshairExtent, screenTargetY + m_iCrosshairExtent}; pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Bottom Line x = {screenTargetX + m_iCrosshairExtent, screenTargetX - m_iCrosshairExtent}; y = {screenTargetY + m_iCrosshairExtent, screenTargetY + m_iCrosshairExtent}; pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Vertical Crosshair Line x = {screenTargetX, screenTargetX}; y = {screenTargetY + m_iCrosshairCrosslineLength, screenTargetY - m_iCrosshairCrosslineLength}; pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Horizontal Crosshair Line x = {screenTargetX + m_iCrosshairCrosslineLength, screenTargetX - m_iCrosshairCrosslineLength}; y = {screenTargetY, screenTargetY}; pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); return true; } //CDasherNode CGameModule::StringToNode(std::string sText) { // //} std::string CGameModule::GetTypedTarget() { return m_sTargetString.substr(0, m_stCurrentStringPos - 1); } std::string CGameModule::GetUntypedTarget() { return m_sTargetString.substr(m_stCurrentStringPos); } void CGameModule::GenerateChunk() { m_stCurrentStringPos = 0; m_sTargetString.clear(); for(int i = 0; i < m_iTargetChunkSize; i++) { m_sTargetString += m_pWordGenerator->GetNextWord(); m_sTargetString += " "; } } diff --git a/Src/DasherCore/GameModule.h b/Src/DasherCore/GameModule.h index a76686d..c4caca1 100644 --- a/Src/DasherCore/GameModule.h +++ b/Src/DasherCore/GameModule.h @@ -1,189 +1,212 @@ // GameModule.h #ifndef __GameModule_h__ #define __GameModule_h__ #include <string> #include <cstring> using namespace std; #include "DasherScreen.h" #include "DasherModel.h" #include "DasherModule.h" #include "DasherNode.h" #include "DasherView.h" #include "DasherTypes.h" #include "DasherInterfaceBase.h" #include "WordGeneratorBase.h" namespace Dasher { /** * This Dasher Module encapsulates all game mode logic. In game mode, users will be given * a target string to type as well as visual feedback for their progress and a helpful * arrow to guide them in the right path through the dasher model. * * The way target strings will be displayed and reasoned about in code is in terms * of chunks. Chunks represent the collection of strings that is displayed at once * on the screen. After typing all the words in a given chunk, a new chunk of size * m_iTargetChunkSize is gotten from the word generator and displayed. * * This class handles logic and drawing code with respect to the above. */ class CGameModule : public CDasherModule { public: CGameModule(Dasher::CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CDasherInterfaceBase *pInterface, ModuleID_t iID, const char *szName, std::vector<int> vEvents, CWordGeneratorBase* pWordGenerator) : m_iCrosshairColor(135), m_iCrosshairNumPoints(2), m_iCrosshairExtent(25), m_iCrosshairCrosslineLength(50), m_iTargetChunkSize(3), m_pWordGenerator(pWordGenerator), CDasherModule(pEventHandler, pSettingsStore, iID, 0, szName, vEvents) { m_pInterface = pInterface; //TODO REMOVE THIS!!! if(m_pWordGenerator == NULL) g_pLogger->Log("Word generator creation FAILED"); GenerateChunk(); if(m_sTargetString == "") m_sTargetString = "My name is julian."; m_stCurrentStringPos = 0; } virtual ~CGameModule() {}; /** * Gets the typed portion of the target string * @return The string that represents the current word(s) that have not been typed */ std::string GetTypedTarget(); /** * Gets the portion of the target string that has yet to be completed * @return The string that represents the current word(s) that have been typed */ std::string GetUntypedTarget(); /** * Draws Game Mode specific visuals to the screen. * @param pView The Dasher View to be modified * @return True if the view was modified, false otherwise. */ bool DecorateView(CDasherView *pView); /** * Handle events from the event processing system * @param pEvent The event to be processed. */ virtual void HandleEvent(Dasher::CEvent *pEvent); private: +/* --------------------------------------------------------------------- + * Private Methods + * --------------------------------------------------------------------- + */ + + /** + * Checks whether the character associated with the given event + * is the character we're currently targetting. A convenience method + * that encapsulates + localizes some of the string manipulation logic. + * + * @param pEvent An edit event. + * @return True if the character associated with the given event + * is equal to the character we're looking for. False otherwise. + */ + bool CharacterFound(CEditEvent* pEvent); + + /** + * @see CharacterFound + */ + bool CharacterFound(CTextDrawEvent* pEvent); /** * Helper function for generating (Or regenerating) a new chunk. * @warning This will destroy the previous chunk. Only use when you * need to grab an entirely new chunk to display. */ void GenerateChunk(); /** * Get the distance of a given point (in Dasher Coordinates) from the origin. * * @param xCoord - the x coordinate of the point * @param yCoord - the y coordinate of the point * */ myint DistanceFromOrigin(myint xCoord, myint yCoord); - /** - * Searches for the dasher node under the current root that represents the desired string - * @param text The string to search for - * @return The node representing the string parameter - */ - //Dasher::CDasherNode StringToNode(std::string sText); + +/* --------------------------------------------------------------------- + * Member Variables + * --------------------------------------------------------------------- + */ + /** * Pointer to the object that encapsulates the word generation * algorithm being used. */ CWordGeneratorBase* m_pWordGenerator; /** * The last node the user typed. */ CDasherNode *pLastTypedNode; /** * The next node (character) the user must type. */ CDasherNode *pNextTargetNode; /** * The target string the user must type. */ std::string m_sTargetString; /** * The current position in the string. * Stored as a size_t to easily use substrings to determine what's been typed and what hasn't. */ size_t m_stCurrentStringPos; /** * The dasher interface. */ CDasherInterfaceBase *m_pInterface; /** * The target x coordinate for the crosshair to point to. */ myint m_iTargetX; /** * The target y coordinate for the crosshair to point to. */ myint m_iTargetY; + + + /* --------------------------------------------------------------------- * Constants * --------------------------------------------------------------------- */ /** * The color (in Dasher colors) to make the crosshair. */ const int m_iCrosshairColor; /** * The number of points that the crosshair's lines pass through. */ const int m_iCrosshairNumPoints; /** * The side length (in pixels) of the crosshair's square portion. */ const int m_iCrosshairExtent; /** * The length of the lines comprising the crosshair's * "cross". */ const int m_iCrosshairCrosslineLength; /** * The number of words displayed at once as a target for the user * to type. */ const int m_iTargetChunkSize; }; } #endif diff --git a/Src/DasherCore/WordGeneratorBase.h b/Src/DasherCore/WordGeneratorBase.h index 24f4df6..ef2ba2b 100644 --- a/Src/DasherCore/WordGeneratorBase.h +++ b/Src/DasherCore/WordGeneratorBase.h @@ -1,70 +1,84 @@ #ifndef __WordGeneratorBase_h__ #define __WordGeneratorBase_h__ #include <string> using namespace std; namespace Dasher { /** * The base class for all word generators. Word generators encapsulate * logic for simply generating words based on implementation-specific * conditions. Currently, this is being used to wrap GameMode's simple * text-file reading mechanism, but another generator can easily be * written that selects words based on a function of the current value * of the Sri Lankan rupee and the amount of twitter feeds regarding * the winter olympics, for example. * * * A typical use case for any class deriving from CWordGeneratorBase * would be the following: * 1) Construct the object (providing any implementation-specific params) * - The words will be generated on construction. * * 2) To retrieve a word, simply call GetNextWord. This will continue * until the specific implementation determines that there are no * more words for any reason. When there are no more, GetNextWord * returns the empty string. + * + * After construcing the object, you also have the option of a secondary + * usage method: + * 1) Construc the object as normal + * + * 2) Use the PREFIX increment operator to ready up the next word + * + * 3) Call GetNextWord. */ class CWordGeneratorBase { public: CWordGeneratorBase(int regen) : m_iRegenTime(regen), m_bWordsReady(false) {} virtual ~CWordGeneratorBase() { } /** * Gets a single word based on the generation rules. * @pre { Generate must have been called at least once. } * @return The next string from this generator */ virtual std::string GetNextWord() = 0; /** + * -- NOT YET IMPLEMENTED -- * Gets the previous word in the generated string based on generation rules. * @pre { Generate must have been called at least once. } * @return The previous string from this generator */ - //virtual std::string GetPrevWord() = 0; + //virtual std::string GetPreviousWord() = 0; + + /** + * All word generators must provide the prefix increment operator. + */ + virtual CWordGeneratorBase& operator++() = 0; protected: /** * Generate the words based on the generation rules * @return True if the generation succeeded, false if not. - * @warning The return value of this function should always be checked in case it's using files - * or other solutions that can fail. + * @warning The return value of this function should always be checked + * in case it's using files or other solutions that can fail. */ virtual bool Generate() = 0; /** * The time in seconds after which a generator should regenerate. */ int m_iRegenTime; /** * A boolean representing whether the words have been generated yet. */ bool m_bWordsReady; }; } #endif
rgee/HFOSS-Dasher
c7f08546b709a24eb045e165f9d4344793f85cb4
Added usage documentation to Word Generator base class and File Word Generator
diff --git a/Src/DasherCore/FileWordGenerator.h b/Src/DasherCore/FileWordGenerator.h index d10ff3e..f024b4e 100644 --- a/Src/DasherCore/FileWordGenerator.h +++ b/Src/DasherCore/FileWordGenerator.h @@ -1,92 +1,108 @@ #ifndef __FileWordGenerator_h__ #define __FileWordGenerator_h__ #include <string> #include <iostream> #include <fstream> using namespace std; #include "WordGeneratorBase.h" #include "DasherInterfaceBase.h" namespace Dasher { + + +/** + * This class implements the Word Generator interface. This means + * that after construction, your primary method of retrieving words + * will be calling GetNextWord(). For specifics on Word Generators, + * see CWordGeneratorBase. + * + * This class specifically reads words from a given file. Files ARE + * kept open for the lifetime of this object and the size of the file + * should not pose an issue. + * + * However, if you read in a file that has unreasonably long lines, + * the behavior is undefined as you may cause the file to be read in all + * at once. + */ class CFileWordGenerator : public CWordGeneratorBase { public: CFileWordGenerator(std::string path, int regen) // This path is set manually for now debug/dev purposes. -rgee : m_sPath("~/Desktop/test_text.txt"), CWordGeneratorBase(regen) {Generate();} CFileWordGenerator(std::string path) : m_sPath("~/Desktop/test_text.txt"), CWordGeneratorBase(0) {Generate();} virtual ~CFileWordGenerator() { m_sFileHandle.close(); } /** * The generator function. In this implementation, it reads from a file to produce strings. * In this implementation, failure means file io has failed for some * reason. * @see CWordGeneratorBase::Generate */ virtual bool Generate(); /** * Returns the next word that was read * @return The next word in the word generator model if there is one. * Otherwise, returns an empty string. */ virtual std::string GetNextWord(); /** * File path getter * @return The path to the file this generator reads from. */ std::string GetPath(); /** * File name getter * @return The actual name of the file being read from */ std::string GetFilename(); /** * Checks if there are any words left to produce. * @return true if there are words left, false otherwise */ bool WordsLeft() { return m_bWordsLeft; } private: /** * The string that has been generated. */ std::string m_sGeneratedString; /** * The path to the file this generator reads from. */ std::string m_sPath; /** * The position we're currently reading from in the string. */ size_t m_uiPos; /** * Flag for whether there are words left in this model. */ bool m_bWordsLeft; /** * The input stream that acts as the handle to the underlying file. */ ifstream m_sFileHandle; }; } #endif diff --git a/Src/DasherCore/WordGeneratorBase.h b/Src/DasherCore/WordGeneratorBase.h index 60b47e1..24f4df6 100644 --- a/Src/DasherCore/WordGeneratorBase.h +++ b/Src/DasherCore/WordGeneratorBase.h @@ -1,58 +1,70 @@ #ifndef __WordGeneratorBase_h__ #define __WordGeneratorBase_h__ #include <string> using namespace std; namespace Dasher { /** * The base class for all word generators. Word generators encapsulate * logic for simply generating words based on implementation-specific * conditions. Currently, this is being used to wrap GameMode's simple * text-file reading mechanism, but another generator can easily be * written that selects words based on a function of the current value * of the Sri Lankan rupee and the amount of twitter feeds regarding * the winter olympics, for example. + * + * + * A typical use case for any class deriving from CWordGeneratorBase + * would be the following: + * 1) Construct the object (providing any implementation-specific params) + * - The words will be generated on construction. + * + * 2) To retrieve a word, simply call GetNextWord. This will continue + * until the specific implementation determines that there are no + * more words for any reason. When there are no more, GetNextWord + * returns the empty string. */ class CWordGeneratorBase { public: - CWordGeneratorBase(int regen) : m_iRegenTime(regen), m_bWordsReady(false) {} + CWordGeneratorBase(int regen) : m_iRegenTime(regen), m_bWordsReady(false) + {} virtual ~CWordGeneratorBase() { } /** * Gets a single word based on the generation rules. * @pre { Generate must have been called at least once. } * @return The next string from this generator */ virtual std::string GetNextWord() = 0; /** * Gets the previous word in the generated string based on generation rules. * @pre { Generate must have been called at least once. } * @return The previous string from this generator */ //virtual std::string GetPrevWord() = 0; protected: /** * Generate the words based on the generation rules * @return True if the generation succeeded, false if not. * @warning The return value of this function should always be checked in case it's using files * or other solutions that can fail. */ virtual bool Generate() = 0; /** * The time in seconds after which a generator should regenerate. */ int m_iRegenTime; /** * A boolean representing whether the words have been generated yet. */ bool m_bWordsReady; }; } #endif
rgee/HFOSS-Dasher
2e78055831905db8e66f2a18d49f7f17ccea60c8
Made generate now private. Implementation classes now responsible for when and how they generate/regenerate.
diff --git a/Src/DasherCore/WordGeneratorBase.h b/Src/DasherCore/WordGeneratorBase.h index 857816a..60b47e1 100644 --- a/Src/DasherCore/WordGeneratorBase.h +++ b/Src/DasherCore/WordGeneratorBase.h @@ -1,57 +1,58 @@ #ifndef __WordGeneratorBase_h__ #define __WordGeneratorBase_h__ #include <string> using namespace std; namespace Dasher { /** * The base class for all word generators. Word generators encapsulate * logic for simply generating words based on implementation-specific * conditions. Currently, this is being used to wrap GameMode's simple * text-file reading mechanism, but another generator can easily be * written that selects words based on a function of the current value * of the Sri Lankan rupee and the amount of twitter feeds regarding * the winter olympics, for example. */ class CWordGeneratorBase { public: CWordGeneratorBase(int regen) : m_iRegenTime(regen), m_bWordsReady(false) {} virtual ~CWordGeneratorBase() { } /** * Gets a single word based on the generation rules. * @pre { Generate must have been called at least once. } * @return The next string from this generator */ virtual std::string GetNextWord() = 0; /** * Gets the previous word in the generated string based on generation rules. * @pre { Generate must have been called at least once. } * @return The previous string from this generator */ //virtual std::string GetPrevWord() = 0; +protected: /** * Generate the words based on the generation rules * @return True if the generation succeeded, false if not. * @warning The return value of this function should always be checked in case it's using files * or other solutions that can fail. */ virtual bool Generate() = 0; -protected: + /** * The time in seconds after which a generator should regenerate. */ int m_iRegenTime; /** * A boolean representing whether the words have been generated yet. */ bool m_bWordsReady; }; } #endif
rgee/HFOSS-Dasher
4495725816c595a18f4aaa6a5e94ab7976dd4ae4
Made file loader workflow more logical. Details to be added to documentation. Still does not work after first 3 words.
diff --git a/Src/DasherCore/FileWordGenerator.cpp b/Src/DasherCore/FileWordGenerator.cpp index 22ae34d..fe9fbd6 100644 --- a/Src/DasherCore/FileWordGenerator.cpp +++ b/Src/DasherCore/FileWordGenerator.cpp @@ -1,59 +1,55 @@ #include "FileWordGenerator.h" using namespace Dasher; -bool CFileWordGenerator::Generate() { - g_pLogger->Log("About to open file"); - if(!m_bWordsReady) { - std::ifstream file_in("test_text.txt"); - string buffer; - while(!std::getline(file_in, buffer).eof()) - { - m_sGeneratedString += buffer; - } - file_in.close(); - g_pLogger->Log(m_sGeneratedString); - - m_uiPos = 0; +bool CFileWordGenerator::Generate() { + if(!m_sFileHandle.is_open()) + m_sFileHandle.open("test_text.txt"); + + + m_uiPos = 0; + m_sGeneratedString.clear(); + if(m_sFileHandle.good()) { + std::getline(m_sFileHandle, m_sGeneratedString); + return true; + } else { + return false; } - return true; } std::string CFileWordGenerator::GetPath() { return m_sPath; } std::string CFileWordGenerator::GetFilename() { return m_sPath.substr(m_sPath.rfind("/")); } -void CFileWordGenerator::SetSource(std::string newPath) { - m_sPath = newPath; - m_bWordsReady = false; - Generate(); -} - std::string CFileWordGenerator::GetNextWord() { + std::string result; - // Check if there are any spaces left in the file from the current - // position to the end. If not, we know we are either right before - // the last word or there are no more left. - size_t found = m_sGeneratedString.substr(m_uiPos).find(" "); - - if(found != string::npos) { - // If we're at the end of the string - if((m_uiPos + 1) == m_sGeneratedString.length()) { - return std::string(""); - }else { - // Grab the next word. - std::string result = m_sGeneratedString.substr(m_uiPos, found); - - // Set the current position to 1 after the space character. - // (i.e. The first letter of the next word.) - m_uiPos = found + 1; - + // We are at the end of the buffer. + if(m_uiPos >= m_sGeneratedString.length()) { + // Attempt to reload the buffer. + if(!Generate()) + { + // If file IO fails, return empty. + result = ""; return result; } + } + + size_t found = m_sGeneratedString.substr(m_uiPos).find(" "); + + // If there are no space characters. + if(found != string::npos) + { + result = m_sGeneratedString.substr(m_uiPos, found); + + m_uiPos += (found + 1); + } else { + result = m_sGeneratedString.substr(m_uiPos); } - return std::string(""); + + return result; } diff --git a/Src/DasherCore/FileWordGenerator.h b/Src/DasherCore/FileWordGenerator.h index 6bfa4ab..d10ff3e 100644 --- a/Src/DasherCore/FileWordGenerator.h +++ b/Src/DasherCore/FileWordGenerator.h @@ -1,85 +1,92 @@ #ifndef __FileWordGenerator_h__ #define __FileWordGenerator_h__ #include <string> #include <iostream> #include <fstream> using namespace std; #include "WordGeneratorBase.h" #include "DasherInterfaceBase.h" namespace Dasher { class CFileWordGenerator : public CWordGeneratorBase { public: CFileWordGenerator(std::string path, int regen) // This path is set manually for now debug/dev purposes. -rgee : m_sPath("~/Desktop/test_text.txt"), CWordGeneratorBase(regen) - {} + {Generate();} CFileWordGenerator(std::string path) : m_sPath("~/Desktop/test_text.txt"), CWordGeneratorBase(0) {Generate();} + + virtual ~CFileWordGenerator() { + m_sFileHandle.close(); + } + + /** * The generator function. In this implementation, it reads from a file to produce strings. + * In this implementation, failure means file io has failed for some + * reason. * @see CWordGeneratorBase::Generate */ virtual bool Generate(); /** * Returns the next word that was read * @return The next word in the word generator model if there is one. * Otherwise, returns an empty string. */ virtual std::string GetNextWord(); /** * File path getter * @return The path to the file this generator reads from. */ std::string GetPath(); /** * File name getter * @return The actual name of the file being read from */ std::string GetFilename(); - /** - * Sets the source file this generator reads from. - * @warning This method regenerates the word generator model and gets rid of the old data. - * @param newPath The path to the file to load from. - */ - void SetSource(std::string newPath); /** * Checks if there are any words left to produce. * @return true if there are words left, false otherwise */ bool WordsLeft() { return m_bWordsLeft; } private: /** * The string that has been generated. */ std::string m_sGeneratedString; /** * The path to the file this generator reads from. */ std::string m_sPath; /** * The position we're currently reading from in the string. */ size_t m_uiPos; /** * Flag for whether there are words left in this model. */ bool m_bWordsLeft; + + /** + * The input stream that acts as the handle to the underlying file. + */ + ifstream m_sFileHandle; }; } #endif diff --git a/Src/DasherCore/GameModule.cpp b/Src/DasherCore/GameModule.cpp index dc619c3..cefbdba 100644 --- a/Src/DasherCore/GameModule.cpp +++ b/Src/DasherCore/GameModule.cpp @@ -1,115 +1,116 @@ #include "GameModule.h" using namespace Dasher; void CGameModule::HandleEvent(Dasher::CEvent *pEvent) { switch(pEvent->m_iEventType) { case EV_EDIT: { CEditEvent* evt = static_cast<CEditEvent*>(pEvent); switch(evt->m_iEditType) { // Added a new character (Stepped one node forward) case 1: // Check if the typed character is correct if(!evt->m_sText.compare(m_sTargetString.substr(m_stCurrentStringPos + 1, 1))) { // Check if we've reached the end of a chunk - if((m_stCurrentStringPos + 1) == m_sTargetString.length()) { + if((m_stCurrentStringPos) == m_sTargetString.length()) { GenerateChunk(); } else { ++m_stCurrentStringPos; } } break; // Removed a character (Stepped one node back) case 0: g_pLogger->Log("Removed a character: " + evt->m_sText); break; default: break; } break; } case EV_TEXTDRAW: { CTextDrawEvent *evt = static_cast<CTextDrawEvent*>(pEvent); // Check whether the text that was drawn is the current target character. if(!m_sTargetString.substr(m_stCurrentStringPos + 1, 1).compare(evt->m_sDisplayText)) { //the x and y coordinates (in Dasher coords) of the target node evt->m_pDasherView->Screen2Dasher(evt->m_iX, evt->m_iY, m_iTargetX, m_iTargetY); } } break; default: break; } return; } bool CGameModule::DecorateView(CDasherView *pView) { screenint screenTargetX, screenTargetY; pView->Dasher2Screen(m_iTargetX, m_iTargetY, screenTargetX, screenTargetY); // Top Line screenint x[2] = {screenTargetX + m_iCrosshairExtent, screenTargetX - m_iCrosshairExtent}; screenint y[2] = {screenTargetY - m_iCrosshairExtent, screenTargetY - m_iCrosshairExtent}; pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Right Line x = {screenTargetX - m_iCrosshairExtent, screenTargetX - m_iCrosshairExtent}; y = {screenTargetY - m_iCrosshairExtent, screenTargetY + m_iCrosshairExtent}; pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Left Line x = {screenTargetX + m_iCrosshairExtent, screenTargetX + m_iCrosshairExtent}; y = {screenTargetY - m_iCrosshairExtent, screenTargetY + m_iCrosshairExtent}; pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Bottom Line x = {screenTargetX + m_iCrosshairExtent, screenTargetX - m_iCrosshairExtent}; y = {screenTargetY + m_iCrosshairExtent, screenTargetY + m_iCrosshairExtent}; pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Vertical Crosshair Line x = {screenTargetX, screenTargetX}; y = {screenTargetY + m_iCrosshairCrosslineLength, screenTargetY - m_iCrosshairCrosslineLength}; pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Horizontal Crosshair Line x = {screenTargetX + m_iCrosshairCrosslineLength, screenTargetX - m_iCrosshairCrosslineLength}; y = {screenTargetY, screenTargetY}; pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); return true; } //CDasherNode CGameModule::StringToNode(std::string sText) { // //} std::string CGameModule::GetTypedTarget() { return m_sTargetString.substr(0, m_stCurrentStringPos - 1); } std::string CGameModule::GetUntypedTarget() { return m_sTargetString.substr(m_stCurrentStringPos); } void CGameModule::GenerateChunk() { m_stCurrentStringPos = 0; m_sTargetString.clear(); for(int i = 0; i < m_iTargetChunkSize; i++) { m_sTargetString += m_pWordGenerator->GetNextWord(); + m_sTargetString += " "; } } diff --git a/Src/DasherCore/GameModule.h b/Src/DasherCore/GameModule.h index 646e41f..a76686d 100644 --- a/Src/DasherCore/GameModule.h +++ b/Src/DasherCore/GameModule.h @@ -1,191 +1,189 @@ // GameModule.h #ifndef __GameModule_h__ #define __GameModule_h__ #include <string> #include <cstring> using namespace std; #include "DasherScreen.h" #include "DasherModel.h" #include "DasherModule.h" #include "DasherNode.h" #include "DasherView.h" #include "DasherTypes.h" #include "DasherInterfaceBase.h" #include "WordGeneratorBase.h" namespace Dasher { /** * This Dasher Module encapsulates all game mode logic. In game mode, users will be given * a target string to type as well as visual feedback for their progress and a helpful * arrow to guide them in the right path through the dasher model. * * The way target strings will be displayed and reasoned about in code is in terms * of chunks. Chunks represent the collection of strings that is displayed at once * on the screen. After typing all the words in a given chunk, a new chunk of size * m_iTargetChunkSize is gotten from the word generator and displayed. * * This class handles logic and drawing code with respect to the above. */ class CGameModule : public CDasherModule { public: - // I don't actually know what the type is supposed to be for this...it's not an input method or an input filter. - // Maybe we should define a new one. I've labeled it 0 for now. - rgee CGameModule(Dasher::CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CDasherInterfaceBase *pInterface, ModuleID_t iID, const char *szName, std::vector<int> vEvents, CWordGeneratorBase* pWordGenerator) : m_iCrosshairColor(135), m_iCrosshairNumPoints(2), m_iCrosshairExtent(25), m_iCrosshairCrosslineLength(50), m_iTargetChunkSize(3), m_pWordGenerator(pWordGenerator), CDasherModule(pEventHandler, pSettingsStore, iID, 0, szName, vEvents) { m_pInterface = pInterface; //TODO REMOVE THIS!!! if(m_pWordGenerator == NULL) g_pLogger->Log("Word generator creation FAILED"); GenerateChunk(); if(m_sTargetString == "") m_sTargetString = "My name is julian."; m_stCurrentStringPos = 0; } virtual ~CGameModule() {}; /** * Gets the typed portion of the target string * @return The string that represents the current word(s) that have not been typed */ std::string GetTypedTarget(); /** * Gets the portion of the target string that has yet to be completed * @return The string that represents the current word(s) that have been typed */ std::string GetUntypedTarget(); /** * Draws Game Mode specific visuals to the screen. * @param pView The Dasher View to be modified * @return True if the view was modified, false otherwise. */ bool DecorateView(CDasherView *pView); /** * Handle events from the event processing system * @param pEvent The event to be processed. */ virtual void HandleEvent(Dasher::CEvent *pEvent); private: /** * Helper function for generating (Or regenerating) a new chunk. * @warning This will destroy the previous chunk. Only use when you * need to grab an entirely new chunk to display. */ void GenerateChunk(); /** * Get the distance of a given point (in Dasher Coordinates) from the origin. * * @param xCoord - the x coordinate of the point * @param yCoord - the y coordinate of the point * */ myint DistanceFromOrigin(myint xCoord, myint yCoord); /** * Searches for the dasher node under the current root that represents the desired string * @param text The string to search for * @return The node representing the string parameter */ //Dasher::CDasherNode StringToNode(std::string sText); /** * Pointer to the object that encapsulates the word generation * algorithm being used. */ CWordGeneratorBase* m_pWordGenerator; /** * The last node the user typed. */ CDasherNode *pLastTypedNode; /** * The next node (character) the user must type. */ CDasherNode *pNextTargetNode; /** * The target string the user must type. */ std::string m_sTargetString; /** * The current position in the string. * Stored as a size_t to easily use substrings to determine what's been typed and what hasn't. */ size_t m_stCurrentStringPos; /** * The dasher interface. */ CDasherInterfaceBase *m_pInterface; /** * The target x coordinate for the crosshair to point to. */ myint m_iTargetX; /** * The target y coordinate for the crosshair to point to. */ myint m_iTargetY; /* --------------------------------------------------------------------- * Constants * --------------------------------------------------------------------- */ /** * The color (in Dasher colors) to make the crosshair. */ const int m_iCrosshairColor; /** * The number of points that the crosshair's lines pass through. */ const int m_iCrosshairNumPoints; /** * The side length (in pixels) of the crosshair's square portion. */ const int m_iCrosshairExtent; /** * The length of the lines comprising the crosshair's * "cross". */ const int m_iCrosshairCrosslineLength; /** * The number of words displayed at once as a target for the user * to type. */ const int m_iTargetChunkSize; }; } #endif
rgee/HFOSS-Dasher
f1b43b2b4a5f4bed4b1bc5a8ad7012ef8ceacb26
Created a test directory that links with Gtest
diff --git a/Testing/dasher_tests/EventTest.cpp b/Testing/dasher_tests/EventTest.cpp new file mode 100755 index 0000000..4cfab05 --- /dev/null +++ b/Testing/dasher_tests/EventTest.cpp @@ -0,0 +1,5 @@ +#include "gtest/gtest.h" + +TEST(EventTest, simpletest) { + EXPECT_EQ(1, 1); +} diff --git a/Testing/dasher_tests/Makefile b/Testing/dasher_tests/Makefile new file mode 100644 index 0000000..c03d350 --- /dev/null +++ b/Testing/dasher_tests/Makefile @@ -0,0 +1,87 @@ +# A sample Makefile for building Google Test and using it in user +# tests. Please tweak it to suit your environment and project. You +# may want to move it to your project's root directory. +# +# SYNOPSIS: +# +# make [all] - makes everything. +# make TARGET - makes the given target. +# make clean - removes all files generated by make. + +# Please tweak the following variable definitions as needed by your +# project, except GTEST_HEADERS, which you can use in your own targets +# but shouldn't modify. + +# Points to the root of Google Test, relative to where this file is. +# Remember to tweak this if you move this file. +GTEST_DIR = ../gtest-1.5.0 + +# Where to find user code. +USER_DIR = . + +# Flags passed to the preprocessor. +CPPFLAGS += -I$(GTEST_DIR)/include + +# Flags passed to the C++ compiler. +CXXFLAGS += -g -Wall -Wextra + +# All tests produced by this Makefile. Remember to add new tests you +# created to the list. +TESTS = EventTest + +# All Google Test headers. Usually you shouldn't change this +# definition. +GTEST_HEADERS = $(GTEST_DIR)/include/gtest/*.h \ + $(GTEST_DIR)/include/gtest/internal/*.h + +# House-keeping build targets. + +all : $(TESTS) + +clean : + rm -f $(TESTS) gtest.a gtest_main.a *.o + +# Builds gtest.a and gtest_main.a. + +# Usually you shouldn't tweak such internal variables, indicated by a +# trailing _. +GTEST_SRCS_ = $(GTEST_DIR)/src/*.cc $(GTEST_DIR)/src/*.h $(GTEST_HEADERS) + +# For simplicity and to avoid depending on Google Test's +# implementation details, the dependencies specified below are +# conservative and not optimized. This is fine as Google Test +# compiles fast and for ordinary users its source rarely changes. +gtest-all.o : $(GTEST_SRCS_) + $(CXX) $(CPPFLAGS) -I$(GTEST_DIR) $(CXXFLAGS) -c \ + $(GTEST_DIR)/src/gtest-all.cc + +gtest_main.o : $(GTEST_SRCS_) + $(CXX) $(CPPFLAGS) -I$(GTEST_DIR) $(CXXFLAGS) -c \ + $(GTEST_DIR)/src/gtest_main.cc + +gtest.a : gtest-all.o + $(AR) $(ARFLAGS) $@ $^ + +gtest_main.a : gtest-all.o gtest_main.o + $(AR) $(ARFLAGS) $@ $^ + +# Builds a sample test. A test should link with either gtest.a or +# gtest_main.a, depending on whether it defines its own main() +# function. + +#sample1.o : $(USER_DIR)/sample1.cc $(USER_DIR)/sample1.h $(GTEST_HEADERS) +# $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/sample1.cc + +#sample1_unittest.o : $(USER_DIR)/sample1_unittest.cc \ +# $(USER_DIR)/sample1.h $(GTEST_HEADERS) +# $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/sample1_unittest.cc + +#sample1_unittest : sample1.o sample1_unittest.o gtest_main.a +# $(CXX) $(CPPFLAGS) $(CXXFLAGS) -lpthread $^ -o $@ + +EventTest : EventTest.o gtest_main.a + $(CXX) $(CPPFLAGS) $(CXXFLAGS) -lpthread $^ -o $@ + +EventTest.o : $(USER_DIR)/EventTest.cpp + $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/EventTest.cpp +
rgee/HFOSS-Dasher
2628cfedc223dff6949e339372c3ad0cba6233da
Reworked FileWordGenerator and GameModule should be drawing from it for words. However, there's an issue with file loading to be resolved soon.
diff --git a/Src/DasherCore/DasherInterfaceBase.cpp b/Src/DasherCore/DasherInterfaceBase.cpp index ceeac7b..88cca61 100644 --- a/Src/DasherCore/DasherInterfaceBase.cpp +++ b/Src/DasherCore/DasherInterfaceBase.cpp @@ -1,1164 +1,1165 @@ // DasherInterfaceBase.cpp // // Copyright (c) 2008 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" #include "DasherInterfaceBase.h" //#include "ActionButton.h" #include "DasherViewSquare.h" #include "ControlManager.h" #include "DasherScreen.h" #include "DasherView.h" #include "DasherInput.h" #include "DasherModel.h" #include "EventHandler.h" #include "Event.h" #include "NodeCreationManager.h" #ifndef _WIN32_WCE #include "UserLog.h" #include "BasicLog.h" #endif #include "DasherGameMode.h" +#include "FileWordGenerator.h" // Input filters #include "AlternatingDirectMode.h" #include "ButtonMode.h" #include "ClickFilter.h" #include "CompassMode.h" #include "DefaultFilter.h" #include "EyetrackerFilter.h" #include "OneButtonFilter.h" #include "OneButtonDynamicFilter.h" #include "OneDimensionalFilter.h" #include "StylusFilter.h" #include "TwoButtonDynamicFilter.h" #include "TwoPushDynamicFilter.h" // STL headers #include <cstdio> #include <iostream> #include <memory> // Declare our global file logging object #include "../DasherCore/FileLogger.h" #ifdef _DEBUG const eLogLevel g_iLogLevel = logDEBUG; const int g_iLogOptions = logTimeStamp | logDateStamp | logDeleteOldFile; #else const eLogLevel g_iLogLevel = logNORMAL; const int g_iLogOptions = logTimeStamp | logDateStamp; #endif #ifndef _WIN32_WCE CFileLogger* g_pLogger = NULL; #endif using namespace Dasher; using namespace std; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG_MEMLEAKS #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif CDasherInterfaceBase::CDasherInterfaceBase() { // Ensure that pointers to 'owned' objects are set to NULL. m_Alphabet = NULL; m_pDasherModel = NULL; m_DasherScreen = NULL; m_pDasherView = NULL; m_pInput = NULL; m_pInputFilter = NULL; m_AlphIO = NULL; m_ColourIO = NULL; m_pUserLog = NULL; m_pNCManager = NULL; m_defaultPolicy = NULL; m_pGameModule = NULL; // Various state variables m_bRedrawScheduled = false; m_iCurrentState = ST_START; // m_bGlobalLock = false; // TODO: Are these actually needed? strCurrentContext = ". "; strTrainfileBuffer = ""; // Create an event handler. m_pEventHandler = new CEventHandler(this); m_bLastChanged = true; #ifndef _WIN32_WCE // Global logging object we can use from anywhere g_pLogger = new CFileLogger("dasher.log", g_iLogLevel, g_iLogOptions); #endif } void CDasherInterfaceBase::Realize() { // TODO: What exactly needs to have happened by the time we call Realize()? CreateSettingsStore(); SetupUI(); SetupPaths(); std::vector<std::string> vAlphabetFiles; ScanAlphabetFiles(vAlphabetFiles); m_AlphIO = new CAlphIO(GetStringParameter(SP_SYSTEM_LOC), GetStringParameter(SP_USER_LOC), vAlphabetFiles); std::vector<std::string> vColourFiles; ScanColourFiles(vColourFiles); m_ColourIO = new CColourIO(GetStringParameter(SP_SYSTEM_LOC), GetStringParameter(SP_USER_LOC), vColourFiles); ChangeColours(); ChangeAlphabet(); // This creates the NodeCreationManager, the Alphabet // Create the user logging object if we are suppose to. We wait // until now so we have the real value of the parameter and not // just the default. // TODO: Sort out log type selection #ifndef _WIN32_WCE int iUserLogLevel = GetLongParameter(LP_USER_LOG_LEVEL_MASK); if(iUserLogLevel == 10) m_pUserLog = new CBasicLog(m_pEventHandler, m_pSettingsStore); else if (iUserLogLevel > 0) m_pUserLog = new CUserLog(m_pEventHandler, m_pSettingsStore, iUserLogLevel, m_Alphabet); #else m_pUserLog = NULL; #endif CreateModules(); CreateInput(); CreateInputFilter(); SetupActionButtons(); CParameterNotificationEvent oEvent(LP_NODE_BUDGET); InterfaceEventHandler(&oEvent); //if game mode is enabled , initialize the game module // if(GetBoolParameter(BP_GAME_MODE)) InitGameModule(); // Set up real orientation to match selection if(GetLongParameter(LP_ORIENTATION) == Dasher::Opts::AlphabetDefault) SetLongParameter(LP_REAL_ORIENTATION, m_Alphabet->GetOrientation()); else SetLongParameter(LP_REAL_ORIENTATION, GetLongParameter(LP_ORIENTATION)); // FIXME - need to rationalise this sort of thing. // InvalidateContext(true); ScheduleRedraw(); #ifndef _WIN32_WCE // All the setup is done by now, so let the user log object know // that future parameter changes should be logged. if (m_pUserLog != NULL) m_pUserLog->InitIsDone(); #endif // TODO: Make things work when model is created latet ChangeState(TR_MODEL_INIT); using GameMode::CDasherGameMode; // Create the teacher singleton object. CDasherGameMode::CreateTeacher(m_pEventHandler, m_pSettingsStore, this); CDasherGameMode::GetTeacher()->SetDasherView(m_pDasherView); CDasherGameMode::GetTeacher()->SetDasherModel(m_pDasherModel); } CDasherInterfaceBase::~CDasherInterfaceBase() { DASHER_ASSERT(m_iCurrentState == ST_SHUTDOWN); // It may seem odd that InterfaceBase does not "own" the teacher. // This is because game mode is a different layer, in a sense. GameMode::CDasherGameMode::DestroyTeacher(); delete m_pDasherModel; // The order of some of these deletions matters delete m_Alphabet; delete m_pDasherView; delete m_ColourIO; delete m_AlphIO; delete m_pNCManager; // Do NOT delete Edit box or Screen. This class did not create them. #ifndef _WIN32_WCE // When we destruct on shutdown, we'll output any detailed log file if (m_pUserLog != NULL) { m_pUserLog->OutputFile(); delete m_pUserLog; m_pUserLog = NULL; } if (g_pLogger != NULL) { delete g_pLogger; g_pLogger = NULL; } #endif for (std::vector<CActionButton *>::iterator it=m_vLeftButtons.begin(); it != m_vLeftButtons.end(); ++it) delete *it; for (std::vector<CActionButton *>::iterator it=m_vRightButtons.begin(); it != m_vRightButtons.end(); ++it) delete *it; // Must delete event handler after all CDasherComponent derived classes delete m_pEventHandler; } void CDasherInterfaceBase::PreSetNotify(int iParameter, const std::string &sNewValue) { // FIXME - make this a more general 'pre-set' event in the message // infrastructure switch(iParameter) { case SP_ALPHABET_ID: // Cycle the alphabet history if(GetStringParameter(SP_ALPHABET_ID) != sNewValue) { if(GetStringParameter(SP_ALPHABET_1) != sNewValue) { if(GetStringParameter(SP_ALPHABET_2) != sNewValue) { if(GetStringParameter(SP_ALPHABET_3) != sNewValue) SetStringParameter(SP_ALPHABET_4, GetStringParameter(SP_ALPHABET_3)); SetStringParameter(SP_ALPHABET_3, GetStringParameter(SP_ALPHABET_2)); } SetStringParameter(SP_ALPHABET_2, GetStringParameter(SP_ALPHABET_1)); } SetStringParameter(SP_ALPHABET_1, GetStringParameter(SP_ALPHABET_ID)); } break; } } void CDasherInterfaceBase::InterfaceEventHandler(Dasher::CEvent *pEvent) { if(pEvent->m_iEventType == EV_PARAM_NOTIFY) { Dasher::CParameterNotificationEvent * pEvt(static_cast < Dasher::CParameterNotificationEvent * >(pEvent)); switch (pEvt->m_iParameter) { case BP_OUTLINE_MODE: ScheduleRedraw(); break; case BP_DRAW_MOUSE: ScheduleRedraw(); break; case BP_CONTROL_MODE: ScheduleRedraw(); break; case BP_DRAW_MOUSE_LINE: ScheduleRedraw(); break; case LP_ORIENTATION: if(GetLongParameter(LP_ORIENTATION) == Dasher::Opts::AlphabetDefault) // TODO: See comment in DasherModel.cpp about prefered values SetLongParameter(LP_REAL_ORIENTATION, m_Alphabet->GetOrientation()); else SetLongParameter(LP_REAL_ORIENTATION, GetLongParameter(LP_ORIENTATION)); ScheduleRedraw(); break; case SP_ALPHABET_ID: ChangeAlphabet(); ScheduleRedraw(); break; case SP_COLOUR_ID: ChangeColours(); ScheduleRedraw(); break; case SP_DEFAULT_COLOUR_ID: // Delibarate fallthrough case BP_PALETTE_CHANGE: if(GetBoolParameter(BP_PALETTE_CHANGE)) SetStringParameter(SP_COLOUR_ID, GetStringParameter(SP_DEFAULT_COLOUR_ID)); break; case LP_LANGUAGE_MODEL_ID: CreateNCManager(); break; case LP_LINE_WIDTH: ScheduleRedraw(); break; case LP_DASHER_FONTSIZE: ScheduleRedraw(); break; case SP_INPUT_DEVICE: CreateInput(); break; case SP_INPUT_FILTER: CreateInputFilter(); ScheduleRedraw(); break; case BP_DASHER_PAUSED: ScheduleRedraw(); break; case LP_MARGIN_WIDTH: case BP_NONLINEAR_Y: case LP_NONLINEAR_X: ScheduleRedraw(); break; case LP_NODE_BUDGET: delete m_defaultPolicy; m_defaultPolicy = new AmortizedPolicy(GetLongParameter(LP_NODE_BUDGET)); default: break; } } else if(pEvent->m_iEventType == EV_EDIT && !GetBoolParameter(BP_GAME_MODE)) { CEditEvent *pEditEvent(static_cast < CEditEvent * >(pEvent)); if(pEditEvent->m_iEditType == 1) { strCurrentContext += pEditEvent->m_sText; if( strCurrentContext.size() > 20 ) strCurrentContext = strCurrentContext.substr( strCurrentContext.size() - 20 ); if(GetBoolParameter(BP_LM_ADAPTIVE)) strTrainfileBuffer += pEditEvent->m_sText; } else if(pEditEvent->m_iEditType == 2) { strCurrentContext = strCurrentContext.substr( 0, strCurrentContext.size() - pEditEvent->m_sText.size()); if(GetBoolParameter(BP_LM_ADAPTIVE)) strTrainfileBuffer = strTrainfileBuffer.substr( 0, strTrainfileBuffer.size() - pEditEvent->m_sText.size()); } } else if(pEvent->m_iEventType == EV_CONTROL) { CControlEvent *pControlEvent(static_cast <CControlEvent*>(pEvent)); switch(pControlEvent->m_iID) { case CControlManager::CTL_STOP: Pause(); break; case CControlManager::CTL_PAUSE: //Halt Dasher - without a stop event, so does not result in speech etc. SetBoolParameter(BP_DASHER_PAUSED, true); m_pDasherModel->TriggerSlowdown(); } } } void CDasherInterfaceBase::WriteTrainFileFull() { WriteTrainFile(strTrainfileBuffer); strTrainfileBuffer = ""; } void CDasherInterfaceBase::WriteTrainFilePartial() { // TODO: what if we're midway through a unicode character? WriteTrainFile(strTrainfileBuffer.substr(0,100)); strTrainfileBuffer = strTrainfileBuffer.substr(100); } void CDasherInterfaceBase::CreateModel(int iOffset) { // Creating a model without a node creation manager is a bad plan if(!m_pNCManager) return; if(m_pDasherModel) { delete m_pDasherModel; m_pDasherModel = 0; } m_pDasherModel = new CDasherModel(m_pEventHandler, m_pSettingsStore, m_pNCManager, this, m_pDasherView, iOffset); // Notify the teacher of the new model if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) pTeacher->SetDasherModel(m_pDasherModel); } void CDasherInterfaceBase::CreateNCManager() { // TODO: Try and make this work without necessarilty rebuilding the model if(!m_AlphIO) return; int lmID = GetLongParameter(LP_LANGUAGE_MODEL_ID); if( lmID == -1 ) return; int iOffset; if(m_pDasherModel) iOffset = m_pDasherModel->GetOffset(); else iOffset = 0; // TODO: Is this right? // Delete the old model and create a new one if(m_pDasherModel) { delete m_pDasherModel; m_pDasherModel = 0; } if(m_pNCManager) { delete m_pNCManager; m_pNCManager = 0; } m_pNCManager = new CNodeCreationManager(this, m_pEventHandler, m_pSettingsStore, m_AlphIO); m_Alphabet = m_pNCManager->GetAlphabet(); // TODO: Eventually we'll not have to pass the NC manager to the model... CreateModel(iOffset); } void CDasherInterfaceBase::Pause() { if (GetBoolParameter(BP_DASHER_PAUSED)) return; //already paused, no need to do anything. SetBoolParameter(BP_DASHER_PAUSED, true); // Request a full redraw at the next time step. SetBoolParameter(BP_REDRAW, true); Dasher::CStopEvent oEvent; m_pEventHandler->InsertEvent(&oEvent); #ifndef _WIN32_WCE if (m_pUserLog != NULL) m_pUserLog->StopWriting((float) GetNats()); #endif } void CDasherInterfaceBase::GameMessageIn(int message, void* messagedata) { GameMode::CDasherGameMode::GetTeacher()->Message(message, messagedata); } void CDasherInterfaceBase::Unpause(unsigned long Time) { if (!GetBoolParameter(BP_DASHER_PAUSED)) return; //already running, no need to do anything SetBoolParameter(BP_DASHER_PAUSED, false); if(m_pDasherModel != 0) m_pDasherModel->Reset_framerate(Time); Dasher::CStartEvent oEvent; m_pEventHandler->InsertEvent(&oEvent); // Commenting this out, can't see a good reason to ResetNats, // just because we are not paused anymore - pconlon // ResetNats(); #ifndef _WIN32_WCE if (m_pUserLog != NULL) m_pUserLog->StartWriting(); #endif } void CDasherInterfaceBase::CreateInput() { if(m_pInput) { m_pInput->Deactivate(); } m_pInput = (CDasherInput *)GetModuleByName(GetStringParameter(SP_INPUT_DEVICE)); if (m_pInput == NULL) m_pInput = (CDasherInput *)GetDefaultInputDevice(); if(m_pInput) { m_pInput->Activate(); } if(m_pDasherView != 0) m_pDasherView->SetInput(m_pInput); } void CDasherInterfaceBase::NewFrame(unsigned long iTime, bool bForceRedraw) { // Prevent NewFrame from being reentered. This can happen occasionally and // cause crashes. static bool bReentered=false; if (bReentered) { #ifdef DEBUG std::cout << "CDasherInterfaceBase::NewFrame was re-entered" << std::endl; #endif return; } bReentered=true; // Fail if Dasher is locked // if(m_iCurrentState != ST_NORMAL) // return; bool bChanged(false), bWasPaused(GetBoolParameter(BP_DASHER_PAUSED)); CExpansionPolicy *pol=m_defaultPolicy; if(m_pDasherView != 0) { if(!GetBoolParameter(BP_TRAINING)) { if (m_pUserLog != NULL) { //ACL note that as of 15/5/09, splitting UpdatePosition into two, //DasherModel no longer guarantees to empty these two if it didn't do anything. //So initialise appropriately... Dasher::VECTOR_SYMBOL_PROB vAdded; int iNumDeleted = 0; if(m_pInputFilter) { bChanged = m_pInputFilter->Timer(iTime, m_pDasherView, m_pDasherModel, &vAdded, &iNumDeleted, &pol); } #ifndef _WIN32_WCE if (iNumDeleted > 0) m_pUserLog->DeleteSymbols(iNumDeleted); if (vAdded.size() > 0) m_pUserLog->AddSymbols(&vAdded); #endif } else { if(m_pInputFilter) { bChanged = m_pInputFilter->Timer(iTime, m_pDasherView, m_pDasherModel, 0, 0, &pol); } } m_pDasherModel->CheckForNewRoot(m_pDasherView); } } //check: if we were paused before, and the input filter didn't unpause, // then nothing can have changed: DASHER_ASSERT(!bWasPaused || !GetBoolParameter(BP_DASHER_PAUSED) || !bChanged); // Flags at this stage: // // - bChanged = the display was updated, so needs to be rendered to the display // - m_bLastChanged = bChanged was true last time around // - m_bRedrawScheduled = Display invalidated internally // - bForceRedraw = Display invalidated externally // TODO: This is a bit hacky - we really need to sort out the redraw logic if((!bChanged && m_bLastChanged) || m_bRedrawScheduled || bForceRedraw) { m_pDasherView->Screen()->SetCaptureBackground(true); m_pDasherView->Screen()->SetLoadBackground(true); } bForceRedraw |= m_bLastChanged; m_bLastChanged = bChanged; //will also be set in Redraw if any nodes were expanded. Redraw(bChanged || m_bRedrawScheduled || bForceRedraw, *pol); m_bRedrawScheduled = false; // This just passes the time through to the framerate tracker, so we // know how often new frames are being drawn. if(m_pDasherModel != 0) m_pDasherModel->RecordFrame(iTime); bReentered=false; } void CDasherInterfaceBase::Redraw(bool bRedrawNodes, CExpansionPolicy &policy) { // No point continuing if there's nothing to draw on... if(!m_pDasherView) return; // Draw the nodes if(bRedrawNodes) { m_pDasherView->Screen()->SendMarker(0); if (m_pDasherModel) m_bLastChanged |= m_pDasherModel->RenderToView(m_pDasherView,policy); } // Draw the decorations m_pDasherView->Screen()->SendMarker(1); if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) pTeacher->DrawGameDecorations(m_pDasherView); bool bDecorationsChanged(false); if(m_pInputFilter) { bDecorationsChanged = m_pInputFilter->DecorateView(m_pDasherView); } if(m_pGameModule) { bDecorationsChanged = m_pGameModule->DecorateView(m_pDasherView) || bDecorationsChanged; } bool bActionButtonsChanged(false); #ifdef EXPERIMENTAL_FEATURES bActionButtonsChanged = DrawActionButtons(); #endif // Only blit the image to the display if something has actually changed if(bRedrawNodes || bDecorationsChanged || bActionButtonsChanged) m_pDasherView->Display(); } void CDasherInterfaceBase::ChangeAlphabet() { if(GetStringParameter(SP_ALPHABET_ID) == "") { SetStringParameter(SP_ALPHABET_ID, m_AlphIO->GetDefault()); // This will result in ChangeAlphabet() being called again, so // exit from the first recursion return; } // Send a lock event WriteTrainFileFull(); // Lock Dasher to prevent changes from happening while we're training. SetBoolParameter( BP_TRAINING, true ); CreateNCManager(); #ifndef _WIN32_WCE // Let our user log object know about the new alphabet since // it needs to convert symbols into text for the log file. if (m_pUserLog != NULL) m_pUserLog->SetAlphabetPtr(m_Alphabet); #endif // Apply options from alphabet SetBoolParameter( BP_TRAINING, false ); //} } void CDasherInterfaceBase::ChangeColours() { if(!m_ColourIO || !m_DasherScreen) return; // TODO: Make fuction return a pointer directly m_DasherScreen->SetColourScheme(&(m_ColourIO->GetInfo(GetStringParameter(SP_COLOUR_ID)))); } void CDasherInterfaceBase::ChangeScreen(CDasherScreen *NewScreen) { // What does ChangeScreen do? m_DasherScreen = NewScreen; ChangeColours(); if(m_pDasherView != 0) { m_pDasherView->ChangeScreen(m_DasherScreen); } else if(GetLongParameter(LP_VIEW_ID) != -1) { ChangeView(); } PositionActionButtons(); BudgettingPolicy pol(GetLongParameter(LP_NODE_BUDGET)); //maintain budget, but allow arbitrary amount of work. Redraw(true, pol); // (we're assuming resolution changes are occasional, i.e. // we don't need to worry about maintaining the frame rate, so we can do // as much work as necessary. However, it'd probably be better still to // get a node queue from the input filter, as that might have a different // policy / budget. } void CDasherInterfaceBase::ChangeView() { // TODO: Actually respond to LP_VIEW_ID parameter (although there is only one view at the moment) // removed condition that m_pDasherModel != 0. Surely the view can exist without the model?-pconlon if(m_DasherScreen != 0 /*&& m_pDasherModel != 0*/) { delete m_pDasherView; m_pDasherView = new CDasherViewSquare(m_pEventHandler, m_pSettingsStore, m_DasherScreen); if (m_pInput) m_pDasherView->SetInput(m_pInput); // Tell the Teacher which view we are using if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) pTeacher->SetDasherView(m_pDasherView); } } const CAlphIO::AlphInfo & CDasherInterfaceBase::GetInfo(const std::string &AlphID) { return m_AlphIO->GetInfo(AlphID); } void CDasherInterfaceBase::SetInfo(const CAlphIO::AlphInfo &NewInfo) { m_AlphIO->SetInfo(NewInfo); } void CDasherInterfaceBase::DeleteAlphabet(const std::string &AlphID) { m_AlphIO->Delete(AlphID); } double CDasherInterfaceBase::GetCurCPM() { // return 0; } double CDasherInterfaceBase::GetCurFPS() { // return 0; } // int CDasherInterfaceBase::GetAutoOffset() { // if(m_pDasherView != 0) { // return m_pDasherView->GetAutoOffset(); // } // return -1; // } double CDasherInterfaceBase::GetNats() const { if(m_pDasherModel) return m_pDasherModel->GetNats(); else return 0.0; } void CDasherInterfaceBase::ResetNats() { if(m_pDasherModel) m_pDasherModel->ResetNats(); } // TODO: Check that none of this needs to be reimplemented // void CDasherInterfaceBase::InvalidateContext(bool bForceStart) { // m_pDasherModel->m_strContextBuffer = ""; // Dasher::CEditContextEvent oEvent(10); // m_pEventHandler->InsertEvent(&oEvent); // std::string strNewContext(m_pDasherModel->m_strContextBuffer); // // We keep track of an internal context and compare that to what // // we are given - don't restart Dasher if nothing has changed. // // This should really be integrated with DasherModel, which // // probably will be the case when we start to deal with being able // // to back off indefinitely. For now though we'll keep it in a // // separate string. // int iContextLength( 6 ); // The 'important' context length - should really get from language model // // FIXME - use unicode lengths // if(bForceStart || (strNewContext.substr( std::max(static_cast<int>(strNewContext.size()) - iContextLength, 0)) != strCurrentContext.substr( std::max(static_cast<int>(strCurrentContext.size()) - iContextLength, 0)))) { // if(m_pDasherModel != NULL) { // // TODO: Reimplement this // // if(m_pDasherModel->m_bContextSensitive || bForceStart) { // { // m_pDasherModel->SetContext(strNewContext); // PauseAt(0,0); // } // } // strCurrentContext = strNewContext; // WriteTrainFileFull(); // } // if(bForceStart) { // int iMinWidth; // if(m_pInputFilter && m_pInputFilter->GetMinWidth(iMinWidth)) { // m_pDasherModel->LimitRoot(iMinWidth); // } // } // if(m_pDasherView) // while( m_pDasherModel->CheckForNewRoot(m_pDasherView) ) { // // Do nothing // } // ScheduleRedraw(); // } // TODO: Fix this std::string CDasherInterfaceBase::GetContext(int iStart, int iLength) { m_strContext = ""; CEditContextEvent oEvent(iStart, iLength); m_pEventHandler->InsertEvent(&oEvent); return m_strContext; } void CDasherInterfaceBase::SetContext(std::string strNewContext) { m_strContext = strNewContext; } // Control mode stuff void CDasherInterfaceBase::RegisterNode( int iID, const std::string &strLabel, int iColour ) { m_pNCManager->RegisterNode(iID, strLabel, iColour); } void CDasherInterfaceBase::ConnectNode(int iChild, int iParent, int iAfter) { m_pNCManager->ConnectNode(iChild, iParent, iAfter); } void CDasherInterfaceBase::DisconnectNode(int iChild, int iParent) { m_pNCManager->DisconnectNode(iChild, iParent); } void CDasherInterfaceBase::SetBoolParameter(int iParameter, bool bValue) { m_pSettingsStore->SetBoolParameter(iParameter, bValue); }; void CDasherInterfaceBase::SetLongParameter(int iParameter, long lValue) { m_pSettingsStore->SetLongParameter(iParameter, lValue); }; void CDasherInterfaceBase::SetStringParameter(int iParameter, const std::string & sValue) { PreSetNotify(iParameter, sValue); m_pSettingsStore->SetStringParameter(iParameter, sValue); }; bool CDasherInterfaceBase::GetBoolParameter(int iParameter) { return m_pSettingsStore->GetBoolParameter(iParameter); } long CDasherInterfaceBase::GetLongParameter(int iParameter) { return m_pSettingsStore->GetLongParameter(iParameter); } std::string CDasherInterfaceBase::GetStringParameter(int iParameter) { return m_pSettingsStore->GetStringParameter(iParameter); } void CDasherInterfaceBase::ResetParameter(int iParameter) { m_pSettingsStore->ResetParameter(iParameter); } // We need to be able to get at the UserLog object from outside the interface CUserLogBase* CDasherInterfaceBase::GetUserLogPtr() { return m_pUserLog; } void CDasherInterfaceBase::KeyDown(int iTime, int iId, bool bPos, int iX, int iY) { if(m_iCurrentState != ST_NORMAL) return; if(m_pInputFilter && !GetBoolParameter(BP_TRAINING)) { m_pInputFilter->KeyDown(iTime, iId, m_pDasherView, m_pDasherModel, m_pUserLog, bPos, iX, iY); } if(m_pInput && !GetBoolParameter(BP_TRAINING)) { m_pInput->KeyDown(iTime, iId); } } void CDasherInterfaceBase::KeyUp(int iTime, int iId, bool bPos, int iX, int iY) { if(m_iCurrentState != ST_NORMAL) return; if(m_pInputFilter && !GetBoolParameter(BP_TRAINING)) { m_pInputFilter->KeyUp(iTime, iId, m_pDasherView, m_pDasherModel, bPos, iX, iY); } if(m_pInput && !GetBoolParameter(BP_TRAINING)) { m_pInput->KeyUp(iTime, iId); } } void CDasherInterfaceBase::InitGameModule() { if(m_pGameModule == NULL) { m_pGameModule = (CGameModule*) GetModuleByName("Game Mode"); } } void CDasherInterfaceBase::CreateInputFilter() { if(m_pInputFilter) { m_pInputFilter->Deactivate(); m_pInputFilter = NULL; } #ifndef _WIN32_WCE m_pInputFilter = (CInputFilter *)GetModuleByName(GetStringParameter(SP_INPUT_FILTER)); #endif if (m_pInputFilter == NULL) m_pInputFilter = (CInputFilter *)GetDefaultInputMethod(); m_pInputFilter->Activate(); } CDasherModule *CDasherInterfaceBase::RegisterModule(CDasherModule *pModule) { return m_oModuleManager.RegisterModule(pModule); } CDasherModule *CDasherInterfaceBase::GetModule(ModuleID_t iID) { return m_oModuleManager.GetModule(iID); } CDasherModule *CDasherInterfaceBase::GetModuleByName(const std::string &strName) { return m_oModuleManager.GetModuleByName(strName); } CDasherModule *CDasherInterfaceBase::GetDefaultInputDevice() { return m_oModuleManager.GetDefaultInputDevice(); } CDasherModule *CDasherInterfaceBase::GetDefaultInputMethod() { return m_oModuleManager.GetDefaultInputMethod(); } void CDasherInterfaceBase::SetDefaultInputDevice(CDasherModule *pModule) { m_oModuleManager.SetDefaultInputDevice(pModule); } void CDasherInterfaceBase::SetDefaultInputMethod(CDasherModule *pModule) { m_oModuleManager.SetDefaultInputMethod(pModule); } void CDasherInterfaceBase::CreateModules() { SetDefaultInputMethod( RegisterModule(new CDefaultFilter(m_pEventHandler, m_pSettingsStore, this, 3, _("Normal Control"))) ); RegisterModule(new COneDimensionalFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CEyetrackerFilter(m_pEventHandler, m_pSettingsStore, this)); #ifndef _WIN32_WCE RegisterModule(new CClickFilter(m_pEventHandler, m_pSettingsStore, this)); #else SetDefaultInputMethod( RegisterModule(new CClickFilter(m_pEventHandler, m_pSettingsStore, this)); ); #endif RegisterModule(new COneButtonFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new COneButtonDynamicFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CTwoButtonDynamicFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CTwoPushDynamicFilter(m_pEventHandler, m_pSettingsStore, this)); // TODO: specialist factory for button mode RegisterModule(new CButtonMode(m_pEventHandler, m_pSettingsStore, this, true, 8, _("Menu Mode"))); RegisterModule(new CButtonMode(m_pEventHandler, m_pSettingsStore, this, false,10, _("Direct Mode"))); // RegisterModule(new CDasherButtons(m_pEventHandler, m_pSettingsStore, this, 4, 0, false,11, "Buttons 3")); RegisterModule(new CAlternatingDirectMode(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CCompassMode(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CStylusFilter(m_pEventHandler, m_pSettingsStore, this, 15, _("Stylus Control"))); // Register game mode with the module manager // TODO should this be wrapped in an "if game mode enabled" // conditional? // TODO: I don't know what a sensible module ID should be // for this, so I chose an arbitrary value // TODO: Put "Game Mode" in enumeration in Parameter.h int GameEvents[] = {EV_EDIT, EV_TEXTDRAW}; RegisterModule(new CGameModule(m_pEventHandler, m_pSettingsStore, this, 21, _("Game Mode"), - std::vector<int>(GameEvents, GameEvents + sizeof(GameEvents) / sizeof(int)))); + std::vector<int>(GameEvents, GameEvents + sizeof(GameEvents) / sizeof(int)), new CFileWordGenerator(""))); } void CDasherInterfaceBase::GetPermittedValues(int iParameter, std::vector<std::string> &vList) { // TODO: Deprecate direct calls to these functions switch (iParameter) { case SP_ALPHABET_ID: if(m_AlphIO) m_AlphIO->GetAlphabets(&vList); break; case SP_COLOUR_ID: if(m_ColourIO) m_ColourIO->GetColours(&vList); break; case SP_INPUT_FILTER: m_oModuleManager.ListModules(1, vList); break; case SP_INPUT_DEVICE: m_oModuleManager.ListModules(0, vList); break; } } void CDasherInterfaceBase::StartShutdown() { ChangeState(TR_SHUTDOWN); } bool CDasherInterfaceBase::GetModuleSettings(const std::string &strName, SModuleSettings **pSettings, int *iCount) { return GetModuleByName(strName)->GetSettings(pSettings, iCount); } void CDasherInterfaceBase::SetupActionButtons() { m_vLeftButtons.push_back(new CActionButton(this, "Exit", true)); m_vLeftButtons.push_back(new CActionButton(this, "Preferences", false)); m_vLeftButtons.push_back(new CActionButton(this, "Help", false)); m_vLeftButtons.push_back(new CActionButton(this, "About", false)); } void CDasherInterfaceBase::DestroyActionButtons() { // TODO: implement and call this } void CDasherInterfaceBase::PositionActionButtons() { if(!m_DasherScreen) return; int iCurrentOffset(16); for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) { (*it)->SetPosition(16, iCurrentOffset, 32, 32); iCurrentOffset += 48; } iCurrentOffset = 16; for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) { (*it)->SetPosition(m_DasherScreen->GetWidth() - 144, iCurrentOffset, 128, 32); iCurrentOffset += 48; } } bool CDasherInterfaceBase::DrawActionButtons() { if(!m_DasherScreen) return false; bool bVisible(GetBoolParameter(BP_DASHER_PAUSED)); bool bRV(bVisible != m_bOldVisible); m_bOldVisible = bVisible; for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) (*it)->Draw(m_DasherScreen, bVisible); for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) (*it)->Draw(m_DasherScreen, bVisible); return bRV; } void CDasherInterfaceBase::HandleClickUp(int iTime, int iX, int iY) { #ifdef EXPERIMENTAL_FEATURES bool bVisible(GetBoolParameter(BP_DASHER_PAUSED)); for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) { if((*it)->HandleClickUp(iTime, iX, iY, bVisible)) return; } for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) { if((*it)->HandleClickUp(iTime, iX, iY, bVisible)) return; } #endif KeyUp(iTime, 100, true, iX, iY); } void CDasherInterfaceBase::HandleClickDown(int iTime, int iX, int iY) { #ifdef EXPERIMENTAL_FEATURES bool bVisible(GetBoolParameter(BP_DASHER_PAUSED)); for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) { if((*it)->HandleClickDown(iTime, iX, iY, bVisible)) return; } for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) { if((*it)->HandleClickDown(iTime, iX, iY, bVisible)) return; } #endif KeyDown(iTime, 100, true, iX, iY); } void CDasherInterfaceBase::ExecuteCommand(const std::string &strName) { // TODO: Pointless - just insert event directly CCommandEvent *pEvent = new CCommandEvent(strName); m_pEventHandler->InsertEvent(pEvent); delete pEvent; } double CDasherInterfaceBase::GetFramerate() { if(m_pDasherModel) return(m_pDasherModel->Framerate()); else return 0.0; } void CDasherInterfaceBase::AddActionButton(const std::string &strName) { m_vRightButtons.push_back(new CActionButton(this, strName, false)); } void CDasherInterfaceBase::OnUIRealised() { StartTimer(); ChangeState(TR_UI_INIT); } void CDasherInterfaceBase::ChangeState(ETransition iTransition) { static EState iTransitionTable[ST_NUM][TR_NUM] = { {ST_MODEL, ST_UI, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN},//ST_START {ST_FORBIDDEN, ST_NORMAL, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN},//ST_MODEL {ST_NORMAL, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN},//ST_UI {ST_FORBIDDEN, ST_FORBIDDEN, ST_LOCKED, ST_FORBIDDEN, ST_SHUTDOWN},//ST_NORMAL {ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_NORMAL, ST_FORBIDDEN},//ST_LOCKED {ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN}//ST_SHUTDOWN //TR_MODEL_INIT, TR_UI_INIT, TR_LOCK, TR_UNLOCK, TR_SHUTDOWN }; EState iNewState(iTransitionTable[m_iCurrentState][iTransition]); if(iNewState != ST_FORBIDDEN) { if (iNewState == ST_SHUTDOWN) { ShutdownTimer(); WriteTrainFileFull(); } m_iCurrentState = iNewState; } } void CDasherInterfaceBase::SetBuffer(int iOffset) { CreateModel(iOffset); } void CDasherInterfaceBase::UnsetBuffer() { // TODO: Write training file? if(m_pDasherModel) delete m_pDasherModel; m_pDasherModel = 0; } void CDasherInterfaceBase::SetOffset(int iOffset) { if(m_pDasherModel) m_pDasherModel->SetOffset(iOffset, m_pDasherView); } void CDasherInterfaceBase::SetControlOffset(int iOffset) { if(m_pDasherModel) m_pDasherModel->SetControlOffset(iOffset); } // Returns 0 on success, an error string on failure. const char* CDasherInterfaceBase::ClSet(const std::string &strKey, const std::string &strValue) { if(m_pSettingsStore) return m_pSettingsStore->ClSet(strKey, strValue); return 0; } void CDasherInterfaceBase::ImportTrainingText(const std::string &strPath) { if(m_pNCManager) m_pNCManager->ImportTrainingText(strPath); } diff --git a/Src/DasherCore/FileWordGenerator.cpp b/Src/DasherCore/FileWordGenerator.cpp index f359a81..22ae34d 100644 --- a/Src/DasherCore/FileWordGenerator.cpp +++ b/Src/DasherCore/FileWordGenerator.cpp @@ -1,33 +1,59 @@ #include "FileWordGenerator.h" using namespace Dasher; bool CFileWordGenerator::Generate() { - if(!m_bWordsReady) { - ifstream file_in; - file_in.open(m_sPath.c_str()); - char buffer; - while(file_in.good()) { - file_in.get(buffer); - m_sGeneratedString.append(&buffer); - } - m_uiPos = 0; - } + g_pLogger->Log("About to open file"); + if(!m_bWordsReady) { + std::ifstream file_in("test_text.txt"); + + string buffer; + while(!std::getline(file_in, buffer).eof()) + { + m_sGeneratedString += buffer; + } + file_in.close(); + g_pLogger->Log(m_sGeneratedString); + + m_uiPos = 0; + } + return true; } std::string CFileWordGenerator::GetPath() { - return m_sPath; + return m_sPath; } std::string CFileWordGenerator::GetFilename() { - return m_sPath.substr(m_sPath.rfind("/")); + return m_sPath.substr(m_sPath.rfind("/")); } void CFileWordGenerator::SetSource(std::string newPath) { - m_sPath = newPath; - m_bWordsReady = false; - Generate(); + m_sPath = newPath; + m_bWordsReady = false; + Generate(); } std::string CFileWordGenerator::GetNextWord() { - return m_sGeneratedString.substr(m_uiPos, m_sGeneratedString.find(" ")); + + // Check if there are any spaces left in the file from the current + // position to the end. If not, we know we are either right before + // the last word or there are no more left. + size_t found = m_sGeneratedString.substr(m_uiPos).find(" "); + + if(found != string::npos) { + // If we're at the end of the string + if((m_uiPos + 1) == m_sGeneratedString.length()) { + return std::string(""); + }else { + // Grab the next word. + std::string result = m_sGeneratedString.substr(m_uiPos, found); + + // Set the current position to 1 after the space character. + // (i.e. The first letter of the next word.) + m_uiPos = found + 1; + + return result; + } + } + return std::string(""); } diff --git a/Src/DasherCore/FileWordGenerator.h b/Src/DasherCore/FileWordGenerator.h index 1d5eee5..6bfa4ab 100644 --- a/Src/DasherCore/FileWordGenerator.h +++ b/Src/DasherCore/FileWordGenerator.h @@ -1,59 +1,85 @@ +#ifndef __FileWordGenerator_h__ +#define __FileWordGenerator_h__ + #include <string> #include <iostream> #include <fstream> using namespace std; #include "WordGeneratorBase.h" +#include "DasherInterfaceBase.h" namespace Dasher { class CFileWordGenerator : public CWordGeneratorBase { public: - CFileWordGenerator(std::string path, int regen) : CWordGeneratorBase(regen) { - } - /** - * The generator function. In this implementation, it reads from a file to produce strings. - * @see CWordGeneratorBase::Generate - */ - virtual bool Generate(); - - /** - * Returns the next word that was read - */ - virtual std::string GetNextWord(); - - - /** - * File path getter - * @return The path to the file this generator reads from. - */ - std::string GetPath(); - - /** - * File name getter - * @return The actual name of the file being read from - */ - std::string GetFilename(); - - /** - * Sets the source file this generator reads from. - * @warning This method regenerates the model and gets rid of the old data. - * @param newPath The path to the file to load from. - */ - void SetSource(std::string newPath); + CFileWordGenerator(std::string path, int regen) + // This path is set manually for now debug/dev purposes. -rgee + : m_sPath("~/Desktop/test_text.txt"), + CWordGeneratorBase(regen) + {} + CFileWordGenerator(std::string path) + : m_sPath("~/Desktop/test_text.txt"), + CWordGeneratorBase(0) + {Generate();} + /** + * The generator function. In this implementation, it reads from a file to produce strings. + * @see CWordGeneratorBase::Generate + */ + virtual bool Generate(); + + /** + * Returns the next word that was read + * @return The next word in the word generator model if there is one. + * Otherwise, returns an empty string. + */ + virtual std::string GetNextWord(); + + + /** + * File path getter + * @return The path to the file this generator reads from. + */ + std::string GetPath(); + + /** + * File name getter + * @return The actual name of the file being read from + */ + std::string GetFilename(); + + /** + * Sets the source file this generator reads from. + * @warning This method regenerates the word generator model and gets rid of the old data. + * @param newPath The path to the file to load from. + */ + void SetSource(std::string newPath); + + /** + * Checks if there are any words left to produce. + * @return true if there are words left, false otherwise + */ + bool WordsLeft() { return m_bWordsLeft; } private: - /** - * The string that has been generated. - */ - std::string m_sGeneratedString; - - /** - * The path to the file this generator reads from. - */ - std::string m_sPath; - - /** - * The position we're currently reading from in the string. - */ - size_t m_uiPos; + /** + * The string that has been generated. + */ + std::string m_sGeneratedString; + + /** + * The path to the file this generator reads from. + */ + std::string m_sPath; + + /** + * The position we're currently reading from in the string. + */ + size_t m_uiPos; + + /** + * Flag for whether there are words left in this model. + */ + bool m_bWordsLeft; }; } + +#endif diff --git a/Src/DasherCore/GameModule.cpp b/Src/DasherCore/GameModule.cpp index 1a3c63f..dc619c3 100644 --- a/Src/DasherCore/GameModule.cpp +++ b/Src/DasherCore/GameModule.cpp @@ -1,100 +1,115 @@ #include "GameModule.h" using namespace Dasher; void CGameModule::HandleEvent(Dasher::CEvent *pEvent) { switch(pEvent->m_iEventType) { case EV_EDIT: { - CEditEvent* evt = static_cast<CEditEvent*>(pEvent); + CEditEvent* evt = static_cast<CEditEvent*>(pEvent); switch(evt->m_iEditType) { // Added a new character (Stepped one node forward) case 1: - if(!evt->m_sText.compare(m_sTargetString.substr(m_stCurrentStringPos + 1, 1))) - ++m_stCurrentStringPos; + // Check if the typed character is correct + if(!evt->m_sText.compare(m_sTargetString.substr(m_stCurrentStringPos + 1, 1))) { + // Check if we've reached the end of a chunk + if((m_stCurrentStringPos + 1) == m_sTargetString.length()) { + GenerateChunk(); + } else { + ++m_stCurrentStringPos; + } + } break; // Removed a character (Stepped one node back) case 0: g_pLogger->Log("Removed a character: " + evt->m_sText); break; default: break; } break; } case EV_TEXTDRAW: - { - CTextDrawEvent *evt = static_cast<CTextDrawEvent*>(pEvent); - if(!m_sTargetString.substr(m_stCurrentStringPos+1, 1).compare(evt->m_sDisplayText)) { - - //the x and y coordinates (in Dasher coords) of the target node - evt->m_pDasherView->Screen2Dasher(evt->m_iX, evt->m_iY, m_iTargetX, m_iTargetY); - } + { + CTextDrawEvent *evt = static_cast<CTextDrawEvent*>(pEvent); + // Check whether the text that was drawn is the current target character. + if(!m_sTargetString.substr(m_stCurrentStringPos + 1, 1).compare(evt->m_sDisplayText)) { + + //the x and y coordinates (in Dasher coords) of the target node + evt->m_pDasherView->Screen2Dasher(evt->m_iX, evt->m_iY, m_iTargetX, m_iTargetY); } - break; - default: + } break; + default: + break; } return; } bool CGameModule::DecorateView(CDasherView *pView) { screenint screenTargetX, screenTargetY; pView->Dasher2Screen(m_iTargetX, m_iTargetY, screenTargetX, screenTargetY); // Top Line screenint x[2] = {screenTargetX + m_iCrosshairExtent, screenTargetX - m_iCrosshairExtent}; screenint y[2] = {screenTargetY - m_iCrosshairExtent, screenTargetY - m_iCrosshairExtent}; pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Right Line x = {screenTargetX - m_iCrosshairExtent, screenTargetX - m_iCrosshairExtent}; y = {screenTargetY - m_iCrosshairExtent, screenTargetY + m_iCrosshairExtent}; pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Left Line x = {screenTargetX + m_iCrosshairExtent, screenTargetX + m_iCrosshairExtent}; y = {screenTargetY - m_iCrosshairExtent, screenTargetY + m_iCrosshairExtent}; pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Bottom Line x = {screenTargetX + m_iCrosshairExtent, screenTargetX - m_iCrosshairExtent}; y = {screenTargetY + m_iCrosshairExtent, screenTargetY + m_iCrosshairExtent}; pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Vertical Crosshair Line x = {screenTargetX, screenTargetX}; y = {screenTargetY + m_iCrosshairCrosslineLength, screenTargetY - m_iCrosshairCrosslineLength}; pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Horizontal Crosshair Line x = {screenTargetX + m_iCrosshairCrosslineLength, screenTargetX - m_iCrosshairCrosslineLength}; y = {screenTargetY, screenTargetY}; pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); return true; } //CDasherNode CGameModule::StringToNode(std::string sText) { // //} std::string CGameModule::GetTypedTarget() { return m_sTargetString.substr(0, m_stCurrentStringPos - 1); } std::string CGameModule::GetUntypedTarget() { return m_sTargetString.substr(m_stCurrentStringPos); } +void CGameModule::GenerateChunk() { + m_stCurrentStringPos = 0; + m_sTargetString.clear(); + for(int i = 0; i < m_iTargetChunkSize; i++) { + m_sTargetString += m_pWordGenerator->GetNextWord(); + } +} diff --git a/Src/DasherCore/GameModule.h b/Src/DasherCore/GameModule.h index 4f71eb8..646e41f 100644 --- a/Src/DasherCore/GameModule.h +++ b/Src/DasherCore/GameModule.h @@ -1,156 +1,191 @@ // GameModule.h -#ifndef GAME_MODULE_H -#define GAME_MODULE_H +#ifndef __GameModule_h__ +#define __GameModule_h__ #include <string> #include <cstring> using namespace std; -#include "DasherView.h" #include "DasherScreen.h" #include "DasherModel.h" #include "DasherModule.h" #include "DasherNode.h" #include "DasherView.h" #include "DasherTypes.h" #include "DasherInterfaceBase.h" +#include "WordGeneratorBase.h" namespace Dasher { /** * This Dasher Module encapsulates all game mode logic. In game mode, users will be given * a target string to type as well as visual feedback for their progress and a helpful * arrow to guide them in the right path through the dasher model. + * + * The way target strings will be displayed and reasoned about in code is in terms + * of chunks. Chunks represent the collection of strings that is displayed at once + * on the screen. After typing all the words in a given chunk, a new chunk of size + * m_iTargetChunkSize is gotten from the word generator and displayed. * * This class handles logic and drawing code with respect to the above. */ class CGameModule : public CDasherModule { public: // I don't actually know what the type is supposed to be for this...it's not an input method or an input filter. // Maybe we should define a new one. I've labeled it 0 for now. - rgee CGameModule(Dasher::CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, - CDasherInterfaceBase *pInterface, ModuleID_t iID, const char *szName, std::vector<int> vEvents) + CDasherInterfaceBase *pInterface, ModuleID_t iID, const char *szName, + std::vector<int> vEvents, CWordGeneratorBase* pWordGenerator) : m_iCrosshairColor(135), m_iCrosshairNumPoints(2), m_iCrosshairExtent(25), m_iCrosshairCrosslineLength(50), + m_iTargetChunkSize(3), + m_pWordGenerator(pWordGenerator), CDasherModule(pEventHandler, pSettingsStore, iID, 0, szName, vEvents) { m_pInterface = pInterface; //TODO REMOVE THIS!!! - m_sTargetString = "My name is julian."; - + if(m_pWordGenerator == NULL) + g_pLogger->Log("Word generator creation FAILED"); + GenerateChunk(); + if(m_sTargetString == "") + m_sTargetString = "My name is julian."; m_stCurrentStringPos = 0; - + } virtual ~CGameModule() {}; /** * Gets the typed portion of the target string * @return The string that represents the current word(s) that have not been typed */ std::string GetTypedTarget(); /** * Gets the portion of the target string that has yet to be completed * @return The string that represents the current word(s) that have been typed */ std::string GetUntypedTarget(); /** * Draws Game Mode specific visuals to the screen. * @param pView The Dasher View to be modified * @return True if the view was modified, false otherwise. */ bool DecorateView(CDasherView *pView); /** * Handle events from the event processing system * @param pEvent The event to be processed. */ virtual void HandleEvent(Dasher::CEvent *pEvent); private: + /** + * Helper function for generating (Or regenerating) a new chunk. + * @warning This will destroy the previous chunk. Only use when you + * need to grab an entirely new chunk to display. + */ + void GenerateChunk(); + /** * Get the distance of a given point (in Dasher Coordinates) from the origin. * * @param xCoord - the x coordinate of the point * @param yCoord - the y coordinate of the point * */ myint DistanceFromOrigin(myint xCoord, myint yCoord); /** * Searches for the dasher node under the current root that represents the desired string * @param text The string to search for * @return The node representing the string parameter */ //Dasher::CDasherNode StringToNode(std::string sText); - + + /** + * Pointer to the object that encapsulates the word generation + * algorithm being used. + */ + CWordGeneratorBase* m_pWordGenerator; + /** * The last node the user typed. */ CDasherNode *pLastTypedNode; /** * The next node (character) the user must type. */ CDasherNode *pNextTargetNode; /** * The target string the user must type. */ std::string m_sTargetString; /** * The current position in the string. * Stored as a size_t to easily use substrings to determine what's been typed and what hasn't. */ size_t m_stCurrentStringPos; /** * The dasher interface. */ CDasherInterfaceBase *m_pInterface; /** * The target x coordinate for the crosshair to point to. */ myint m_iTargetX; /** * The target y coordinate for the crosshair to point to. */ myint m_iTargetY; +/* --------------------------------------------------------------------- + * Constants + * --------------------------------------------------------------------- + */ + /** * The color (in Dasher colors) to make the crosshair. */ const int m_iCrosshairColor; /** * The number of points that the crosshair's lines pass through. */ const int m_iCrosshairNumPoints; /** * The side length (in pixels) of the crosshair's square portion. */ const int m_iCrosshairExtent; /** * The length of the lines comprising the crosshair's * "cross". */ const int m_iCrosshairCrosslineLength; + + /** + * The number of words displayed at once as a target for the user + * to type. + */ + const int m_iTargetChunkSize; }; } #endif diff --git a/Src/DasherCore/WordGeneratorBase.h b/Src/DasherCore/WordGeneratorBase.h index 1c2318b..857816a 100644 --- a/Src/DasherCore/WordGeneratorBase.h +++ b/Src/DasherCore/WordGeneratorBase.h @@ -1,52 +1,57 @@ +#ifndef __WordGeneratorBase_h__ +#define __WordGeneratorBase_h__ + #include <string> using namespace std; namespace Dasher { /** * The base class for all word generators. Word generators encapsulate * logic for simply generating words based on implementation-specific * conditions. Currently, this is being used to wrap GameMode's simple * text-file reading mechanism, but another generator can easily be * written that selects words based on a function of the current value * of the Sri Lankan rupee and the amount of twitter feeds regarding * the winter olympics, for example. */ class CWordGeneratorBase { public: - CWordGeneratorBase(int regen) : m_iRegenTime(regen), m_bWordsReady(false) {} - - virtual ~CWordGeneratorBase() { } - - - /** - * Gets a single word based on the generation rules. - * @pre { Generate must have been called at least once. } - * @return The next string from this generator - */ - virtual std::string GetNextWord() = 0; - - /** - * Gets the previous word in the generated string based on generation rules. - * @pre { Generate must have been called at least once. } - * @return The previous string from this generator - */ - //virtual std::string GetPrevWord() = 0; - - /** - * Generate the words based on the generation rules - * @return True if the generation succeeded, false if not. - * @warning The return value of this function should always be checked in case it's using files. - */ - virtual bool Generate() = 0; + CWordGeneratorBase(int regen) : m_iRegenTime(regen), m_bWordsReady(false) {} + + virtual ~CWordGeneratorBase() { } + + + /** + * Gets a single word based on the generation rules. + * @pre { Generate must have been called at least once. } + * @return The next string from this generator + */ + virtual std::string GetNextWord() = 0; + + /** + * Gets the previous word in the generated string based on generation rules. + * @pre { Generate must have been called at least once. } + * @return The previous string from this generator + */ + //virtual std::string GetPrevWord() = 0; + + /** + * Generate the words based on the generation rules + * @return True if the generation succeeded, false if not. + * @warning The return value of this function should always be checked in case it's using files + * or other solutions that can fail. + */ + virtual bool Generate() = 0; protected: - /** - * The time in seconds after which a generator should regenerate. - */ - int m_iRegenTime; - - /** - * A boolean representing whether the words have been generated yet. - */ - bool m_bWordsReady; + /** + * The time in seconds after which a generator should regenerate. + */ + int m_iRegenTime; + + /** + * A boolean representing whether the words have been generated yet. + */ + bool m_bWordsReady; }; } +#endif
rgee/HFOSS-Dasher
9e283614ac35fbfc91b63e5cb53090ac0471dcfe
Game Mode now looks for the appropriate letter after typing some.
diff --git a/Src/DasherCore/GameModule.cpp b/Src/DasherCore/GameModule.cpp index d14614f..1a3c63f 100644 --- a/Src/DasherCore/GameModule.cpp +++ b/Src/DasherCore/GameModule.cpp @@ -1,99 +1,100 @@ #include "GameModule.h" using namespace Dasher; void CGameModule::HandleEvent(Dasher::CEvent *pEvent) { switch(pEvent->m_iEventType) { case EV_EDIT: { CEditEvent* evt = static_cast<CEditEvent*>(pEvent); switch(evt->m_iEditType) { // Added a new character (Stepped one node forward) - case 0: - m_stCurrentStringPos++; - //pLastTypedNode = StringToNode(evt->m_sText); + case 1: + if(!evt->m_sText.compare(m_sTargetString.substr(m_stCurrentStringPos + 1, 1))) + ++m_stCurrentStringPos; break; // Removed a character (Stepped one node back) - case 1: + case 0: + g_pLogger->Log("Removed a character: " + evt->m_sText); break; default: break; } break; } case EV_TEXTDRAW: { CTextDrawEvent *evt = static_cast<CTextDrawEvent*>(pEvent); if(!m_sTargetString.substr(m_stCurrentStringPos+1, 1).compare(evt->m_sDisplayText)) { //the x and y coordinates (in Dasher coords) of the target node evt->m_pDasherView->Screen2Dasher(evt->m_iX, evt->m_iY, m_iTargetX, m_iTargetY); } } break; default: break; } return; } bool CGameModule::DecorateView(CDasherView *pView) { screenint screenTargetX, screenTargetY; pView->Dasher2Screen(m_iTargetX, m_iTargetY, screenTargetX, screenTargetY); // Top Line screenint x[2] = {screenTargetX + m_iCrosshairExtent, screenTargetX - m_iCrosshairExtent}; screenint y[2] = {screenTargetY - m_iCrosshairExtent, screenTargetY - m_iCrosshairExtent}; pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Right Line x = {screenTargetX - m_iCrosshairExtent, screenTargetX - m_iCrosshairExtent}; y = {screenTargetY - m_iCrosshairExtent, screenTargetY + m_iCrosshairExtent}; pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Left Line x = {screenTargetX + m_iCrosshairExtent, screenTargetX + m_iCrosshairExtent}; y = {screenTargetY - m_iCrosshairExtent, screenTargetY + m_iCrosshairExtent}; pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Bottom Line x = {screenTargetX + m_iCrosshairExtent, screenTargetX - m_iCrosshairExtent}; y = {screenTargetY + m_iCrosshairExtent, screenTargetY + m_iCrosshairExtent}; pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Vertical Crosshair Line x = {screenTargetX, screenTargetX}; y = {screenTargetY + m_iCrosshairCrosslineLength, screenTargetY - m_iCrosshairCrosslineLength}; pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); // Horizontal Crosshair Line x = {screenTargetX + m_iCrosshairCrosslineLength, screenTargetX - m_iCrosshairCrosslineLength}; y = {screenTargetY, screenTargetY}; pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); return true; } //CDasherNode CGameModule::StringToNode(std::string sText) { // //} std::string CGameModule::GetTypedTarget() { return m_sTargetString.substr(0, m_stCurrentStringPos - 1); } std::string CGameModule::GetUntypedTarget() { return m_sTargetString.substr(m_stCurrentStringPos); }
rgee/HFOSS-Dasher
815126f80b87d54dfdfab7b20d49d5d2f678755f
Fixed bug where listeners were not properly being added to the event system.
diff --git a/Src/DasherCore/EventHandler.cpp b/Src/DasherCore/EventHandler.cpp index 285caeb..adbdb25 100644 --- a/Src/DasherCore/EventHandler.cpp +++ b/Src/DasherCore/EventHandler.cpp @@ -1,112 +1,116 @@ #include "../Common/Common.h" #include "EventHandler.h" #include "DasherComponent.h" #include "DasherInterfaceBase.h" #include "Event.h" #include <algorithm> #include <iostream> using namespace Dasher; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif +#include <sstream> + void CEventHandler::InsertEvent(CEvent *pEvent) { - ++m_iInHandler; + ++m_iInHandler; - for(std::vector<CDasherComponent*>::const_iterator it = m_vSpecificListeners[pEvent->m_iEventType].begin(); - it != m_vSpecificListeners[pEvent->m_iEventType].end(); - ++it) - { - (*it)->HandleEvent(pEvent); - } + for(std::vector<CDasherComponent*>::const_iterator it = m_vSpecificListeners[pEvent->m_iEventType - 1].begin(); + it != m_vSpecificListeners[pEvent->m_iEventType - 1].end(); + ++it) + { + (*it)->HandleEvent(pEvent); + } - m_pInterface->InterfaceEventHandler(pEvent); - - m_pInterface->ExternalEventHandler(pEvent); + m_pInterface->InterfaceEventHandler(pEvent); + + m_pInterface->ExternalEventHandler(pEvent); - --m_iInHandler; + --m_iInHandler; - if(m_iInHandler == 0) { - - //loop through the queue of specific listeners waiting to be registered and register them - for(ListenerQueue::iterator it = m_vSpecificListenerQueue.begin(); it != m_vSpecificListenerQueue.end(); ++it) { - RegisterListener((*it).first, (*it).second); - } - } + if(m_iInHandler == 0) { + + //loop through the queue of specific listeners waiting to be registered and register them + for(ListenerQueue::iterator it = m_vSpecificListenerQueue.begin(); it != m_vSpecificListenerQueue.end(); ++it) { + RegisterListener((*it).first, (*it).second); + } + } } void CEventHandler::RegisterListener(CDasherComponent *pListener) { - - if(std::find(m_vGeneralListenerQueue.begin(), m_vGeneralListenerQueue.end(), pListener) == m_vGeneralListenerQueue.end()) { - return; - } - else { - - for(ListenerMap::iterator it = m_vSpecificListeners.begin(); it != m_vSpecificListeners.end(); ++it) { - - if((std::find((*it).begin(), (*it).end(), pListener) == (*it).end())) { - if(m_iInHandler == 0) { - (*it).push_back(pListener); - } - else { - m_vGeneralListenerQueue.push_back(pListener); - } - } - else { - // Can't add the same listener twice - } - } + // If the listener is in the queue waiting to be added, don't add it again + if((std::find(m_vGeneralListenerQueue.begin(), m_vGeneralListenerQueue.end(), pListener) != m_vGeneralListenerQueue.end())) { + return; + } + else { + // For each event listener list, either add it or queue it... + for(ListenerMap::iterator it = m_vSpecificListeners.begin(); it != m_vSpecificListeners.end(); ++it) { + //...but only if it doesn't already exist + if((std::find((*it).begin(), (*it).end(), pListener) == (*it).end())) { + + if(m_iInHandler == 0) { + (*it).push_back(pListener); + } + else { + m_vGeneralListenerQueue.push_back(pListener); + } + } + else { + // Can't add the same listener twice + } + } } } void CEventHandler::RegisterListener(CDasherComponent *pListener, int iEventType) { - - if((std::find(m_vSpecificListeners[iEventType].begin(), m_vSpecificListeners[iEventType].end(), pListener) == m_vSpecificListeners[iEventType].end())) { - if(m_iInHandler == 0) - m_vSpecificListeners[iEventType].push_back(pListener); - else - m_vSpecificListenerQueue.push_back(std::make_pair(pListener, iEventType)); - } - else { - // Can't add the same listener twice - } + // Only try to add a new listener if it doesn't already exist in the Listener map + if((std::find(m_vSpecificListeners[iEventType - 1].begin(), m_vSpecificListeners[iEventType - 1].end(), pListener) == m_vSpecificListeners[iEventType - 1].end())) { + if(m_iInHandler == 0) + m_vSpecificListeners[iEventType - 1].push_back(pListener); + else + // Add the listener to the queue if events are being processed + m_vSpecificListenerQueue.push_back(std::make_pair(pListener, iEventType)); + } + else { + // Can't add the same listener twice + } } void CEventHandler::UnregisterListener(CDasherComponent *pListener, int iEventType) { - for(std::vector<CDasherComponent*>::iterator it = m_vSpecificListeners[iEventType].begin(); it != m_vSpecificListeners[iEventType].end(); ++it) { - if( (*it) == pListener) - m_vSpecificListeners[iEventType].erase(it); - } + for(std::vector<CDasherComponent*>::iterator it = m_vSpecificListeners[iEventType].begin(); it != m_vSpecificListeners[iEventType].end(); ++it) { + if( (*it) == pListener) + m_vSpecificListeners[iEventType].erase(it); + } } void CEventHandler::UnregisterListener(CDasherComponent *pListener) { - std::vector < CDasherComponent * >::iterator mapFound; + std::vector < CDasherComponent * >::iterator mapFound; - for(ListenerMap::iterator it = m_vSpecificListeners.begin(); it != m_vSpecificListeners.end(); ++it) { - mapFound = std::find((*it).begin(), (*it).end(), pListener); - if(mapFound != (*it).end()) - (*it).erase(mapFound); - } + for(ListenerMap::iterator it = m_vSpecificListeners.begin(); it != m_vSpecificListeners.end(); ++it) { + mapFound = std::find((*it).begin(), (*it).end(), pListener); + if(mapFound != (*it).end()) + (*it).erase(mapFound); + } - std::vector < CDasherComponent * >::iterator queueFound = std::find(m_vGeneralListenerQueue.begin(), m_vGeneralListenerQueue.end(), pListener); - if(queueFound != m_vGeneralListenerQueue.end()) - m_vGeneralListenerQueue.erase(queueFound); + std::vector < CDasherComponent * >::iterator queueFound = std::find(m_vGeneralListenerQueue.begin(), m_vGeneralListenerQueue.end(), pListener); + if(queueFound != m_vGeneralListenerQueue.end()) + m_vGeneralListenerQueue.erase(queueFound); - for(ListenerQueue::iterator it = m_vSpecificListenerQueue.begin(); it != m_vSpecificListenerQueue.end(); ++it) { - if((*it).first == pListener) { - it = m_vSpecificListenerQueue.erase(it); - } - } + for(ListenerQueue::iterator it = m_vSpecificListenerQueue.begin(); it != m_vSpecificListenerQueue.end(); ++it) { + if((*it).first == pListener) { + it = m_vSpecificListenerQueue.erase(it); + } + } }
rgee/HFOSS-Dasher
b31ac5a0c2c2be35684ea3c946428fb03e473729
Game mode now draws a crosshair over the target letter.
diff --git a/Src/DasherCore/GameModule.cpp b/Src/DasherCore/GameModule.cpp index 900c336..cd901ee 100644 --- a/Src/DasherCore/GameModule.cpp +++ b/Src/DasherCore/GameModule.cpp @@ -1,72 +1,100 @@ #include "GameModule.h" using namespace Dasher; void CGameModule::HandleEvent(Dasher::CEvent *pEvent) { - switch(pEvent->m_iEventType) - { - case EV_EDIT: - { - CEditEvent* evt = static_cast<CEditEvent*>(pEvent); + switch(pEvent->m_iEventType) + { + case EV_EDIT: + { + CEditEvent* evt = static_cast<CEditEvent*>(pEvent); - switch(evt->m_iEditType) - { - // Added a new character (Stepped one node forward) - case 0: - m_stCurrentStringPos++; - //pLastTypedNode = StringToNode(evt->m_sText); - break; - // Removed a character (Stepped one node back) - case 1: - break; - default: - break; - } - break; - } - case EV_TEXTDRAW: - { - CTextDrawEvent *evt = static_cast<CTextDrawEvent*>(pEvent); - if(!m_sTargetString.substr(m_stCurrentStringPos+1, 1).compare(evt->m_sDisplayText)) { - - //the x and y coordinates (in Dasher coords) of the target node - myint xDasherCoord, yDasherCoord; - evt->m_pDasherView->Screen2Dasher(evt->m_iX, evt->m_iY, xCoord, yCoord); - - if(xDasherCoord < GetLongParameter(LP_OX) && ) - } - } - break; + switch(evt->m_iEditType) + { + // Added a new character (Stepped one node forward) + case 0: + m_stCurrentStringPos++; + //pLastTypedNode = StringToNode(evt->m_sText); + break; + // Removed a character (Stepped one node back) + case 1: + break; + default: + break; + } + break; + } + case EV_TEXTDRAW: + { + CTextDrawEvent *evt = static_cast<CTextDrawEvent*>(pEvent); + if(!m_sTargetString.substr(m_stCurrentStringPos+1, 1).compare(evt->m_sDisplayText)) { + + //the x and y coordinates (in Dasher coords) of the target node + evt->m_pDasherView->Screen2Dasher(evt->m_iX, evt->m_iY, m_iTargetX, m_iTargetY); + } + } + break; default: - break; + break; - } - return; + } + return; } bool CGameModule::DecorateView(CDasherView *pView) { - - //set up the points for the arrow to pass through - - //starts at the crosshair, ends at the target letter - myint x[2] = {GetLongParameter(LP_OX), m_iTargetX}; - myint y[2] = {GetLongParameter(LP_OY), m_iTargetY}; - - pView->DasherPolyarrow(x, y, m_iArrowNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iArrowColor, m_dArrowSizeFactor); - + screenint screenTargetX, screenTargetY; + pView->Dasher2Screen(m_iTargetX, m_iTargetY, screenTargetX, screenTargetY); + + + // Top Line + screenint x[2] = {screenTargetX + m_iCrosshairExtent, screenTargetX - m_iCrosshairExtent}; + screenint y[2] = {screenTargetY - m_iCrosshairExtent, screenTargetY - m_iCrosshairExtent}; + pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); + + + // Right Line + x = {screenTargetX - m_iCrosshairExtent, screenTargetX - m_iCrosshairExtent}; + y = {screenTargetY - m_iCrosshairExtent, screenTargetY + m_iCrosshairExtent}; + pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); + + + // Left Line + x = {screenTargetX + m_iCrosshairExtent, screenTargetX + m_iCrosshairExtent}; + y = {screenTargetY - m_iCrosshairExtent, screenTargetY + m_iCrosshairExtent}; + pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); + + + // Bottom Line + x = {screenTargetX + m_iCrosshairExtent, screenTargetX - m_iCrosshairExtent}; + y = {screenTargetY + m_iCrosshairExtent, screenTargetY + m_iCrosshairExtent}; + pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); + + + // Vertical Crosshair Line + x = {screenTargetX, screenTargetX}; + y = {screenTargetY + m_iCrosshairCrosslineLength, screenTargetY - m_iCrosshairCrosslineLength}; + pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); + + + // Horizontal Crosshair Line + x = {screenTargetX + m_iCrosshairCrosslineLength, screenTargetX - m_iCrosshairCrosslineLength}; + y = {screenTargetY, screenTargetY}; + pView->ScreenPolyline(x, y, m_iCrosshairNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iCrosshairColor); + return true; } //CDasherNode CGameModule::StringToNode(std::string sText) { -// +// //} std::string CGameModule::GetTypedTarget() { - return m_sTargetString.substr(0, m_stCurrentStringPos - 1); + return m_sTargetString.substr(0, m_stCurrentStringPos - 1); } std::string CGameModule::GetUntypedTarget() { - return m_sTargetString.substr(m_stCurrentStringPos); + return m_sTargetString.substr(m_stCurrentStringPos); } diff --git a/Src/DasherCore/GameModule.h b/Src/DasherCore/GameModule.h index cb55711..db0eba0 100644 --- a/Src/DasherCore/GameModule.h +++ b/Src/DasherCore/GameModule.h @@ -1,150 +1,156 @@ // GameModule.h #ifndef GAME_MODULE_H #define GAME_MODULE_H #include <string> #include <cstring> using namespace std; #include "DasherView.h" +#include "DasherScreen.h" #include "DasherModel.h" #include "DasherModule.h" #include "DasherNode.h" #include "DasherView.h" #include "DasherTypes.h" #include "DasherInterfaceBase.h" namespace Dasher { /** * This Dasher Module encapsulates all game mode logic. In game mode, users will be given * a target string to type as well as visual feedback for their progress and a helpful * arrow to guide them in the right path through the dasher model. * * This class handles logic and drawing code with respect to the above. */ class CGameModule : public CDasherModule { public: // I don't actually know what the type is supposed to be for this...it's not an input method or an input filter. // Maybe we should define a new one. I've labeled it 0 for now. - rgee CGameModule(Dasher::CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CDasherInterfaceBase *pInterface, ModuleID_t iID, const char *szName) - : m_iArrowColor(135), - m_dArrowSizeFactor(0.1), - m_iArrowNumPoints(2), + : m_iCrosshairColor(135), + m_iCrosshairNumPoints(2), + m_iCrosshairExtent(25), + m_iCrosshairCrosslineLength(50), CDasherModule(pEventHandler, pSettingsStore, iID, 0, szName) - { - m_pInterface = pInterface; - - //TODO REMOVE THIS!!! - m_sTargetString = "My name is julian."; + { + m_pInterface = pInterface; + + //TODO REMOVE THIS!!! + m_sTargetString = "My name is julian."; - m_stCurrentStringPos = 0; + m_stCurrentStringPos = 0; } virtual ~CGameModule() {}; /** * Gets the typed portion of the target string * @return The string that represents the current word(s) that have not been typed */ std::string GetTypedTarget(); /** * Gets the portion of the target string that has yet to be completed * @return The string that represents the current word(s) that have been typed */ std::string GetUntypedTarget(); - bool DecorateView(CDasherView *pView); - void SetDasherModel(CDasherModel *pModel) { m_pModel = pModel; } + /** + * Draws Game Mode specific visuals to the screen. + * @param pView The Dasher View to be modified + * @return True if the view was modified, false otherwise. + */ + bool DecorateView(CDasherView *pView); /** * Handle events from the event processing system * @param pEvent The event to be processed. */ virtual void HandleEvent(Dasher::CEvent *pEvent); private: /** * Get the distance of a given point (in Dasher Coordinates) from the origin. * * @param xCoord - the x coordinate of the point * @param yCoord - the y coordinate of the point * */ myint DistanceFromOrigin(myint xCoord, myint yCoord); /** * Searches for the dasher node under the current root that represents the desired string * @param text The string to search for * @return The node representing the string parameter */ //Dasher::CDasherNode StringToNode(std::string sText); /** * The last node the user typed. */ CDasherNode *pLastTypedNode; /** * The next node (character) the user must type. */ CDasherNode *pNextTargetNode; /** * The target string the user must type. - */ + */ std::string m_sTargetString; /** * The current position in the string. * Stored as a size_t to easily use substrings to determine what's been typed and what hasn't. */ size_t m_stCurrentStringPos; - /** - * The dasher model. - */ - CDasherModel *m_pModel; - /** * The dasher interface. */ CDasherInterfaceBase *m_pInterface; /** - * The target x coordinate for the arrow to point to. + * The target x coordinate for the crosshair to point to. */ myint m_iTargetX; /** - * The target y coordinate for the arrow to point to. + * The target y coordinate for the crosshair to point to. */ myint m_iTargetY; /** - * The color (in Dasher colors) to make the guiding arrow. + * The color (in Dasher colors) to make the crosshair. */ - const int m_iArrowColor; - + const int m_iCrosshairColor; /** - * The factor by which the size the hat on the guiding arrow + * The number of points that the crosshair's lines pass through. */ - const double m_dArrowSizeFactor; - + const int m_iCrosshairNumPoints; + + /** + * The side length (in pixels) of the crosshair's square portion. + */ + const int m_iCrosshairExtent; + /** - * The number of points that the guiding arrow passes through + * The length of the lines comprising the crosshair's + * "cross". */ - const int m_iArrowNumPoints; + const int m_iCrosshairCrosslineLength; }; } #endif
rgee/HFOSS-Dasher
86fb3796ac79b72fe10c2db0e9df5ea65c0815eb
Wrote a function that draws lines in screen space so that we can have visuals that don't resize with dasher coords.
diff --git a/Src/DasherCore/DasherView.cpp b/Src/DasherCore/DasherView.cpp index 08b9f6a..3701eac 100644 --- a/Src/DasherCore/DasherView.cpp +++ b/Src/DasherCore/DasherView.cpp @@ -1,299 +1,317 @@ // DasherView.cpp // // Copyright (c) 2008 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" #include "DasherGameMode.h" #include "DasherInput.h" #include "DasherModel.h" #include "DasherView.h" #include "Event.h" #include "EventHandler.h" #include "DasherScreen.h" using namespace Dasher; using std::vector; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG_MEMLEAKS #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif ///////////////////////////////////////////////////////////////////////////// CDasherView::CDasherView(CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CDasherScreen *DasherScreen) :CDasherComponent(pEventHandler, pSettingsStore), m_pScreen(DasherScreen), m_pInput(0), m_bDemoMode(false), m_bGameMode(false) { } ///////////////////////////////////////////////////////////////////////////// void CDasherView::ChangeScreen(CDasherScreen *NewScreen) { m_pScreen = NewScreen; } ///////////////////////////////////////////////////////////////////////////// void CDasherView::Render(CDasherNode *pRoot, myint iRootMin, myint iRootMax, CExpansionPolicy &policy, bool bRedrawDisplay) { m_iRenderCount = 0; Screen()->SetLoadBackground(false); RenderNodes(pRoot, iRootMin, iRootMax, policy); } int CDasherView::GetCoordinateCount() { // TODO: Do we really need support for co-ordinate counts other than 2? if(m_pInput) return m_pInput->GetCoordinateCount(); else return 0; } int CDasherView::GetInputCoordinates(int iN, myint * pCoordinates) { if(m_pInput) return m_pInput->GetCoordinates(iN, pCoordinates); else return 0; } void CDasherView::SetInput(CDasherInput * _pInput) { // TODO: Is it sensible to make this responsible for the input // device - I guess it makes sense for now DASHER_ASSERT_VALIDPTR_RW(_pInput); // Don't delete the old input class; whoever is calling this method // might want to keep several Input class instances around and // change which one is currently driving dasher without deleting any m_pInput = _pInput; // Tell the new object about maximum values myint iMaxCoordinates[2]; iMaxCoordinates[0] = GetLongParameter(LP_MAX_Y); iMaxCoordinates[1] = GetLongParameter(LP_MAX_Y); m_pInput->SetMaxCoordinates(2, iMaxCoordinates); } void CDasherView::Display() { Screen()->SetLoadBackground(true); m_pScreen->Display(); } void CDasherView::DasherSpaceLine(myint x1, myint y1, myint x2, myint y2, int iWidth, int iColor) { if (!ClipLineToVisible(x1, y1, x2, y2)) return; vector<CDasherScreen::point> vPoints; CDasherScreen::point p; Dasher2Screen(x1, y1, p.x, p.y); vPoints.push_back(p); DasherLine2Screen(x1,y1,x2,y2,vPoints); CDasherScreen::point *pts = new CDasherScreen::point[vPoints.size()]; for (int i = vPoints.size(); i-->0; ) pts[i] = vPoints[i]; Screen()->Polyline(pts, vPoints.size(), iWidth, iColor); } bool CDasherView::ClipLineToVisible(myint &x1, myint &y1, myint &x2, myint &y2) { if (x1 > x2) return ClipLineToVisible(x2,y2,x1,y1); //ok. have x1 <= x2... myint iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); if (x1 > iDasherMaxX) { DASHER_ASSERT(x2>iDasherMaxX); return false; //entirely offscreen! } if (x2 < iDasherMinX) { DASHER_ASSERT(x1<iDasherMinX); return false; } if (y1 < iDasherMinY && y2 < iDasherMinY) return false; if (y1 > iDasherMaxY && y2 > iDasherMaxY) return false; if (x1 < iDasherMinX) { y1 = y2+((y1-y2)*(iDasherMinX-x2)/(x1 - x2)); x1 = iDasherMinX; } if (x2 > iDasherMaxX) { y2 = y1 + (y2-y1)*(iDasherMaxX-x1)/(x2-x1); x2 = iDasherMaxX; } for (int i=0; i<2; i++) { myint &y(i ? y2 : y1), &oy(i ? y1 : y2); myint &x(i ? x2 : x1), &ox(i ? x1 : x2); if (y<iDasherMinY) { x = ox- (ox-x)*(oy-iDasherMinY)/(oy-y); y = iDasherMinY; } else if (y>iDasherMaxY) { x = ox-(ox-x)*(oy-iDasherMaxY)/(oy-y); y = iDasherMaxY; } } return true; } - /// Draw a polyline specified in Dasher co-ordinates + void CDasherView::DasherPolyline(myint *x, myint *y, int n, int iWidth, int iColour) { CDasherScreen::point * ScreenPoints = new CDasherScreen::point[n]; for(int i(0); i < n; ++i) Dasher2Screen(x[i], y[i], ScreenPoints[i].x, ScreenPoints[i].y); if(iColour != -1) { Screen()->Polyline(ScreenPoints, n, iWidth, iColour); } else { Screen()->Polyline(ScreenPoints, n, iWidth,0);//no color given } delete[]ScreenPoints; } +void CDasherView::ScreenPolyline(screenint *x, screenint *y, int n, int iWidth, int iColour) { + CDasherScreen::point * ScreenPoints = new CDasherScreen::point[n]; + + for(int i(0); i < n; ++i) + { + ScreenPoints[i].x = x[i]; + ScreenPoints[i].y = y[i]; + } + + if(iColour != -1) { + Screen()->Polyline(ScreenPoints, n, iWidth, iColour); + } + else { + Screen()->Polyline(ScreenPoints, n, iWidth, 0); + } + delete[] ScreenPoints; +} + // Draw a polyline with an arrow on the end void CDasherView::DasherPolyarrow(myint *x, myint *y, int n, int iWidth, int iColour, double dArrowSizeFactor) { CDasherScreen::point * ScreenPoints = new CDasherScreen::point[n+3]; for(int i(0); i < n; ++i) Dasher2Screen(x[i], y[i], ScreenPoints[i].x, ScreenPoints[i].y); int iXvec = (int)((ScreenPoints[n-2].x - ScreenPoints[n-1].x)*dArrowSizeFactor); int iYvec = (int)((ScreenPoints[n-2].y - ScreenPoints[n-1].y)*dArrowSizeFactor); ScreenPoints[n].x = ScreenPoints[n-1].x + iXvec + iYvec; ScreenPoints[n].y = ScreenPoints[n-1].y - iXvec + iYvec; ScreenPoints[n+1].x = ScreenPoints[n-1].x ; ScreenPoints[n+1].y = ScreenPoints[n-1].y ; ScreenPoints[n+2].x = ScreenPoints[n-1].x + iXvec - iYvec; ScreenPoints[n+2].y = ScreenPoints[n-1].y + iXvec + iYvec; if(iColour != -1) { Screen()->Polyline(ScreenPoints, n+3, iWidth, iColour); } else { Screen()->Polyline(ScreenPoints, n+3, iWidth,0);//no color given } delete[]ScreenPoints; } // Draw a box specified in Dasher co-ordinates void CDasherView::DasherDrawRectangle(myint iLeft, myint iTop, myint iRight, myint iBottom, const int Color, int iOutlineColour, Opts::ColorSchemes ColorScheme, int iThickness) { screenint iScreenLeft; screenint iScreenTop; screenint iScreenRight; screenint iScreenBottom; Dasher2Screen(iLeft, iTop, iScreenLeft, iScreenTop); Dasher2Screen(iRight, iBottom, iScreenRight, iScreenBottom); Screen()->DrawRectangle(iScreenLeft, iScreenTop, iScreenRight, iScreenBottom, Color, iOutlineColour, ColorScheme, iThickness); } /// Draw a rectangle centred on a given dasher co-ordinate, but with a size specified in screen co-ordinates (used for drawing the mouse blob) void CDasherView::DasherDrawCentredRectangle(myint iDasherX, myint iDasherY, screenint iSize, const int Color, Opts::ColorSchemes ColorScheme, bool bDrawOutline) { screenint iScreenX; screenint iScreenY; Dasher2Screen(iDasherX, iDasherY, iScreenX, iScreenY); Screen()->DrawRectangle(iScreenX - iSize, iScreenY - iSize, iScreenX + iSize, iScreenY + iSize, Color, -1, ColorScheme, bDrawOutline ? 1 : 0); } void CDasherView::DrawText(const std::string & str, myint x, myint y, int Size, int iColor) { screenint X, Y; Dasher2Screen(x, y, X, Y); Screen()->DrawString(str, X, Y, Size, iColor); } int CDasherView::GetCoordinates(myint &iDasherX, myint &iDasherY) { // FIXME - Actually turn autocalibration on and off! // FIXME - AutoCalibrate should use Dasher co-ordinates, not raw mouse co-ordinates? // FIXME - Have I broken this by moving it before the offset is applied? // FIXME - put ymap stuff back in // FIXME - optimise this int iCoordinateCount(GetCoordinateCount()); myint *pCoordinates(new myint[iCoordinateCount]); int iType(GetInputCoordinates(iCoordinateCount, pCoordinates)); screenint mousex; screenint mousey; if(iCoordinateCount == 1) { mousex = 0; mousey = pCoordinates[0]; } else { mousex = pCoordinates[0]; mousey = pCoordinates[1]; } delete[]pCoordinates; switch(iType) { case 0: Screen2Dasher(mousex, mousey, iDasherX, iDasherY); break; case 1: iDasherX = mousex; iDasherY = mousey; break; default: // TODO: Error break; } ///GAME/// if(m_bGameMode) { using GameMode::CDasherGameMode; if(m_bDemoMode) CDasherGameMode::GetTeacher()->DemoModeGetCoordinates(iDasherX, iDasherY); CDasherGameMode::GetTeacher()->SetUserMouseCoordinates(iDasherX, iDasherY); } return iType; } void CDasherView::SetDemoMode(bool bDemoMode) { m_bDemoMode = bDemoMode; } void CDasherView::SetGameMode(bool bGameMode) { m_bGameMode = bGameMode; } diff --git a/Src/DasherCore/DasherView.h b/Src/DasherCore/DasherView.h index 8746051..d9ae545 100644 --- a/Src/DasherCore/DasherView.h +++ b/Src/DasherCore/DasherView.h @@ -1,226 +1,235 @@ // DasherView.h // // Copyright (c) 2001-2005 David Ward #ifndef __DasherView_h_ #define __DasherView_h_ namespace Dasher { class CDasherModel; class CDasherInput; // Why does DasherView care about input? - pconlon class CDasherComponent; class CDasherView; class CDasherNode; } #include "DasherTypes.h" #include "DasherComponent.h" #include "ExpansionPolicy.h" #include "DasherScreen.h" /// \defgroup View Visualisation of the model /// @{ /// \brief View base class. /// /// Dasher views represent the visualisation of a Dasher model on the screen. /// /// Note that we really should aim to avoid having to try and keep /// multiple pointers to the same object (model etc.) up-to-date at /// once. We should be able to avoid the need for this just by being /// sane about passing pointers as arguments to the relevant /// functions, for example we could pass a pointer to the canvas every /// time we call the render routine, rather than worrying about /// notifying this object every time it changes. The same logic can be /// applied in several other places. /// /// We should also attempt to try and remove the need for this class /// to know about the model. When we call render we should just pass a /// pointer to the root node, which we can obtain elsewhere, and make /// sure that the data structure contains all the info we need to do /// the rendering (eg make sure it contains strings as well as symbol /// IDs). /// /// There are really three roles played by CDasherView: providing high /// level drawing functions, providing a mapping between Dasher /// co-ordinates and screen co-ordinates and providing a mapping /// between true and effective Dasher co-ordinates (eg for eyetracking /// mode). We should probably consider creating separate classes for /// these. class Dasher::CDasherView : public Dasher::CDasherComponent { public: /// Constructor /// /// \param pEventHandler Pointer to the event handler /// \param pSettingsStore Pointer to the settings store /// \param DasherScreen Pointer to the CDasherScreen object used to do rendering CDasherView(CEventHandler * pEventHandler, CSettingsStore * pSettingsStore, CDasherScreen * DasherScreen); virtual ~CDasherView() { } /// @name Pointing device mappings /// @{ /// Set the input device class. Note that this class will now assume ownership of the pointer, ie it will delete the object when it's done with it. /// \param _pInput Pointer to the new CDasherInput. void SetInput(CDasherInput * _pInput); void SetDemoMode(bool); void SetGameMode(bool); /// Translates the screen coordinates to Dasher coordinates and calls /// dashermodel.TapOnDisplay virtual int GetCoordinates(myint &iDasherX, myint &iDasherY); /// Get the co-ordinate count from the input device int GetCoordinateCount(); /// @} /// /// @name Coordinate system conversion /// Convert between screen and Dasher coordinates /// @{ /// /// Convert a screen co-ordinate to Dasher co-ordinates /// virtual void Screen2Dasher(screenint iInputX, screenint iInputY, myint & iDasherX, myint & iDasherY) = 0; /// /// Convert Dasher co-ordinates to screen co-ordinates /// virtual void Dasher2Screen(myint iDasherX, myint iDasherY, screenint & iScreenX, screenint & iScreenY) = 0; /// /// Convert Dasher co-ordinates to polar co-ordinates (r,theta), with 0<r<1, 0<theta<2*pi /// virtual void Dasher2Polar(myint iDasherX, myint iDasherY, double &r, double &theta) = 0; virtual bool IsSpaceAroundNode(myint y1, myint y2)=0; virtual void VisibleRegion( myint &iDasherMinX, myint &iDasherMinY, myint &iDasherMaxX, myint &iDasherMaxY ) = 0; /// @} /// Change the screen - must be called if the Screen is replaced or resized /// \param NewScreen Pointer to the new CDasherScreen. virtual void ChangeScreen(CDasherScreen * NewScreen); /// @name High level drawing /// Drawing more complex structures, generally implemented by derived class /// @{ /// Renders Dasher with mouse-dependent items /// \todo Clarify relationship between Render functions and probably only expose one virtual void Render(CDasherNode *pRoot, myint iRootMin, myint iRootMax, CExpansionPolicy &policy, bool bRedrawDisplay); /// @} ////// Return a reference to the screen - can't be protected due to circlestarthandler CDasherScreen *Screen() { return m_pScreen; } /// /// @name Low level drawing /// Basic drawing primitives specified in Dasher coordinates. /// @{ ///Draw a straight line in Dasher-space - which may be curved on the screen... void DasherSpaceLine(myint x1, myint y1, myint x2, myint y2, int iWidth, int iColour); /// /// Draw a polyline specified in Dasher co-ordinates /// void DasherPolyline(myint * x, myint * y, int n, int iWidth, int iColour); + + /** + * Draw a line in screen coordinates. Needed for drawing without respect to + * the strange squishing and resizing that can happen when drawing in Dasher + * coordinates. + * + * @see DasherPolyline + */ + void ScreenPolyline(screenint * x, screenint * y, int n, int iWidth, int iColour); /** * Draw an arrow in Dasher space. The parameters x and y allow the client to specify * points through which the arrow's main line should be drawn. For example, to draw an * arrow through the Dasher coordinates (1000, 2000) and (3000, 4000), one would pass in: * * myint x[2] = {1000, 3000}; * myint y[2] = {2000, 4000}; * * @param x - an array of x coordinates to draw the arrow through * @param y - an array of y coordinates to draw the arrow through * @param iWidth - the width to make the arrow lines - typically of the form - * GetLongParameter(LP_LINE_WIDTH)*CONSTANT + * GetLongParameter(LP_LINE_WIDTH)*CONSTANT * @param iColour - the color to make the arrow (in Dasher color) * @param dArrowSizeFactor - the factor by which to scale the "hat" on the arrow */ void DasherPolyarrow(myint * x, myint * y, int n, int iWidth, int iColour, double dArrowSizeFactor = 0.7071); /// /// Draw a rectangle specified in Dasher co-ordinates /// Color of -1 => no fill; any other value => fill in that color /// iOutlineColor of -1 => no outline; any other value => outline in that color, EXCEPT /// Thickness < 1 => no outline. /// void DasherDrawRectangle(myint iLeft, myint iTop, myint iRight, myint iBottom, const int Color, int iOutlineColour, Opts::ColorSchemes ColorScheme, int iThickness); /// /// Draw a centred rectangle specified in Dasher co-ordinates (used for mouse cursor) /// void DasherDrawCentredRectangle(myint iDasherX, myint iDasherY, screenint iSize, const int Color, Opts::ColorSchemes ColorScheme, bool bDrawOutline); void DrawText(const std::string & str, myint x, myint y, int Size, int iColor); /// Request the Screen to copy its buffer to the Display /// \todo Shouldn't be public? void Display(); /// @} protected: /// Clips a line (specified in Dasher co-ordinates) to the visible region /// by intersecting with all boundaries. /// \return true if any part of the line was within the visible region; in this case, (x1,y1)-(x2,y2) delineate exactly that part /// false if the line would be entirely outside the visible region; x1, y1, x2, y2 unaffected. bool ClipLineToVisible(myint &x1, myint &y1, myint &x2, myint &y2); ///Convert a straight line in Dasher-space, to coordinates for a corresponding polyline on the screen /// (because of nonlinearity, this may require multiple line segments) /// \param x1,y1 Dasher co-ordinates of start of line segment; note that these are guaranteed within VisibleRegion. /// \param x2,y2 Dasher co-ordinates of end of line segment; also guaranteed within VisibleRegion. /// \param vPoints vector to which to add screen points. Note that at the point that DasherLine2Screen is called, /// the screen coordinates of the first point should already have been added to this vector; DasherLine2Screen /// will then add exactly one CDasherScreen::point for each line segment required. virtual void DasherLine2Screen(myint x1, myint y1, myint x2, myint y2, std::vector<CDasherScreen::point> &vPoints)=0; // Orientation of Dasher Screen /* inline void MapScreen(screenint * DrawX, screenint * DrawY); */ /* inline void UnMapScreen(screenint * DrawX, screenint * DrawY); */ bool m_bVisibleRegionValid; int m_iRenderCount; private: CDasherScreen *m_pScreen; // provides the graphics (text, lines, rectangles): CDasherInput *m_pInput; // Input device abstraction /// Renders the Dasher node structure virtual void RenderNodes(CDasherNode *pRoot, myint iRootMin, myint iRootMax, CExpansionPolicy &policy) = 0; /// Get the co-ordinates from the input device int GetInputCoordinates(int iN, myint * pCoordinates); bool m_bDemoMode; bool m_bGameMode; }; /// @} #endif /* #ifndef __DasherView_h_ */
rgee/HFOSS-Dasher
0c17d3550cf7c212e5ec2e0d1cb050c69da16678
The new event system is now compiling, and it appears to be working properly at runtime. Still need to test/add documentation.
diff --git a/Src/DasherCore/Event.h b/Src/DasherCore/Event.h index 221aebd..e3303ce 100644 --- a/Src/DasherCore/Event.h +++ b/Src/DasherCore/Event.h @@ -1,181 +1,179 @@ #ifndef __event_h__ #define __event_h__ // Classes representing different event types. #include <string> #include "DasherTypes.h" namespace Dasher { class CEvent; class CTextDrawEvent; class CParameterNotificationEvent; class CEditEvent; class CEditContextEvent; class CStartEvent; class CStopEvent; class CControlEvent; class CLockEvent; class CMessageEvent; class CCommandEvent; class CDasherView; } enum { EV_PARAM_NOTIFY = 1, EV_EDIT, EV_EDIT_CONTEXT, EV_START, EV_STOP, EV_CONTROL, EV_LOCK, EV_MESSAGE, EV_COMMAND, EV_TEXTDRAW }; -int iNUM_EVENTS = 10; - /// \ingroup Core /// @{ /// \defgroup Events Events generated by Dasher modules. /// @{ class Dasher::CEvent { public: int m_iEventType; }; class Dasher::CParameterNotificationEvent:public Dasher::CEvent { public: CParameterNotificationEvent(int iParameter) { m_iEventType = EV_PARAM_NOTIFY; m_iParameter = iParameter; }; int m_iParameter; }; class Dasher::CEditEvent:public Dasher::CEvent { public: CEditEvent(int iEditType, const std::string & sText, int iOffset) { m_iEventType = EV_EDIT; m_iEditType = iEditType; m_sText = sText; m_iOffset = iOffset; }; int m_iEditType; std::string m_sText; int m_iOffset; }; class Dasher::CEditContextEvent:public Dasher::CEvent { public: CEditContextEvent(int iOffset, int iLength) { m_iEventType = EV_EDIT_CONTEXT; m_iOffset = iOffset; m_iLength = iLength; }; int m_iOffset; int m_iLength; }; /** * An event that signals text has been drawn. Useful for determining its location * because that information is only available at draw time. */ class Dasher::CTextDrawEvent : public Dasher::CEvent { public: CTextDrawEvent(std::string sDisplayText, CDasherView *pView, screenint iX, screenint iY, int iSize) :m_sDisplayText(sDisplayText), m_pDasherView(pView), m_iX(iX), m_iY(iY), m_iSize(iSize) { m_iEventType = EV_TEXTDRAW; }; /** * The text that has been drawn. */ std::string m_sDisplayText; /** * The dasher view that emitted this event. */ CDasherView* m_pDasherView; /** * The X position (in screen coordinates) of the center of the box surrounding the text. */ screenint m_iX; /** * The Y position (in screen coordinates) of the center of the box surrounding the text. */ screenint m_iY; /** * The size of the text. Useful for determining the boundaries of the text "box" */ int m_iSize; }; class Dasher::CStartEvent:public Dasher::CEvent { public: CStartEvent() { m_iEventType = EV_START; }; }; class Dasher::CStopEvent:public Dasher::CEvent { public: CStopEvent() { m_iEventType = EV_STOP; }; }; class Dasher::CControlEvent:public Dasher::CEvent { public: CControlEvent(int iID) { m_iEventType = EV_CONTROL; m_iID = iID; }; int m_iID; }; class Dasher::CLockEvent : public Dasher::CEvent { public: CLockEvent(const std::string &strMessage, bool bLock, int iPercent) { m_iEventType = EV_LOCK; m_strMessage = strMessage; m_bLock = bLock; m_iPercent = iPercent; }; std::string m_strMessage; bool m_bLock; int m_iPercent; }; class Dasher::CMessageEvent : public Dasher::CEvent { public: CMessageEvent(const std::string &strMessage, int iID, int iType) { m_iEventType = EV_MESSAGE; m_strMessage = strMessage; m_iID = iID; m_iType = iType; }; std::string m_strMessage; int m_iID; int m_iType; }; class Dasher::CCommandEvent : public Dasher::CEvent { public: CCommandEvent(const std::string &strCommand) { m_iEventType = EV_COMMAND; m_strCommand = strCommand; }; std::string m_strCommand; }; /// @} /// @} #endif diff --git a/Src/DasherCore/EventHandler.cpp b/Src/DasherCore/EventHandler.cpp index 9706b6a..285caeb 100644 --- a/Src/DasherCore/EventHandler.cpp +++ b/Src/DasherCore/EventHandler.cpp @@ -1,108 +1,112 @@ - #include "../Common/Common.h" #include "EventHandler.h" #include "DasherComponent.h" #include "DasherInterfaceBase.h" #include "Event.h" - #include <algorithm> #include <iostream> using namespace Dasher; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif void CEventHandler::InsertEvent(CEvent *pEvent) { ++m_iInHandler; for(std::vector<CDasherComponent*>::const_iterator it = m_vSpecificListeners[pEvent->m_iEventType].begin(); it != m_vSpecificListeners[pEvent->m_iEventType].end(); ++it) { (*it)->HandleEvent(pEvent); } m_pInterface->InterfaceEventHandler(pEvent); m_pInterface->ExternalEventHandler(pEvent); --m_iInHandler; if(m_iInHandler == 0) { //loop through the queue of specific listeners waiting to be registered and register them for(ListenerQueue::iterator it = m_vSpecificListenerQueue.begin(); it != m_vSpecificListenerQueue.end(); ++it) { RegisterListener((*it).first, (*it).second); } } } void CEventHandler::RegisterListener(CDasherComponent *pListener) { - if(std::find(m_vGeneralListenerQueue.begin(), m_vGeneralListenerQueue.end(), pListener)) { + if(std::find(m_vGeneralListenerQueue.begin(), m_vGeneralListenerQueue.end(), pListener) == m_vGeneralListenerQueue.end()) { return; } else { - for(ListenerMap::iterator it = m_vSpecificListeners.begin() it != m_vSpecificListeners.end(); ++it) { + for(ListenerMap::iterator it = m_vSpecificListeners.begin(); it != m_vSpecificListeners.end(); ++it) { if((std::find((*it).begin(), (*it).end(), pListener) == (*it).end())) { if(m_iInHandler == 0) { (*it).push_back(pListener); } else { m_vGeneralListenerQueue.push_back(pListener); } } else { // Can't add the same listener twice } } } } void CEventHandler::RegisterListener(CDasherComponent *pListener, int iEventType) { if((std::find(m_vSpecificListeners[iEventType].begin(), m_vSpecificListeners[iEventType].end(), pListener) == m_vSpecificListeners[iEventType].end())) { if(m_iInHandler == 0) m_vSpecificListeners[iEventType].push_back(pListener); else - m_vSpecificListenerQueue[iEventType].push_back(pListener); + m_vSpecificListenerQueue.push_back(std::make_pair(pListener, iEventType)); } else { // Can't add the same listener twice } } void CEventHandler::UnregisterListener(CDasherComponent *pListener, int iEventType) { for(std::vector<CDasherComponent*>::iterator it = m_vSpecificListeners[iEventType].begin(); it != m_vSpecificListeners[iEventType].end(); ++it) { if( (*it) == pListener) m_vSpecificListeners[iEventType].erase(it); } } void CEventHandler::UnregisterListener(CDasherComponent *pListener) { - std::vector < CDasherComponent * >::iterator iFound; + std::vector < CDasherComponent * >::iterator mapFound; for(ListenerMap::iterator it = m_vSpecificListeners.begin(); it != m_vSpecificListeners.end(); ++it) { - iFound = std::find((*it).begin(), (*it).end(), pListener); - if(iFound != (*it).end()) - (*it).erase(iFound); + mapFound = std::find((*it).begin(), (*it).end(), pListener); + if(mapFound != (*it).end()) + (*it).erase(mapFound); + } + + std::vector < CDasherComponent * >::iterator queueFound = std::find(m_vGeneralListenerQueue.begin(), m_vGeneralListenerQueue.end(), pListener); + if(queueFound != m_vGeneralListenerQueue.end()) + m_vGeneralListenerQueue.erase(queueFound); + + for(ListenerQueue::iterator it = m_vSpecificListenerQueue.begin(); it != m_vSpecificListenerQueue.end(); ++it) { + if((*it).first == pListener) { + it = m_vSpecificListenerQueue.erase(it); + } } - for(ListenerMap::iterator it = m_vSpecificListenerQueue.begin(); it != m_vSpecificListenerQueue.end(); ++it) { - iFound = std::find((*it).begin(), (*it).end(), pListener); - if(iFound != (*it).end()) - (*it).erase(iFound); - } + } diff --git a/Src/DasherCore/EventHandler.h b/Src/DasherCore/EventHandler.h index b366a37..0bbeda1 100644 --- a/Src/DasherCore/EventHandler.h +++ b/Src/DasherCore/EventHandler.h @@ -1,121 +1,131 @@ #ifndef __eventhandler_h__ #define __eventhandler_h__ #include <vector> -#include <Event.h> +#include "Event.h" namespace Dasher { class CEventHandler; class CDasherComponent; class CDasherInterfaceBase; class CEvent; } /// \ingroup Core /// @{ class Dasher::CEventHandler { public: /** * @var typedef vector<vector<CDasherComponent*>> ListenerMap * @brief A 2d vector of Dasher Components where each sub-vector corresponds * to a specific event. The contents of the sub-vectors are the components * that subscribe to this event. */ typedef std::vector<std::vector<CDasherComponent*> > ListenerMap; /** * @var typedef vector<pair<CDasherComponent*, int> > ListenerQueue * @brief A queue whose elements represent 1 to 1 associations between * Dasher Components and Dasher core event types */ typedef std::vector<std::pair<CDasherComponent*, int> > ListenerQueue; - CEventHandler(Dasher::CDasherInterfaceBase * pInterface):m_pInterface(pInterface) { + CEventHandler(Dasher::CDasherInterfaceBase * pInterface): m_iNUM_EVENTS(10), m_pInterface(pInterface) { m_iInHandler = 0; // Initialize the event listener container (and queue) so we can add elements without // checking if the sub-vectors actually exist or not. - for(int i = 0; i < iNUM_EVENTS; i++) { - m_vSpecificListeners.push_back(std::vector<CDasherComponent*>()); - } - for(int i = 0; i < iNUM_EVENTS; i++) { - m_vSpecificListenerQueue.push_back(std::vector<CDasherComponent*>()); + for(int i = 0; i < m_iNUM_EVENTS; i++) { + m_vSpecificListeners.push_back(std::vector<CDasherComponent*>()); } }; ~CEventHandler() { }; // Insert an event, which will be propagated to all listeners. void InsertEvent(Dasher::CEvent * pEvent); /** * Register a listener for ALL events. To specify one, pass it * as a second parameter. * @param pListener The Dasher Component to be registered for all events. */ void RegisterListener(Dasher::CDasherComponent * pListener); /** * Register a listener to listen for specific events. * @param pListener A pointer to the dasher component that will listen for events * @param iEventType An integer defined in the event type enumeration in Event.h * that represents the event to which you'd like to subscribe. */ void RegisterListener(Dasher::CDasherComponent * pListener, int iEventType); /** * Unregister a listener from a specific event. * @param pListener A pointer tot he dasher component to be unregistered * @param iEventType An integer defined in the event type enumeration in Event.h * that represents the event to which you'd like to unsubscribe. */ void UnregisterListener(Dasher::CDasherComponent * pListener, int iEventType); /** * Unregister a listener from ALL events. * @param pListener The Dasher Component to unregister from all events. */ void UnregisterListener(Dasher::CDasherComponent * pListener); protected: /** * A 2-dimensional vector of listeners where each sub-vector represents * the listener for a specific event type (Defined in the event type enumeration * in Event.h. To access a vector for a specific event type, index into the top-level * vector using the event type as an index. */ ListenerMap m_vSpecificListeners; /** * The queue of listeners waiting to be registered with specific * events while InsertEvent is still processing. Used to prevent * m_vSpecificListeners from being modified while InsertEvent is * iterating over it. */ ListenerQueue m_vSpecificListenerQueue; /** * The queue of "old style" listeners waiting to be registered * with all events while InsertEvent is still processing. Used * to prevent m_vSpecificListeners from being modified while * InsertEvent is iterating over it. */ - std::vector<CDasherComponent> m_vGeneralListenerQueue; + std::vector<CDasherComponent*> m_vGeneralListenerQueue; int m_iInHandler; Dasher::CDasherInterfaceBase * m_pInterface; + +private: + + /** + * @var m_iNUM_EVENTS + * @brief The number of event types in the enumeration of Dasher events in Event.h. Had + * to put it here to stop the compiler from complaining about multiple definitions. Please + * keep this up to date with the number of items in the enumeration. + * TODO - figure out a better solution to the compiler problem - this one is kind of clumsy + */ + const int m_iNUM_EVENTS; + + }; /// @} #endif
rgee/HFOSS-Dasher
8ceee4c58e1698fe936a39df305ab5463552192b
Started work to correcy problems in the pointer arrow's behavior. Does not compile right now - lots of incomplete stuff.
diff --git a/Src/DasherCore/GameModule.cpp b/Src/DasherCore/GameModule.cpp index 5d41f21..900c336 100644 --- a/Src/DasherCore/GameModule.cpp +++ b/Src/DasherCore/GameModule.cpp @@ -1,67 +1,72 @@ #include "GameModule.h" using namespace Dasher; void CGameModule::HandleEvent(Dasher::CEvent *pEvent) { switch(pEvent->m_iEventType) { case EV_EDIT: { CEditEvent* evt = static_cast<CEditEvent*>(pEvent); switch(evt->m_iEditType) { // Added a new character (Stepped one node forward) case 0: m_stCurrentStringPos++; //pLastTypedNode = StringToNode(evt->m_sText); break; // Removed a character (Stepped one node back) case 1: break; default: break; } break; } case EV_TEXTDRAW: { CTextDrawEvent *evt = static_cast<CTextDrawEvent*>(pEvent); - if(!m_sTargetString.substr(m_stCurrentStringPos+1, 1).compare(evt->m_sDisplayText) - && evt->m_iY < GetLongParameter(LP_OX)) { - evt->m_pDasherView->Screen2Dasher(evt->m_iX, evt->m_iY, m_iTargetX, m_iTargetY); + if(!m_sTargetString.substr(m_stCurrentStringPos+1, 1).compare(evt->m_sDisplayText)) { + + //the x and y coordinates (in Dasher coords) of the target node + myint xDasherCoord, yDasherCoord; + evt->m_pDasherView->Screen2Dasher(evt->m_iX, evt->m_iY, xCoord, yCoord); + + if(xDasherCoord < GetLongParameter(LP_OX) && ) } } break; default: break; } return; } bool CGameModule::DecorateView(CDasherView *pView) { - - //set up the points for the arrow through - starts at the crosshair, ends at the target letter + + //set up the points for the arrow to pass through - + //starts at the crosshair, ends at the target letter myint x[2] = {GetLongParameter(LP_OX), m_iTargetX}; myint y[2] = {GetLongParameter(LP_OY), m_iTargetY}; pView->DasherPolyarrow(x, y, m_iArrowNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iArrowColor, m_dArrowSizeFactor); return true; } //CDasherNode CGameModule::StringToNode(std::string sText) { // //} std::string CGameModule::GetTypedTarget() { return m_sTargetString.substr(0, m_stCurrentStringPos - 1); } std::string CGameModule::GetUntypedTarget() { return m_sTargetString.substr(m_stCurrentStringPos); } diff --git a/Src/DasherCore/GameModule.h b/Src/DasherCore/GameModule.h index 3241565..cb55711 100644 --- a/Src/DasherCore/GameModule.h +++ b/Src/DasherCore/GameModule.h @@ -1,143 +1,150 @@ // GameModule.h #ifndef GAME_MODULE_H #define GAME_MODULE_H #include <string> #include <cstring> using namespace std; #include "DasherView.h" #include "DasherModel.h" #include "DasherModule.h" #include "DasherNode.h" #include "DasherView.h" #include "DasherTypes.h" #include "DasherInterfaceBase.h" namespace Dasher { /** * This Dasher Module encapsulates all game mode logic. In game mode, users will be given * a target string to type as well as visual feedback for their progress and a helpful * arrow to guide them in the right path through the dasher model. * * This class handles logic and drawing code with respect to the above. */ class CGameModule : public CDasherModule { public: // I don't actually know what the type is supposed to be for this...it's not an input method or an input filter. // Maybe we should define a new one. I've labeled it 0 for now. - rgee CGameModule(Dasher::CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CDasherInterfaceBase *pInterface, ModuleID_t iID, const char *szName) : m_iArrowColor(135), m_dArrowSizeFactor(0.1), m_iArrowNumPoints(2), CDasherModule(pEventHandler, pSettingsStore, iID, 0, szName) { m_pInterface = pInterface; //TODO REMOVE THIS!!! m_sTargetString = "My name is julian."; m_stCurrentStringPos = 0; - //m_iArrowColor = 135; - //m_dArrowSizeFactor = 0.1; - //m_iArrowNumPoints = 2; } virtual ~CGameModule() {}; /** * Gets the typed portion of the target string * @return The string that represents the current word(s) that have not been typed */ std::string GetTypedTarget(); /** * Gets the portion of the target string that has yet to be completed * @return The string that represents the current word(s) that have been typed */ std::string GetUntypedTarget(); bool DecorateView(CDasherView *pView); void SetDasherModel(CDasherModel *pModel) { m_pModel = pModel; } /** * Handle events from the event processing system * @param pEvent The event to be processed. */ virtual void HandleEvent(Dasher::CEvent *pEvent); private: + + /** + * Get the distance of a given point (in Dasher Coordinates) from the origin. + * + * @param xCoord - the x coordinate of the point + * @param yCoord - the y coordinate of the point + * + */ + myint DistanceFromOrigin(myint xCoord, myint yCoord); + /** * Searches for the dasher node under the current root that represents the desired string * @param text The string to search for * @return The node representing the string parameter */ - //Dasher::CDasherNode StringToNode(std::string sText); + //Dasher::CDasherNode StringToNode(std::string sText); /** * The last node the user typed. */ CDasherNode *pLastTypedNode; /** * The next node (character) the user must type. */ CDasherNode *pNextTargetNode; /** * The target string the user must type. */ std::string m_sTargetString; /** * The current position in the string. * Stored as a size_t to easily use substrings to determine what's been typed and what hasn't. */ size_t m_stCurrentStringPos; /** * The dasher model. */ CDasherModel *m_pModel; /** * The dasher interface. */ CDasherInterfaceBase *m_pInterface; /** * The target x coordinate for the arrow to point to. */ myint m_iTargetX; /** * The target y coordinate for the arrow to point to. */ myint m_iTargetY; /** * The color (in Dasher colors) to make the guiding arrow. */ const int m_iArrowColor; /** * The factor by which the size the hat on the guiding arrow */ const double m_dArrowSizeFactor; /** * The number of points that the guiding arrow passes through */ const int m_iArrowNumPoints; }; } #endif
rgee/HFOSS-Dasher
65634bc79dab27b8d788ad6d32b3b236e901a32e
Doing more fixes to the new event system. Not done yet - won't compile.
diff --git a/Src/DasherCore/EventHandler.cpp b/Src/DasherCore/EventHandler.cpp index e26ca3f..9706b6a 100644 --- a/Src/DasherCore/EventHandler.cpp +++ b/Src/DasherCore/EventHandler.cpp @@ -1,103 +1,108 @@ #include "../Common/Common.h" #include "EventHandler.h" #include "DasherComponent.h" #include "DasherInterfaceBase.h" #include "Event.h" #include <algorithm> #include <iostream> using namespace Dasher; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif void CEventHandler::InsertEvent(CEvent *pEvent) { + ++m_iInHandler; for(std::vector<CDasherComponent*>::const_iterator it = m_vSpecificListeners[pEvent->m_iEventType].begin(); it != m_vSpecificListeners[pEvent->m_iEventType].end(); ++it) { (*it)->HandleEvent(pEvent); } m_pInterface->InterfaceEventHandler(pEvent); m_pInterface->ExternalEventHandler(pEvent); --m_iInHandler; if(m_iInHandler == 0) { - // Loop through each specific event vector in the queue and transfer its elements to - // the corresponding vector in the listener container - for(int i = 0; i < iNUM_EVENTS; i++) { - for(std::vector < CDasherComponent* >::const_iterator it = m_vSpecificListenerQueue[i].begin(); it != m_vSpecificListenerQueue[i].end(); ++it) { - m_vSpecificListeners[i].push_back(*it); - } - m_vSpecificListenerQueue[i].clear(); + + //loop through the queue of specific listeners waiting to be registered and register them + for(ListenerQueue::iterator it = m_vSpecificListenerQueue.begin(); it != m_vSpecificListenerQueue.end(); ++it) { + RegisterListener((*it).first, (*it).second); } } } void CEventHandler::RegisterListener(CDasherComponent *pListener) { - if((std::find(m_vSpecificListeners.begin(), m_vSpecificListeners.end(), pListener) == m_vSpecificListeners.end()) && - (std::find(m_vSpecificListenerQueue.begin(), m_vSpecificListenerQueue.end(), pListener) == m_vSpecificListenerQueue.end())) { - if(!m_iInHandler > 0) - for(ListenerMap::iterator it = m_vSpecificListeners.begin(); it != m_vSpecificListeners.end(); ++it) { - (*it).push_back(pListener); - } - else - for(ListenerMap::iterator it = m_vSpecificListenerQueue.begin(); it != m_vSpecificListenerQueue.end(); ++it) { - (*it).push_back(pListener); - } + + if(std::find(m_vGeneralListenerQueue.begin(), m_vGeneralListenerQueue.end(), pListener)) { + return; } else { - // Can't add the same listener twice - } + + for(ListenerMap::iterator it = m_vSpecificListeners.begin() it != m_vSpecificListeners.end(); ++it) { + + if((std::find((*it).begin(), (*it).end(), pListener) == (*it).end())) { + if(m_iInHandler == 0) { + (*it).push_back(pListener); + } + else { + m_vGeneralListenerQueue.push_back(pListener); + } + } + else { + // Can't add the same listener twice + } + } + } } void CEventHandler::RegisterListener(CDasherComponent *pListener, int iEventType) { - if((std::find(m_vSpecificListeners.begin(), m_vSpecificListeners.end(), pListener) == m_vSpecificListeners.end()) && - (std::find(m_vSpecificListeners.begin(), m_vSpecificListenerQueue.end(), pListener) == m_vSpecificListenerQueue.end())) { - if(!m_iInHandler > 0) + + if((std::find(m_vSpecificListeners[iEventType].begin(), m_vSpecificListeners[iEventType].end(), pListener) == m_vSpecificListeners[iEventType].end())) { + if(m_iInHandler == 0) m_vSpecificListeners[iEventType].push_back(pListener); else m_vSpecificListenerQueue[iEventType].push_back(pListener); } else { // Can't add the same listener twice } } void CEventHandler::UnregisterListener(CDasherComponent *pListener, int iEventType) { for(std::vector<CDasherComponent*>::iterator it = m_vSpecificListeners[iEventType].begin(); it != m_vSpecificListeners[iEventType].end(); ++it) { if( (*it) == pListener) m_vSpecificListeners[iEventType].erase(it); } } void CEventHandler::UnregisterListener(CDasherComponent *pListener) { std::vector < CDasherComponent * >::iterator iFound; for(ListenerMap::iterator it = m_vSpecificListeners.begin(); it != m_vSpecificListeners.end(); ++it) { iFound = std::find((*it).begin(), (*it).end(), pListener); if(iFound != (*it).end()) (*it).erase(iFound); } for(ListenerMap::iterator it = m_vSpecificListenerQueue.begin(); it != m_vSpecificListenerQueue.end(); ++it) { iFound = std::find((*it).begin(), (*it).end(), pListener); if(iFound != (*it).end()) (*it).erase(iFound); } } diff --git a/Src/DasherCore/EventHandler.h b/Src/DasherCore/EventHandler.h index 2ba3b30..b366a37 100644 --- a/Src/DasherCore/EventHandler.h +++ b/Src/DasherCore/EventHandler.h @@ -1,103 +1,121 @@ #ifndef __eventhandler_h__ #define __eventhandler_h__ #include <vector> #include <Event.h> namespace Dasher { class CEventHandler; class CDasherComponent; class CDasherInterfaceBase; class CEvent; } /// \ingroup Core /// @{ class Dasher::CEventHandler { public: /** * @var typedef vector<vector<CDasherComponent*>> ListenerMap * @brief A 2d vector of Dasher Components where each sub-vector corresponds * to a specific event. The contents of the sub-vectors are the components * that subscribe to this event. */ typedef std::vector<std::vector<CDasherComponent*> > ListenerMap; + + /** + * @var typedef vector<pair<CDasherComponent*, int> > ListenerQueue + * @brief A queue whose elements represent 1 to 1 associations between + * Dasher Components and Dasher core event types + */ + typedef std::vector<std::pair<CDasherComponent*, int> > ListenerQueue; CEventHandler(Dasher::CDasherInterfaceBase * pInterface):m_pInterface(pInterface) { m_iInHandler = 0; // Initialize the event listener container (and queue) so we can add elements without // checking if the sub-vectors actually exist or not. for(int i = 0; i < iNUM_EVENTS; i++) { m_vSpecificListeners.push_back(std::vector<CDasherComponent*>()); } for(int i = 0; i < iNUM_EVENTS; i++) { m_vSpecificListenerQueue.push_back(std::vector<CDasherComponent*>()); } }; ~CEventHandler() { }; // Insert an event, which will be propagated to all listeners. void InsertEvent(Dasher::CEvent * pEvent); /** * Register a listener for ALL events. To specify one, pass it * as a second parameter. * @param pListener The Dasher Component to be registered for all events. */ void RegisterListener(Dasher::CDasherComponent * pListener); /** * Register a listener to listen for specific events. * @param pListener A pointer to the dasher component that will listen for events * @param iEventType An integer defined in the event type enumeration in Event.h * that represents the event to which you'd like to subscribe. */ void RegisterListener(Dasher::CDasherComponent * pListener, int iEventType); /** * Unregister a listener from a specific event. * @param pListener A pointer tot he dasher component to be unregistered * @param iEventType An integer defined in the event type enumeration in Event.h * that represents the event to which you'd like to unsubscribe. */ void UnregisterListener(Dasher::CDasherComponent * pListener, int iEventType); /** * Unregister a listener from ALL events. * @param pListener The Dasher Component to unregister from all events. */ void UnregisterListener(Dasher::CDasherComponent * pListener); protected: + /** * A 2-dimensional vector of listeners where each sub-vector represents * the listener for a specific event type (Defined in the event type enumeration * in Event.h. To access a vector for a specific event type, index into the top-level * vector using the event type as an index. */ ListenerMap m_vSpecificListeners; - /** - * A container identical in structure to m_vSpecificListeners that holds Dasher Components - * that have yet to be processed. - */ - ListenerMap m_vSpecificListenerQueue; + /** + * The queue of listeners waiting to be registered with specific + * events while InsertEvent is still processing. Used to prevent + * m_vSpecificListeners from being modified while InsertEvent is + * iterating over it. + */ + ListenerQueue m_vSpecificListenerQueue; + + /** + * The queue of "old style" listeners waiting to be registered + * with all events while InsertEvent is still processing. Used + * to prevent m_vSpecificListeners from being modified while + * InsertEvent is iterating over it. + */ + std::vector<CDasherComponent> m_vGeneralListenerQueue; int m_iInHandler; Dasher::CDasherInterfaceBase * m_pInterface; }; /// @} #endif
rgee/HFOSS-Dasher
9e07b361c5b4b8450e3560a9b22d753b89022af9
Doing more fixed to the event system - this step is not done yet. Won't compile.
diff --git a/Src/DasherCore/EventHandler.cpp b/Src/DasherCore/EventHandler.cpp index e26ca3f..9706b6a 100644 --- a/Src/DasherCore/EventHandler.cpp +++ b/Src/DasherCore/EventHandler.cpp @@ -1,103 +1,108 @@ #include "../Common/Common.h" #include "EventHandler.h" #include "DasherComponent.h" #include "DasherInterfaceBase.h" #include "Event.h" #include <algorithm> #include <iostream> using namespace Dasher; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif void CEventHandler::InsertEvent(CEvent *pEvent) { + ++m_iInHandler; for(std::vector<CDasherComponent*>::const_iterator it = m_vSpecificListeners[pEvent->m_iEventType].begin(); it != m_vSpecificListeners[pEvent->m_iEventType].end(); ++it) { (*it)->HandleEvent(pEvent); } m_pInterface->InterfaceEventHandler(pEvent); m_pInterface->ExternalEventHandler(pEvent); --m_iInHandler; if(m_iInHandler == 0) { - // Loop through each specific event vector in the queue and transfer its elements to - // the corresponding vector in the listener container - for(int i = 0; i < iNUM_EVENTS; i++) { - for(std::vector < CDasherComponent* >::const_iterator it = m_vSpecificListenerQueue[i].begin(); it != m_vSpecificListenerQueue[i].end(); ++it) { - m_vSpecificListeners[i].push_back(*it); - } - m_vSpecificListenerQueue[i].clear(); + + //loop through the queue of specific listeners waiting to be registered and register them + for(ListenerQueue::iterator it = m_vSpecificListenerQueue.begin(); it != m_vSpecificListenerQueue.end(); ++it) { + RegisterListener((*it).first, (*it).second); } } } void CEventHandler::RegisterListener(CDasherComponent *pListener) { - if((std::find(m_vSpecificListeners.begin(), m_vSpecificListeners.end(), pListener) == m_vSpecificListeners.end()) && - (std::find(m_vSpecificListenerQueue.begin(), m_vSpecificListenerQueue.end(), pListener) == m_vSpecificListenerQueue.end())) { - if(!m_iInHandler > 0) - for(ListenerMap::iterator it = m_vSpecificListeners.begin(); it != m_vSpecificListeners.end(); ++it) { - (*it).push_back(pListener); - } - else - for(ListenerMap::iterator it = m_vSpecificListenerQueue.begin(); it != m_vSpecificListenerQueue.end(); ++it) { - (*it).push_back(pListener); - } + + if(std::find(m_vGeneralListenerQueue.begin(), m_vGeneralListenerQueue.end(), pListener)) { + return; } else { - // Can't add the same listener twice - } + + for(ListenerMap::iterator it = m_vSpecificListeners.begin() it != m_vSpecificListeners.end(); ++it) { + + if((std::find((*it).begin(), (*it).end(), pListener) == (*it).end())) { + if(m_iInHandler == 0) { + (*it).push_back(pListener); + } + else { + m_vGeneralListenerQueue.push_back(pListener); + } + } + else { + // Can't add the same listener twice + } + } + } } void CEventHandler::RegisterListener(CDasherComponent *pListener, int iEventType) { - if((std::find(m_vSpecificListeners.begin(), m_vSpecificListeners.end(), pListener) == m_vSpecificListeners.end()) && - (std::find(m_vSpecificListeners.begin(), m_vSpecificListenerQueue.end(), pListener) == m_vSpecificListenerQueue.end())) { - if(!m_iInHandler > 0) + + if((std::find(m_vSpecificListeners[iEventType].begin(), m_vSpecificListeners[iEventType].end(), pListener) == m_vSpecificListeners[iEventType].end())) { + if(m_iInHandler == 0) m_vSpecificListeners[iEventType].push_back(pListener); else m_vSpecificListenerQueue[iEventType].push_back(pListener); } else { // Can't add the same listener twice } } void CEventHandler::UnregisterListener(CDasherComponent *pListener, int iEventType) { for(std::vector<CDasherComponent*>::iterator it = m_vSpecificListeners[iEventType].begin(); it != m_vSpecificListeners[iEventType].end(); ++it) { if( (*it) == pListener) m_vSpecificListeners[iEventType].erase(it); } } void CEventHandler::UnregisterListener(CDasherComponent *pListener) { std::vector < CDasherComponent * >::iterator iFound; for(ListenerMap::iterator it = m_vSpecificListeners.begin(); it != m_vSpecificListeners.end(); ++it) { iFound = std::find((*it).begin(), (*it).end(), pListener); if(iFound != (*it).end()) (*it).erase(iFound); } for(ListenerMap::iterator it = m_vSpecificListenerQueue.begin(); it != m_vSpecificListenerQueue.end(); ++it) { iFound = std::find((*it).begin(), (*it).end(), pListener); if(iFound != (*it).end()) (*it).erase(iFound); } } diff --git a/Src/DasherCore/EventHandler.h b/Src/DasherCore/EventHandler.h index 2ba3b30..b366a37 100644 --- a/Src/DasherCore/EventHandler.h +++ b/Src/DasherCore/EventHandler.h @@ -1,103 +1,121 @@ #ifndef __eventhandler_h__ #define __eventhandler_h__ #include <vector> #include <Event.h> namespace Dasher { class CEventHandler; class CDasherComponent; class CDasherInterfaceBase; class CEvent; } /// \ingroup Core /// @{ class Dasher::CEventHandler { public: /** * @var typedef vector<vector<CDasherComponent*>> ListenerMap * @brief A 2d vector of Dasher Components where each sub-vector corresponds * to a specific event. The contents of the sub-vectors are the components * that subscribe to this event. */ typedef std::vector<std::vector<CDasherComponent*> > ListenerMap; + + /** + * @var typedef vector<pair<CDasherComponent*, int> > ListenerQueue + * @brief A queue whose elements represent 1 to 1 associations between + * Dasher Components and Dasher core event types + */ + typedef std::vector<std::pair<CDasherComponent*, int> > ListenerQueue; CEventHandler(Dasher::CDasherInterfaceBase * pInterface):m_pInterface(pInterface) { m_iInHandler = 0; // Initialize the event listener container (and queue) so we can add elements without // checking if the sub-vectors actually exist or not. for(int i = 0; i < iNUM_EVENTS; i++) { m_vSpecificListeners.push_back(std::vector<CDasherComponent*>()); } for(int i = 0; i < iNUM_EVENTS; i++) { m_vSpecificListenerQueue.push_back(std::vector<CDasherComponent*>()); } }; ~CEventHandler() { }; // Insert an event, which will be propagated to all listeners. void InsertEvent(Dasher::CEvent * pEvent); /** * Register a listener for ALL events. To specify one, pass it * as a second parameter. * @param pListener The Dasher Component to be registered for all events. */ void RegisterListener(Dasher::CDasherComponent * pListener); /** * Register a listener to listen for specific events. * @param pListener A pointer to the dasher component that will listen for events * @param iEventType An integer defined in the event type enumeration in Event.h * that represents the event to which you'd like to subscribe. */ void RegisterListener(Dasher::CDasherComponent * pListener, int iEventType); /** * Unregister a listener from a specific event. * @param pListener A pointer tot he dasher component to be unregistered * @param iEventType An integer defined in the event type enumeration in Event.h * that represents the event to which you'd like to unsubscribe. */ void UnregisterListener(Dasher::CDasherComponent * pListener, int iEventType); /** * Unregister a listener from ALL events. * @param pListener The Dasher Component to unregister from all events. */ void UnregisterListener(Dasher::CDasherComponent * pListener); protected: + /** * A 2-dimensional vector of listeners where each sub-vector represents * the listener for a specific event type (Defined in the event type enumeration * in Event.h. To access a vector for a specific event type, index into the top-level * vector using the event type as an index. */ ListenerMap m_vSpecificListeners; - /** - * A container identical in structure to m_vSpecificListeners that holds Dasher Components - * that have yet to be processed. - */ - ListenerMap m_vSpecificListenerQueue; + /** + * The queue of listeners waiting to be registered with specific + * events while InsertEvent is still processing. Used to prevent + * m_vSpecificListeners from being modified while InsertEvent is + * iterating over it. + */ + ListenerQueue m_vSpecificListenerQueue; + + /** + * The queue of "old style" listeners waiting to be registered + * with all events while InsertEvent is still processing. Used + * to prevent m_vSpecificListeners from being modified while + * InsertEvent is iterating over it. + */ + std::vector<CDasherComponent> m_vGeneralListenerQueue; int m_iInHandler; Dasher::CDasherInterfaceBase * m_pInterface; }; /// @} #endif
rgee/HFOSS-Dasher
99f7b9dc3f7e051d5bb64f9f37a777c9a3c3ab12
Correcting assorted compilation bugs
diff --git a/Src/DasherCore/EventHandler.cpp b/Src/DasherCore/EventHandler.cpp index 332d117..e26ca3f 100644 --- a/Src/DasherCore/EventHandler.cpp +++ b/Src/DasherCore/EventHandler.cpp @@ -1,103 +1,103 @@ #include "../Common/Common.h" #include "EventHandler.h" #include "DasherComponent.h" #include "DasherInterfaceBase.h" #include "Event.h" #include <algorithm> #include <iostream> using namespace Dasher; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif void CEventHandler::InsertEvent(CEvent *pEvent) { ++m_iInHandler; - for(std::vector<CdasherComponent*>::const_iterator it = m_vSpecificListeners[pEvent->m_iEventType].begin(); + for(std::vector<CDasherComponent*>::const_iterator it = m_vSpecificListeners[pEvent->m_iEventType].begin(); it != m_vSpecificListeners[pEvent->m_iEventType].end(); ++it) { (*it)->HandleEvent(pEvent); } m_pInterface->InterfaceEventHandler(pEvent); m_pInterface->ExternalEventHandler(pEvent); --m_iInHandler; if(m_iInHandler == 0) { // Loop through each specific event vector in the queue and transfer its elements to // the corresponding vector in the listener container for(int i = 0; i < iNUM_EVENTS; i++) { for(std::vector < CDasherComponent* >::const_iterator it = m_vSpecificListenerQueue[i].begin(); it != m_vSpecificListenerQueue[i].end(); ++it) { m_vSpecificListeners[i].push_back(*it); } m_vSpecificListenerQueue[i].clear(); } } } void CEventHandler::RegisterListener(CDasherComponent *pListener) { - if((std::find(m_vSpecificListeners.begin(), m_vSpecificListeneres.end(), pListener) == m_vListeners.end()) && - (std::find(m_vSpecificListeners.begin(), m_vListenerQueue.end(), pListener) == m_vSpecificListenerQueue.end())) { - if(!m_viInHandler > 0) + if((std::find(m_vSpecificListeners.begin(), m_vSpecificListeners.end(), pListener) == m_vSpecificListeners.end()) && + (std::find(m_vSpecificListenerQueue.begin(), m_vSpecificListenerQueue.end(), pListener) == m_vSpecificListenerQueue.end())) { + if(!m_iInHandler > 0) for(ListenerMap::iterator it = m_vSpecificListeners.begin(); it != m_vSpecificListeners.end(); ++it) { (*it).push_back(pListener); } else - for(std::vector<CDasherComponent*>>::iterator it = m_vSpecificListenerQueue.begin(); it != m_vSpecificListenerQueue.end(); ++it) { + for(ListenerMap::iterator it = m_vSpecificListenerQueue.begin(); it != m_vSpecificListenerQueue.end(); ++it) { (*it).push_back(pListener); } } else { // Can't add the same listener twice } } void CEventHandler::RegisterListener(CDasherComponent *pListener, int iEventType) { - if((std::find(m_vSpecificListeners.begin(), m_vSpecificListeneres.end(), pListener) == m_vListeners.end()) && - (std::find(m_vSpecificListeners.begin(), m_vListenerQueue.end(), pListener) == m_vSpecificListenerQueue.end())) { - if(!m_vInHandler > 0) - m_vSpecificListener[iEventType].push_back(pListener); + if((std::find(m_vSpecificListeners.begin(), m_vSpecificListeners.end(), pListener) == m_vSpecificListeners.end()) && + (std::find(m_vSpecificListeners.begin(), m_vSpecificListenerQueue.end(), pListener) == m_vSpecificListenerQueue.end())) { + if(!m_iInHandler > 0) + m_vSpecificListeners[iEventType].push_back(pListener); else m_vSpecificListenerQueue[iEventType].push_back(pListener); } else { // Can't add the same listener twice } } void CEventHandler::UnregisterListener(CDasherComponent *pListener, int iEventType) { for(std::vector<CDasherComponent*>::iterator it = m_vSpecificListeners[iEventType].begin(); it != m_vSpecificListeners[iEventType].end(); ++it) { if( (*it) == pListener) m_vSpecificListeners[iEventType].erase(it); } } void CEventHandler::UnregisterListener(CDasherComponent *pListener) { std::vector < CDasherComponent * >::iterator iFound; for(ListenerMap::iterator it = m_vSpecificListeners.begin(); it != m_vSpecificListeners.end(); ++it) { iFound = std::find((*it).begin(), (*it).end(), pListener); if(iFound != (*it).end()) (*it).erase(iFound); } for(ListenerMap::iterator it = m_vSpecificListenerQueue.begin(); it != m_vSpecificListenerQueue.end(); ++it) { iFound = std::find((*it).begin(), (*it).end(), pListener); if(iFound != (*it).end()) (*it).erase(iFound); } } diff --git a/Src/DasherCore/EventHandler.h b/Src/DasherCore/EventHandler.h index 4e3d8a9..2ba3b30 100644 --- a/Src/DasherCore/EventHandler.h +++ b/Src/DasherCore/EventHandler.h @@ -1,103 +1,103 @@ #ifndef __eventhandler_h__ #define __eventhandler_h__ #include <vector> +#include <Event.h> namespace Dasher { class CEventHandler; class CDasherComponent; class CDasherInterfaceBase; class CEvent; - /** - * @var typedef vector<vector<CDasherComponent*>> ListenerMap - * @brief A 2d vector of Dasher Components where each sub-vector corresponds - * to a specific event. The contents of the sub-vectors are the components - * that subscribe to this event. - */ - typedef std::vector<std::vector<CDasherComponent*>> ListenerMap; - } /// \ingroup Core /// @{ class Dasher::CEventHandler { public: - + /** + * @var typedef vector<vector<CDasherComponent*>> ListenerMap + * @brief A 2d vector of Dasher Components where each sub-vector corresponds + * to a specific event. The contents of the sub-vectors are the components + * that subscribe to this event. + */ + typedef std::vector<std::vector<CDasherComponent*> > ListenerMap; + CEventHandler(Dasher::CDasherInterfaceBase * pInterface):m_pInterface(pInterface) { m_iInHandler = 0; // Initialize the event listener container (and queue) so we can add elements without // checking if the sub-vectors actually exist or not. for(int i = 0; i < iNUM_EVENTS; i++) { - m_vSpecificListeners.push_back(new Vector<CDasherComponent*>()); + m_vSpecificListeners.push_back(std::vector<CDasherComponent*>()); } - for(int i = 0; it < iNUM_EVENTS; i++) { - m_vSpecificListenerQueue.push_back(new Vector<CDasherComponent*>()); + for(int i = 0; i < iNUM_EVENTS; i++) { + m_vSpecificListenerQueue.push_back(std::vector<CDasherComponent*>()); } }; ~CEventHandler() { }; // Insert an event, which will be propagated to all listeners. - void InsertEvent(Dasher::CEvent * pEvent) + void InsertEvent(Dasher::CEvent * pEvent); /** * Register a listener for ALL events. To specify one, pass it * as a second parameter. * @param pListener The Dasher Component to be registered for all events. */ void RegisterListener(Dasher::CDasherComponent * pListener); /** * Register a listener to listen for specific events. * @param pListener A pointer to the dasher component that will listen for events * @param iEventType An integer defined in the event type enumeration in Event.h * that represents the event to which you'd like to subscribe. */ void RegisterListener(Dasher::CDasherComponent * pListener, int iEventType); /** * Unregister a listener from a specific event. * @param pListener A pointer tot he dasher component to be unregistered * @param iEventType An integer defined in the event type enumeration in Event.h * that represents the event to which you'd like to unsubscribe. */ - void UnregisterListener(Dasher::CDashercomponent * pListener, int iEventType); + void UnregisterListener(Dasher::CDasherComponent * pListener, int iEventType); /** * Unregister a listener from ALL events. * @param pListener The Dasher Component to unregister from all events. */ void UnregisterListener(Dasher::CDasherComponent * pListener); protected: /** * A 2-dimensional vector of listeners where each sub-vector represents * the listener for a specific event type (Defined in the event type enumeration * in Event.h. To access a vector for a specific event type, index into the top-level * vector using the event type as an index. */ ListenerMap m_vSpecificListeners; /** * A container identical in structure to m_vSpecificListeners that holds Dasher Components * that have yet to be processed. */ ListenerMap m_vSpecificListenerQueue; int m_iInHandler; Dasher::CDasherInterfaceBase * m_pInterface; }; /// @} #endif
rgee/HFOSS-Dasher
2ee9f6000f8ee10e2e0e7c195d72b121884b782e
Documented iNUM_EVENTS
diff --git a/Src/DasherCore/Event.h b/Src/DasherCore/Event.h index 221aebd..b6f3576 100644 --- a/Src/DasherCore/Event.h +++ b/Src/DasherCore/Event.h @@ -1,181 +1,184 @@ #ifndef __event_h__ #define __event_h__ // Classes representing different event types. #include <string> #include "DasherTypes.h" namespace Dasher { class CEvent; class CTextDrawEvent; class CParameterNotificationEvent; class CEditEvent; class CEditContextEvent; class CStartEvent; class CStopEvent; class CControlEvent; class CLockEvent; class CMessageEvent; class CCommandEvent; class CDasherView; } enum { EV_PARAM_NOTIFY = 1, EV_EDIT, EV_EDIT_CONTEXT, EV_START, EV_STOP, EV_CONTROL, EV_LOCK, EV_MESSAGE, EV_COMMAND, EV_TEXTDRAW }; - -int iNUM_EVENTS = 10; +/** + * The number of event types. This is required for the event handler, but it's kept here to emphasize + * that this corresponds to the "length" above enum + */ +const int iNUM_EVENTS = 10; /// \ingroup Core /// @{ /// \defgroup Events Events generated by Dasher modules. /// @{ class Dasher::CEvent { public: int m_iEventType; }; class Dasher::CParameterNotificationEvent:public Dasher::CEvent { public: CParameterNotificationEvent(int iParameter) { m_iEventType = EV_PARAM_NOTIFY; m_iParameter = iParameter; }; int m_iParameter; }; class Dasher::CEditEvent:public Dasher::CEvent { public: CEditEvent(int iEditType, const std::string & sText, int iOffset) { m_iEventType = EV_EDIT; m_iEditType = iEditType; m_sText = sText; m_iOffset = iOffset; }; int m_iEditType; std::string m_sText; int m_iOffset; }; class Dasher::CEditContextEvent:public Dasher::CEvent { public: CEditContextEvent(int iOffset, int iLength) { m_iEventType = EV_EDIT_CONTEXT; m_iOffset = iOffset; m_iLength = iLength; }; int m_iOffset; int m_iLength; }; /** * An event that signals text has been drawn. Useful for determining its location * because that information is only available at draw time. */ class Dasher::CTextDrawEvent : public Dasher::CEvent { public: CTextDrawEvent(std::string sDisplayText, CDasherView *pView, screenint iX, screenint iY, int iSize) :m_sDisplayText(sDisplayText), m_pDasherView(pView), m_iX(iX), m_iY(iY), m_iSize(iSize) { m_iEventType = EV_TEXTDRAW; }; /** * The text that has been drawn. */ std::string m_sDisplayText; /** * The dasher view that emitted this event. */ CDasherView* m_pDasherView; /** * The X position (in screen coordinates) of the center of the box surrounding the text. */ screenint m_iX; /** * The Y position (in screen coordinates) of the center of the box surrounding the text. */ screenint m_iY; /** * The size of the text. Useful for determining the boundaries of the text "box" */ int m_iSize; }; class Dasher::CStartEvent:public Dasher::CEvent { public: CStartEvent() { m_iEventType = EV_START; }; }; class Dasher::CStopEvent:public Dasher::CEvent { public: CStopEvent() { m_iEventType = EV_STOP; }; }; class Dasher::CControlEvent:public Dasher::CEvent { public: CControlEvent(int iID) { m_iEventType = EV_CONTROL; m_iID = iID; }; int m_iID; }; class Dasher::CLockEvent : public Dasher::CEvent { public: CLockEvent(const std::string &strMessage, bool bLock, int iPercent) { m_iEventType = EV_LOCK; m_strMessage = strMessage; m_bLock = bLock; m_iPercent = iPercent; }; std::string m_strMessage; bool m_bLock; int m_iPercent; }; class Dasher::CMessageEvent : public Dasher::CEvent { public: CMessageEvent(const std::string &strMessage, int iID, int iType) { m_iEventType = EV_MESSAGE; m_strMessage = strMessage; m_iID = iID; m_iType = iType; }; std::string m_strMessage; int m_iID; int m_iType; }; class Dasher::CCommandEvent : public Dasher::CEvent { public: CCommandEvent(const std::string &strCommand) { m_iEventType = EV_COMMAND; m_strCommand = strCommand; }; std::string m_strCommand; }; /// @} /// @} #endif
rgee/HFOSS-Dasher
3ee007a274dfe7a4f99950c488459fd7e45bca19
Moved typedef.
diff --git a/Src/DasherCore/EventHandler.h b/Src/DasherCore/EventHandler.h index 5a0089c..4e3d8a9 100644 --- a/Src/DasherCore/EventHandler.h +++ b/Src/DasherCore/EventHandler.h @@ -1,99 +1,103 @@ #ifndef __eventhandler_h__ #define __eventhandler_h__ #include <vector> namespace Dasher { class CEventHandler; class CDasherComponent; class CDasherInterfaceBase; class CEvent; + + /** + * @var typedef vector<vector<CDasherComponent*>> ListenerMap + * @brief A 2d vector of Dasher Components where each sub-vector corresponds + * to a specific event. The contents of the sub-vectors are the components + * that subscribe to this event. + */ + typedef std::vector<std::vector<CDasherComponent*>> ListenerMap; + } -/** - * @var typedef vector<vector<CDasherComponent*>> ListenerMap - * @brief A 2d vector of Dasher Components where each sub-vector corresponds - * to a specific event. The contents of the sub-vectors are the components - * that subscribe to this event. - */ -typedef std::vector<std::vector<CDasherComponent*>> ListenerMap; /// \ingroup Core /// @{ class Dasher::CEventHandler { public: + + CEventHandler(Dasher::CDasherInterfaceBase * pInterface):m_pInterface(pInterface) { m_iInHandler = 0; // Initialize the event listener container (and queue) so we can add elements without // checking if the sub-vectors actually exist or not. for(int i = 0; i < iNUM_EVENTS; i++) { m_vSpecificListeners.push_back(new Vector<CDasherComponent*>()); } for(int i = 0; it < iNUM_EVENTS; i++) { m_vSpecificListenerQueue.push_back(new Vector<CDasherComponent*>()); } }; ~CEventHandler() { }; // Insert an event, which will be propagated to all listeners. void InsertEvent(Dasher::CEvent * pEvent) /** * Register a listener for ALL events. To specify one, pass it * as a second parameter. * @param pListener The Dasher Component to be registered for all events. */ void RegisterListener(Dasher::CDasherComponent * pListener); /** * Register a listener to listen for specific events. * @param pListener A pointer to the dasher component that will listen for events * @param iEventType An integer defined in the event type enumeration in Event.h * that represents the event to which you'd like to subscribe. */ void RegisterListener(Dasher::CDasherComponent * pListener, int iEventType); /** * Unregister a listener from a specific event. * @param pListener A pointer tot he dasher component to be unregistered * @param iEventType An integer defined in the event type enumeration in Event.h * that represents the event to which you'd like to unsubscribe. */ void UnregisterListener(Dasher::CDashercomponent * pListener, int iEventType); /** * Unregister a listener from ALL events. * @param pListener The Dasher Component to unregister from all events. */ void UnregisterListener(Dasher::CDasherComponent * pListener); protected: /** * A 2-dimensional vector of listeners where each sub-vector represents * the listener for a specific event type (Defined in the event type enumeration * in Event.h. To access a vector for a specific event type, index into the top-level * vector using the event type as an index. */ ListenerMap m_vSpecificListeners; /** * A container identical in structure to m_vSpecificListeners that holds Dasher Components * that have yet to be processed. */ ListenerMap m_vSpecificListenerQueue; int m_iInHandler; Dasher::CDasherInterfaceBase * m_pInterface; }; /// @} #endif
rgee/HFOSS-Dasher
23993423d61422c4516cc02ae471c4c21193fe6a
Started work to correct problems in the pointer arrow's behavior
diff --git a/Src/DasherCore/GameModule.cpp b/Src/DasherCore/GameModule.cpp index 5d41f21..900c336 100644 --- a/Src/DasherCore/GameModule.cpp +++ b/Src/DasherCore/GameModule.cpp @@ -1,67 +1,72 @@ #include "GameModule.h" using namespace Dasher; void CGameModule::HandleEvent(Dasher::CEvent *pEvent) { switch(pEvent->m_iEventType) { case EV_EDIT: { CEditEvent* evt = static_cast<CEditEvent*>(pEvent); switch(evt->m_iEditType) { // Added a new character (Stepped one node forward) case 0: m_stCurrentStringPos++; //pLastTypedNode = StringToNode(evt->m_sText); break; // Removed a character (Stepped one node back) case 1: break; default: break; } break; } case EV_TEXTDRAW: { CTextDrawEvent *evt = static_cast<CTextDrawEvent*>(pEvent); - if(!m_sTargetString.substr(m_stCurrentStringPos+1, 1).compare(evt->m_sDisplayText) - && evt->m_iY < GetLongParameter(LP_OX)) { - evt->m_pDasherView->Screen2Dasher(evt->m_iX, evt->m_iY, m_iTargetX, m_iTargetY); + if(!m_sTargetString.substr(m_stCurrentStringPos+1, 1).compare(evt->m_sDisplayText)) { + + //the x and y coordinates (in Dasher coords) of the target node + myint xDasherCoord, yDasherCoord; + evt->m_pDasherView->Screen2Dasher(evt->m_iX, evt->m_iY, xCoord, yCoord); + + if(xDasherCoord < GetLongParameter(LP_OX) && ) } } break; default: break; } return; } bool CGameModule::DecorateView(CDasherView *pView) { - - //set up the points for the arrow through - starts at the crosshair, ends at the target letter + + //set up the points for the arrow to pass through - + //starts at the crosshair, ends at the target letter myint x[2] = {GetLongParameter(LP_OX), m_iTargetX}; myint y[2] = {GetLongParameter(LP_OY), m_iTargetY}; pView->DasherPolyarrow(x, y, m_iArrowNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iArrowColor, m_dArrowSizeFactor); return true; } //CDasherNode CGameModule::StringToNode(std::string sText) { // //} std::string CGameModule::GetTypedTarget() { return m_sTargetString.substr(0, m_stCurrentStringPos - 1); } std::string CGameModule::GetUntypedTarget() { return m_sTargetString.substr(m_stCurrentStringPos); } diff --git a/Src/DasherCore/GameModule.h b/Src/DasherCore/GameModule.h index 3241565..cb55711 100644 --- a/Src/DasherCore/GameModule.h +++ b/Src/DasherCore/GameModule.h @@ -1,143 +1,150 @@ // GameModule.h #ifndef GAME_MODULE_H #define GAME_MODULE_H #include <string> #include <cstring> using namespace std; #include "DasherView.h" #include "DasherModel.h" #include "DasherModule.h" #include "DasherNode.h" #include "DasherView.h" #include "DasherTypes.h" #include "DasherInterfaceBase.h" namespace Dasher { /** * This Dasher Module encapsulates all game mode logic. In game mode, users will be given * a target string to type as well as visual feedback for their progress and a helpful * arrow to guide them in the right path through the dasher model. * * This class handles logic and drawing code with respect to the above. */ class CGameModule : public CDasherModule { public: // I don't actually know what the type is supposed to be for this...it's not an input method or an input filter. // Maybe we should define a new one. I've labeled it 0 for now. - rgee CGameModule(Dasher::CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CDasherInterfaceBase *pInterface, ModuleID_t iID, const char *szName) : m_iArrowColor(135), m_dArrowSizeFactor(0.1), m_iArrowNumPoints(2), CDasherModule(pEventHandler, pSettingsStore, iID, 0, szName) { m_pInterface = pInterface; //TODO REMOVE THIS!!! m_sTargetString = "My name is julian."; m_stCurrentStringPos = 0; - //m_iArrowColor = 135; - //m_dArrowSizeFactor = 0.1; - //m_iArrowNumPoints = 2; } virtual ~CGameModule() {}; /** * Gets the typed portion of the target string * @return The string that represents the current word(s) that have not been typed */ std::string GetTypedTarget(); /** * Gets the portion of the target string that has yet to be completed * @return The string that represents the current word(s) that have been typed */ std::string GetUntypedTarget(); bool DecorateView(CDasherView *pView); void SetDasherModel(CDasherModel *pModel) { m_pModel = pModel; } /** * Handle events from the event processing system * @param pEvent The event to be processed. */ virtual void HandleEvent(Dasher::CEvent *pEvent); private: + + /** + * Get the distance of a given point (in Dasher Coordinates) from the origin. + * + * @param xCoord - the x coordinate of the point + * @param yCoord - the y coordinate of the point + * + */ + myint DistanceFromOrigin(myint xCoord, myint yCoord); + /** * Searches for the dasher node under the current root that represents the desired string * @param text The string to search for * @return The node representing the string parameter */ - //Dasher::CDasherNode StringToNode(std::string sText); + //Dasher::CDasherNode StringToNode(std::string sText); /** * The last node the user typed. */ CDasherNode *pLastTypedNode; /** * The next node (character) the user must type. */ CDasherNode *pNextTargetNode; /** * The target string the user must type. */ std::string m_sTargetString; /** * The current position in the string. * Stored as a size_t to easily use substrings to determine what's been typed and what hasn't. */ size_t m_stCurrentStringPos; /** * The dasher model. */ CDasherModel *m_pModel; /** * The dasher interface. */ CDasherInterfaceBase *m_pInterface; /** * The target x coordinate for the arrow to point to. */ myint m_iTargetX; /** * The target y coordinate for the arrow to point to. */ myint m_iTargetY; /** * The color (in Dasher colors) to make the guiding arrow. */ const int m_iArrowColor; /** * The factor by which the size the hat on the guiding arrow */ const double m_dArrowSizeFactor; /** * The number of points that the guiding arrow passes through */ const int m_iArrowNumPoints; }; } #endif
rgee/HFOSS-Dasher
cde3bab65d6ea5391fbf360700e9691c316af4d8
Event system should be complete. Keeping it in a branch for testing.
diff --git a/Src/DasherCore/EventHandler.cpp b/Src/DasherCore/EventHandler.cpp index a95740b..332d117 100644 --- a/Src/DasherCore/EventHandler.cpp +++ b/Src/DasherCore/EventHandler.cpp @@ -1,131 +1,103 @@ #include "../Common/Common.h" #include "EventHandler.h" #include "DasherComponent.h" #include "DasherInterfaceBase.h" #include "Event.h" #include <algorithm> #include <iostream> using namespace Dasher; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif void CEventHandler::InsertEvent(CEvent *pEvent) { ++m_iInHandler; for(std::vector<CdasherComponent*>::const_iterator it = m_vSpecificListeners[pEvent->m_iEventType].begin(); it != m_vSpecificListeners[pEvent->m_iEventType].end(); ++it) { (*it)->HandleEvent(pEvent); } m_pInterface->InterfaceEventHandler(pEvent); m_pInterface->ExternalEventHandler(pEvent); --m_iInHandler; if(m_iInHandler == 0) { - + // Loop through each specific event vector in the queue and transfer its elements to + // the corresponding vector in the listener container + for(int i = 0; i < iNUM_EVENTS; i++) { + for(std::vector < CDasherComponent* >::const_iterator it = m_vSpecificListenerQueue[i].begin(); it != m_vSpecificListenerQueue[i].end(); ++it) { + m_vSpecificListeners[i].push_back(*it); + } + m_vSpecificListenerQueue[i].clear(); + } } - - -// -// // We may end up here recursively, so keep track of how far down we -// // are, and only permit new handlers to be registered after all -// // messages are processed. -// -// // An alternative approach would be a message queue - this might actually be a bit more sensible -// ++m_iInHandler; -// -// // Loop through components and notify them of the event -// for(std::vector < CDasherComponent * >::iterator iCurrent(m_vListeners.begin()); iCurrent != m_vListeners.end(); ++iCurrent) { -// (*iCurrent)->HandleEvent(pEvent); -// } -// -// // Call external handler last, to make sure that internal components are fully up to date before external events happen -// -// m_pInterface->InterfaceEventHandler(pEvent); -// -// m_pInterface->ExternalEventHandler(pEvent); -// -// --m_iInHandler; -// -// if(m_iInHandler == 0) { -// for(std::vector < CDasherComponent * >::iterator iCurrent(m_vListenerQueue.begin()); iCurrent != m_vListenerQueue.end(); ++iCurrent) -// m_vListeners.push_back(*iCurrent); -// m_vListenerQueue.clear(); -// } } void CEventHandler::RegisterListener(CDasherComponent *pListener) { if((std::find(m_vSpecificListeners.begin(), m_vSpecificListeneres.end(), pListener) == m_vListeners.end()) && (std::find(m_vSpecificListeners.begin(), m_vListenerQueue.end(), pListener) == m_vSpecificListenerQueue.end())) { if(!m_viInHandler > 0) - for(std::vector<std::vector<CDasherComponent*>>::const_iterator it = m_vSpecificListeners.begin(); it != m_vSpecificListeners.end(); ++it) { - it.push_back(pListener); + for(ListenerMap::iterator it = m_vSpecificListeners.begin(); it != m_vSpecificListeners.end(); ++it) { + (*it).push_back(pListener); } else - for(std::vector<CDasherComponent*>>::cosnt_iterator it = m_vSpecificListenerQueue.begin(); it != m_vSpecificListenerQueue.end(); ++it) { - it.push_back(pListener); + for(std::vector<CDasherComponent*>>::iterator it = m_vSpecificListenerQueue.begin(); it != m_vSpecificListenerQueue.end(); ++it) { + (*it).push_back(pListener); } } else { // Can't add the same listener twice } -// ===OLD EVENT CODE== -// if((std::find(m_vListeners.begin(), m_vListeners.end(), pListener) == m_vListeners.end()) && -// (std::find(m_vListenerQueue.begin(), m_vListenerQueue.end(), pListener) == m_vListenerQueue.end())) { -// if(!m_iInHandler > 0) -// m_vListeners.push_back(pListener); -// else -// m_vListenerQueue.push_back(pListener); -// } -// else { -// // Can't add the same listener twice -// } } void CEventHandler::RegisterListener(CDasherComponent *pListener, int iEventType) { if((std::find(m_vSpecificListeners.begin(), m_vSpecificListeneres.end(), pListener) == m_vListeners.end()) && (std::find(m_vSpecificListeners.begin(), m_vListenerQueue.end(), pListener) == m_vSpecificListenerQueue.end())) { if(!m_vInHandler > 0) m_vSpecificListener[iEventType].push_back(pListener); else m_vSpecificListenerQueue[iEventType].push_back(pListener); } + else { + // Can't add the same listener twice + } } void CEventHandler::UnregisterListener(CDasherComponent *pListener, int iEventType) { - for(std::vector<CDasherComponent*>::const_iterator it = m_vSpecificListeners[iEventType].begin(); it != m_vSpecificListeners[iEventType].end(); ++it) { + for(std::vector<CDasherComponent*>::iterator it = m_vSpecificListeners[iEventType].begin(); it != m_vSpecificListeners[iEventType].end(); ++it) { if( (*it) == pListener) m_vSpecificListeners[iEventType].erase(it); } } void CEventHandler::UnregisterListener(CDasherComponent *pListener) { std::vector < CDasherComponent * >::iterator iFound; - iFound = std::find(m_vListeners.begin(), m_vListeners.end(), pListener); - - if(iFound != m_vListeners.end()) - m_vListeners.erase(iFound); - - iFound = std::find(m_vListenerQueue.begin(), m_vListenerQueue.end(), pListener); - - if(iFound != m_vListenerQueue.end()) - m_vListenerQueue.erase(iFound); + for(ListenerMap::iterator it = m_vSpecificListeners.begin(); it != m_vSpecificListeners.end(); ++it) { + iFound = std::find((*it).begin(), (*it).end(), pListener); + if(iFound != (*it).end()) + (*it).erase(iFound); + } + for(ListenerMap::iterator it = m_vSpecificListenerQueue.begin(); it != m_vSpecificListenerQueue.end(); ++it) { + iFound = std::find((*it).begin(), (*it).end(), pListener); + if(iFound != (*it).end()) + (*it).erase(iFound); + } } diff --git a/Src/DasherCore/EventHandler.h b/Src/DasherCore/EventHandler.h index 3e45753..5a0089c 100644 --- a/Src/DasherCore/EventHandler.h +++ b/Src/DasherCore/EventHandler.h @@ -1,87 +1,99 @@ #ifndef __eventhandler_h__ #define __eventhandler_h__ #include <vector> namespace Dasher { class CEventHandler; class CDasherComponent; class CDasherInterfaceBase; class CEvent; } +/** + * @var typedef vector<vector<CDasherComponent*>> ListenerMap + * @brief A 2d vector of Dasher Components where each sub-vector corresponds + * to a specific event. The contents of the sub-vectors are the components + * that subscribe to this event. + */ +typedef std::vector<std::vector<CDasherComponent*>> ListenerMap; /// \ingroup Core /// @{ class Dasher::CEventHandler { public: CEventHandler(Dasher::CDasherInterfaceBase * pInterface):m_pInterface(pInterface) { m_iInHandler = 0; // Initialize the event listener container (and queue) so we can add elements without // checking if the sub-vectors actually exist or not. for(int i = 0; i < iNUM_EVENTS; i++) { m_vSpecificListeners.push_back(new Vector<CDasherComponent*>()); } - for(int i = 0; it < iNUM_EVENTS; i++) { m_vSpecificListenerQueue.push_back(new Vector<CDasherComponent*>()); } }; ~CEventHandler() { }; // Insert an event, which will be propagated to all listeners. - void InsertEvent(Dasher::CEvent * pEvent); + void InsertEvent(Dasher::CEvent * pEvent) + - // (Un)register a listener with the event handler. + /** + * Register a listener for ALL events. To specify one, pass it + * as a second parameter. + * @param pListener The Dasher Component to be registered for all events. + */ void RegisterListener(Dasher::CDasherComponent * pListener); /** * Register a listener to listen for specific events. * @param pListener A pointer to the dasher component that will listen for events * @param iEventType An integer defined in the event type enumeration in Event.h * that represents the event to which you'd like to subscribe. */ void RegisterListener(Dasher::CDasherComponent * pListener, int iEventType); - /** - * Unregister a listener from a specific event. - * @param pListener A pointer tot he dasher component to be unregistered - * @param iEventType An integer defined in the event type enumeration in Event.h + /** + * Unregister a listener from a specific event. + * @param pListener A pointer tot he dasher component to be unregistered + * @param iEventType An integer defined in the event type enumeration in Event.h * that represents the event to which you'd like to unsubscribe. - */ - void UnregisterListener(Dasher::CDashercomponent * pListener, int iEventType); + */ + void UnregisterListener(Dasher::CDashercomponent * pListener, int iEventType); + + /** + * Unregister a listener from ALL events. + * @param pListener The Dasher Component to unregister from all events. + */ void UnregisterListener(Dasher::CDasherComponent * pListener); protected: - - // Vector containing all currently registered listeners. - - std::vector < Dasher::CDasherComponent * >m_vListeners; - std::vector < Dasher::CDasherComponent * >m_vListenerQueue; - - - /** * A 2-dimensional vector of listeners where each sub-vector represents * the listener for a specific event type (Defined in the event type enumeration * in Event.h. To access a vector for a specific event type, index into the top-level * vector using the event type as an index. */ - std::vector < std::vector < Dasher::CDasherComponent * > > m_vSpecificListeners; + ListenerMap m_vSpecificListeners; - std::vector < std::vector < Dasher::CDasherComponent * > > m_vSpecificListenerQueue; + /** + * A container identical in structure to m_vSpecificListeners that holds Dasher Components + * that have yet to be processed. + */ + ListenerMap m_vSpecificListenerQueue; int m_iInHandler; Dasher::CDasherInterfaceBase * m_pInterface; }; /// @} #endif
rgee/HFOSS-Dasher
6695a99070e796d550b1ba6cca5c290e1d6756c5
Added whitespace to GameModule.cpp - don't plan to make other changes to game code on this branch.
diff --git a/Src/DasherCore/GameModule.cpp b/Src/DasherCore/GameModule.cpp index 5d41f21..4818633 100644 --- a/Src/DasherCore/GameModule.cpp +++ b/Src/DasherCore/GameModule.cpp @@ -1,67 +1,67 @@ #include "GameModule.h" using namespace Dasher; void CGameModule::HandleEvent(Dasher::CEvent *pEvent) { switch(pEvent->m_iEventType) { case EV_EDIT: { CEditEvent* evt = static_cast<CEditEvent*>(pEvent); switch(evt->m_iEditType) { // Added a new character (Stepped one node forward) case 0: m_stCurrentStringPos++; //pLastTypedNode = StringToNode(evt->m_sText); break; // Removed a character (Stepped one node back) case 1: break; default: break; } break; } case EV_TEXTDRAW: { CTextDrawEvent *evt = static_cast<CTextDrawEvent*>(pEvent); if(!m_sTargetString.substr(m_stCurrentStringPos+1, 1).compare(evt->m_sDisplayText) && evt->m_iY < GetLongParameter(LP_OX)) { - evt->m_pDasherView->Screen2Dasher(evt->m_iX, evt->m_iY, m_iTargetX, m_iTargetY); + evt->m_pDasherView->Screen2Dasher(evt->m_iX, evt->m_iY, m_iTargetX, m_iTargetY); } } break; default: break; } return; } bool CGameModule::DecorateView(CDasherView *pView) { //set up the points for the arrow through - starts at the crosshair, ends at the target letter myint x[2] = {GetLongParameter(LP_OX), m_iTargetX}; myint y[2] = {GetLongParameter(LP_OY), m_iTargetY}; pView->DasherPolyarrow(x, y, m_iArrowNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iArrowColor, m_dArrowSizeFactor); return true; } //CDasherNode CGameModule::StringToNode(std::string sText) { // //} std::string CGameModule::GetTypedTarget() { return m_sTargetString.substr(0, m_stCurrentStringPos - 1); } std::string CGameModule::GetUntypedTarget() { return m_sTargetString.substr(m_stCurrentStringPos); }
rgee/HFOSS-Dasher
30f1282e45875ef7cd67c7f64beea79eb49fa47b
Game Module now draws an arrow that points to target letters. There are, however, still significant issues to work out with it's behavior. Removed g_pLogger->Log() calls from places we were previously experimenting, and added documentation to DasherView::DasherPolyArrow()
diff --git a/Src/DasherCore/DasherInterfaceBase.cpp b/Src/DasherCore/DasherInterfaceBase.cpp index 5412ab2..ec690e2 100644 --- a/Src/DasherCore/DasherInterfaceBase.cpp +++ b/Src/DasherCore/DasherInterfaceBase.cpp @@ -369,795 +369,794 @@ void CDasherInterfaceBase::InterfaceEventHandler(Dasher::CEvent *pEvent) { m_pDasherModel->TriggerSlowdown(); } } } void CDasherInterfaceBase::WriteTrainFileFull() { WriteTrainFile(strTrainfileBuffer); strTrainfileBuffer = ""; } void CDasherInterfaceBase::WriteTrainFilePartial() { // TODO: what if we're midway through a unicode character? WriteTrainFile(strTrainfileBuffer.substr(0,100)); strTrainfileBuffer = strTrainfileBuffer.substr(100); } void CDasherInterfaceBase::CreateModel(int iOffset) { // Creating a model without a node creation manager is a bad plan if(!m_pNCManager) return; if(m_pDasherModel) { delete m_pDasherModel; m_pDasherModel = 0; } m_pDasherModel = new CDasherModel(m_pEventHandler, m_pSettingsStore, m_pNCManager, this, m_pDasherView, iOffset); // Notify the teacher of the new model if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) pTeacher->SetDasherModel(m_pDasherModel); } void CDasherInterfaceBase::CreateNCManager() { // TODO: Try and make this work without necessarilty rebuilding the model if(!m_AlphIO) return; int lmID = GetLongParameter(LP_LANGUAGE_MODEL_ID); if( lmID == -1 ) return; int iOffset; if(m_pDasherModel) iOffset = m_pDasherModel->GetOffset(); else iOffset = 0; // TODO: Is this right? // Delete the old model and create a new one if(m_pDasherModel) { delete m_pDasherModel; m_pDasherModel = 0; } if(m_pNCManager) { delete m_pNCManager; m_pNCManager = 0; } m_pNCManager = new CNodeCreationManager(this, m_pEventHandler, m_pSettingsStore, m_AlphIO); m_Alphabet = m_pNCManager->GetAlphabet(); // TODO: Eventually we'll not have to pass the NC manager to the model... CreateModel(iOffset); } void CDasherInterfaceBase::Pause() { if (GetBoolParameter(BP_DASHER_PAUSED)) return; //already paused, no need to do anything. SetBoolParameter(BP_DASHER_PAUSED, true); // Request a full redraw at the next time step. SetBoolParameter(BP_REDRAW, true); Dasher::CStopEvent oEvent; m_pEventHandler->InsertEvent(&oEvent); #ifndef _WIN32_WCE if (m_pUserLog != NULL) m_pUserLog->StopWriting((float) GetNats()); #endif } void CDasherInterfaceBase::GameMessageIn(int message, void* messagedata) { GameMode::CDasherGameMode::GetTeacher()->Message(message, messagedata); } void CDasherInterfaceBase::Unpause(unsigned long Time) { if (!GetBoolParameter(BP_DASHER_PAUSED)) return; //already running, no need to do anything SetBoolParameter(BP_DASHER_PAUSED, false); if(m_pDasherModel != 0) m_pDasherModel->Reset_framerate(Time); Dasher::CStartEvent oEvent; m_pEventHandler->InsertEvent(&oEvent); // Commenting this out, can't see a good reason to ResetNats, // just because we are not paused anymore - pconlon // ResetNats(); #ifndef _WIN32_WCE if (m_pUserLog != NULL) m_pUserLog->StartWriting(); #endif } void CDasherInterfaceBase::CreateInput() { if(m_pInput) { m_pInput->Deactivate(); } m_pInput = (CDasherInput *)GetModuleByName(GetStringParameter(SP_INPUT_DEVICE)); if (m_pInput == NULL) m_pInput = (CDasherInput *)GetDefaultInputDevice(); if(m_pInput) { m_pInput->Activate(); } if(m_pDasherView != 0) m_pDasherView->SetInput(m_pInput); } void CDasherInterfaceBase::NewFrame(unsigned long iTime, bool bForceRedraw) { // Prevent NewFrame from being reentered. This can happen occasionally and // cause crashes. static bool bReentered=false; if (bReentered) { #ifdef DEBUG std::cout << "CDasherInterfaceBase::NewFrame was re-entered" << std::endl; #endif return; } bReentered=true; // Fail if Dasher is locked // if(m_iCurrentState != ST_NORMAL) // return; bool bChanged(false), bWasPaused(GetBoolParameter(BP_DASHER_PAUSED)); CExpansionPolicy *pol=m_defaultPolicy; if(m_pDasherView != 0) { if(!GetBoolParameter(BP_TRAINING)) { if (m_pUserLog != NULL) { //ACL note that as of 15/5/09, splitting UpdatePosition into two, //DasherModel no longer guarantees to empty these two if it didn't do anything. //So initialise appropriately... Dasher::VECTOR_SYMBOL_PROB vAdded; int iNumDeleted = 0; if(m_pInputFilter) { bChanged = m_pInputFilter->Timer(iTime, m_pDasherView, m_pDasherModel, &vAdded, &iNumDeleted, &pol); } #ifndef _WIN32_WCE if (iNumDeleted > 0) m_pUserLog->DeleteSymbols(iNumDeleted); if (vAdded.size() > 0) m_pUserLog->AddSymbols(&vAdded); #endif } else { if(m_pInputFilter) { bChanged = m_pInputFilter->Timer(iTime, m_pDasherView, m_pDasherModel, 0, 0, &pol); } } m_pDasherModel->CheckForNewRoot(m_pDasherView); } } //check: if we were paused before, and the input filter didn't unpause, // then nothing can have changed: DASHER_ASSERT(!bWasPaused || !GetBoolParameter(BP_DASHER_PAUSED) || !bChanged); // Flags at this stage: // // - bChanged = the display was updated, so needs to be rendered to the display // - m_bLastChanged = bChanged was true last time around // - m_bRedrawScheduled = Display invalidated internally // - bForceRedraw = Display invalidated externally // TODO: This is a bit hacky - we really need to sort out the redraw logic if((!bChanged && m_bLastChanged) || m_bRedrawScheduled || bForceRedraw) { m_pDasherView->Screen()->SetCaptureBackground(true); m_pDasherView->Screen()->SetLoadBackground(true); } bForceRedraw |= m_bLastChanged; m_bLastChanged = bChanged; //will also be set in Redraw if any nodes were expanded. Redraw(bChanged || m_bRedrawScheduled || bForceRedraw, *pol); m_bRedrawScheduled = false; // This just passes the time through to the framerate tracker, so we // know how often new frames are being drawn. if(m_pDasherModel != 0) m_pDasherModel->RecordFrame(iTime); bReentered=false; } void CDasherInterfaceBase::Redraw(bool bRedrawNodes, CExpansionPolicy &policy) { // No point continuing if there's nothing to draw on... if(!m_pDasherView) return; // Draw the nodes if(bRedrawNodes) { m_pDasherView->Screen()->SendMarker(0); if (m_pDasherModel) m_bLastChanged |= m_pDasherModel->RenderToView(m_pDasherView,policy); } // Draw the decorations m_pDasherView->Screen()->SendMarker(1); if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) pTeacher->DrawGameDecorations(m_pDasherView); bool bDecorationsChanged(false); if(m_pInputFilter) { bDecorationsChanged = m_pInputFilter->DecorateView(m_pDasherView); } if(m_pGameModule) { bDecorationsChanged = m_pGameModule->DecorateView(m_pDasherView) || bDecorationsChanged; } bool bActionButtonsChanged(false); #ifdef EXPERIMENTAL_FEATURES bActionButtonsChanged = DrawActionButtons(); #endif // Only blit the image to the display if something has actually changed if(bRedrawNodes || bDecorationsChanged || bActionButtonsChanged) m_pDasherView->Display(); } void CDasherInterfaceBase::ChangeAlphabet() { if(GetStringParameter(SP_ALPHABET_ID) == "") { SetStringParameter(SP_ALPHABET_ID, m_AlphIO->GetDefault()); // This will result in ChangeAlphabet() being called again, so // exit from the first recursion return; } // Send a lock event WriteTrainFileFull(); // Lock Dasher to prevent changes from happening while we're training. SetBoolParameter( BP_TRAINING, true ); CreateNCManager(); #ifndef _WIN32_WCE // Let our user log object know about the new alphabet since // it needs to convert symbols into text for the log file. if (m_pUserLog != NULL) m_pUserLog->SetAlphabetPtr(m_Alphabet); #endif // Apply options from alphabet SetBoolParameter( BP_TRAINING, false ); //} } void CDasherInterfaceBase::ChangeColours() { if(!m_ColourIO || !m_DasherScreen) return; // TODO: Make fuction return a pointer directly m_DasherScreen->SetColourScheme(&(m_ColourIO->GetInfo(GetStringParameter(SP_COLOUR_ID)))); } void CDasherInterfaceBase::ChangeScreen(CDasherScreen *NewScreen) { // What does ChangeScreen do? m_DasherScreen = NewScreen; ChangeColours(); if(m_pDasherView != 0) { m_pDasherView->ChangeScreen(m_DasherScreen); } else if(GetLongParameter(LP_VIEW_ID) != -1) { ChangeView(); } PositionActionButtons(); BudgettingPolicy pol(GetLongParameter(LP_NODE_BUDGET)); //maintain budget, but allow arbitrary amount of work. Redraw(true, pol); // (we're assuming resolution changes are occasional, i.e. // we don't need to worry about maintaining the frame rate, so we can do // as much work as necessary. However, it'd probably be better still to // get a node queue from the input filter, as that might have a different // policy / budget. } void CDasherInterfaceBase::ChangeView() { // TODO: Actually respond to LP_VIEW_ID parameter (although there is only one view at the moment) // removed condition that m_pDasherModel != 0. Surely the view can exist without the model?-pconlon if(m_DasherScreen != 0 /*&& m_pDasherModel != 0*/) { delete m_pDasherView; m_pDasherView = new CDasherViewSquare(m_pEventHandler, m_pSettingsStore, m_DasherScreen); if (m_pInput) m_pDasherView->SetInput(m_pInput); // Tell the Teacher which view we are using if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) pTeacher->SetDasherView(m_pDasherView); } } const CAlphIO::AlphInfo & CDasherInterfaceBase::GetInfo(const std::string &AlphID) { return m_AlphIO->GetInfo(AlphID); } void CDasherInterfaceBase::SetInfo(const CAlphIO::AlphInfo &NewInfo) { m_AlphIO->SetInfo(NewInfo); } void CDasherInterfaceBase::DeleteAlphabet(const std::string &AlphID) { m_AlphIO->Delete(AlphID); } double CDasherInterfaceBase::GetCurCPM() { // return 0; } double CDasherInterfaceBase::GetCurFPS() { // return 0; } // int CDasherInterfaceBase::GetAutoOffset() { // if(m_pDasherView != 0) { // return m_pDasherView->GetAutoOffset(); // } // return -1; // } double CDasherInterfaceBase::GetNats() const { if(m_pDasherModel) return m_pDasherModel->GetNats(); else return 0.0; } void CDasherInterfaceBase::ResetNats() { if(m_pDasherModel) m_pDasherModel->ResetNats(); } // TODO: Check that none of this needs to be reimplemented // void CDasherInterfaceBase::InvalidateContext(bool bForceStart) { // m_pDasherModel->m_strContextBuffer = ""; // Dasher::CEditContextEvent oEvent(10); // m_pEventHandler->InsertEvent(&oEvent); // std::string strNewContext(m_pDasherModel->m_strContextBuffer); // // We keep track of an internal context and compare that to what // // we are given - don't restart Dasher if nothing has changed. // // This should really be integrated with DasherModel, which // // probably will be the case when we start to deal with being able // // to back off indefinitely. For now though we'll keep it in a // // separate string. // int iContextLength( 6 ); // The 'important' context length - should really get from language model // // FIXME - use unicode lengths // if(bForceStart || (strNewContext.substr( std::max(static_cast<int>(strNewContext.size()) - iContextLength, 0)) != strCurrentContext.substr( std::max(static_cast<int>(strCurrentContext.size()) - iContextLength, 0)))) { // if(m_pDasherModel != NULL) { // // TODO: Reimplement this // // if(m_pDasherModel->m_bContextSensitive || bForceStart) { // { // m_pDasherModel->SetContext(strNewContext); // PauseAt(0,0); // } // } // strCurrentContext = strNewContext; // WriteTrainFileFull(); // } // if(bForceStart) { // int iMinWidth; // if(m_pInputFilter && m_pInputFilter->GetMinWidth(iMinWidth)) { // m_pDasherModel->LimitRoot(iMinWidth); // } // } // if(m_pDasherView) // while( m_pDasherModel->CheckForNewRoot(m_pDasherView) ) { // // Do nothing // } // ScheduleRedraw(); // } // TODO: Fix this std::string CDasherInterfaceBase::GetContext(int iStart, int iLength) { m_strContext = ""; CEditContextEvent oEvent(iStart, iLength); m_pEventHandler->InsertEvent(&oEvent); return m_strContext; } void CDasherInterfaceBase::SetContext(std::string strNewContext) { m_strContext = strNewContext; } // Control mode stuff void CDasherInterfaceBase::RegisterNode( int iID, const std::string &strLabel, int iColour ) { m_pNCManager->RegisterNode(iID, strLabel, iColour); } void CDasherInterfaceBase::ConnectNode(int iChild, int iParent, int iAfter) { m_pNCManager->ConnectNode(iChild, iParent, iAfter); } void CDasherInterfaceBase::DisconnectNode(int iChild, int iParent) { m_pNCManager->DisconnectNode(iChild, iParent); } void CDasherInterfaceBase::SetBoolParameter(int iParameter, bool bValue) { m_pSettingsStore->SetBoolParameter(iParameter, bValue); }; void CDasherInterfaceBase::SetLongParameter(int iParameter, long lValue) { m_pSettingsStore->SetLongParameter(iParameter, lValue); }; void CDasherInterfaceBase::SetStringParameter(int iParameter, const std::string & sValue) { PreSetNotify(iParameter, sValue); m_pSettingsStore->SetStringParameter(iParameter, sValue); }; bool CDasherInterfaceBase::GetBoolParameter(int iParameter) { return m_pSettingsStore->GetBoolParameter(iParameter); } long CDasherInterfaceBase::GetLongParameter(int iParameter) { return m_pSettingsStore->GetLongParameter(iParameter); } std::string CDasherInterfaceBase::GetStringParameter(int iParameter) { return m_pSettingsStore->GetStringParameter(iParameter); } void CDasherInterfaceBase::ResetParameter(int iParameter) { m_pSettingsStore->ResetParameter(iParameter); } // We need to be able to get at the UserLog object from outside the interface CUserLogBase* CDasherInterfaceBase::GetUserLogPtr() { return m_pUserLog; } void CDasherInterfaceBase::KeyDown(int iTime, int iId, bool bPos, int iX, int iY) { if(m_iCurrentState != ST_NORMAL) return; if(m_pInputFilter && !GetBoolParameter(BP_TRAINING)) { m_pInputFilter->KeyDown(iTime, iId, m_pDasherView, m_pDasherModel, m_pUserLog, bPos, iX, iY); } if(m_pInput && !GetBoolParameter(BP_TRAINING)) { m_pInput->KeyDown(iTime, iId); } } void CDasherInterfaceBase::KeyUp(int iTime, int iId, bool bPos, int iX, int iY) { if(m_iCurrentState != ST_NORMAL) return; if(m_pInputFilter && !GetBoolParameter(BP_TRAINING)) { m_pInputFilter->KeyUp(iTime, iId, m_pDasherView, m_pDasherModel, bPos, iX, iY); } if(m_pInput && !GetBoolParameter(BP_TRAINING)) { m_pInput->KeyUp(iTime, iId); } } void CDasherInterfaceBase::InitGameModule() { if(m_pGameModule == NULL) { - g_pLogger->Log("Initializing the game module."); m_pGameModule = (CGameModule*) GetModuleByName("Game Mode"); } } void CDasherInterfaceBase::CreateInputFilter() { if(m_pInputFilter) { m_pInputFilter->Deactivate(); m_pInputFilter = NULL; } #ifndef _WIN32_WCE m_pInputFilter = (CInputFilter *)GetModuleByName(GetStringParameter(SP_INPUT_FILTER)); #endif if (m_pInputFilter == NULL) m_pInputFilter = (CInputFilter *)GetDefaultInputMethod(); m_pInputFilter->Activate(); } CDasherModule *CDasherInterfaceBase::RegisterModule(CDasherModule *pModule) { return m_oModuleManager.RegisterModule(pModule); } CDasherModule *CDasherInterfaceBase::GetModule(ModuleID_t iID) { return m_oModuleManager.GetModule(iID); } CDasherModule *CDasherInterfaceBase::GetModuleByName(const std::string &strName) { return m_oModuleManager.GetModuleByName(strName); } CDasherModule *CDasherInterfaceBase::GetDefaultInputDevice() { return m_oModuleManager.GetDefaultInputDevice(); } CDasherModule *CDasherInterfaceBase::GetDefaultInputMethod() { return m_oModuleManager.GetDefaultInputMethod(); } void CDasherInterfaceBase::SetDefaultInputDevice(CDasherModule *pModule) { m_oModuleManager.SetDefaultInputDevice(pModule); } void CDasherInterfaceBase::SetDefaultInputMethod(CDasherModule *pModule) { m_oModuleManager.SetDefaultInputMethod(pModule); } void CDasherInterfaceBase::CreateModules() { SetDefaultInputMethod( RegisterModule(new CDefaultFilter(m_pEventHandler, m_pSettingsStore, this, 3, _("Normal Control"))) ); RegisterModule(new COneDimensionalFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CEyetrackerFilter(m_pEventHandler, m_pSettingsStore, this)); #ifndef _WIN32_WCE RegisterModule(new CClickFilter(m_pEventHandler, m_pSettingsStore, this)); #else SetDefaultInputMethod( RegisterModule(new CClickFilter(m_pEventHandler, m_pSettingsStore, this)); ); #endif RegisterModule(new COneButtonFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new COneButtonDynamicFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CTwoButtonDynamicFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CTwoPushDynamicFilter(m_pEventHandler, m_pSettingsStore, this)); // TODO: specialist factory for button mode RegisterModule(new CButtonMode(m_pEventHandler, m_pSettingsStore, this, true, 8, _("Menu Mode"))); RegisterModule(new CButtonMode(m_pEventHandler, m_pSettingsStore, this, false,10, _("Direct Mode"))); // RegisterModule(new CDasherButtons(m_pEventHandler, m_pSettingsStore, this, 4, 0, false,11, "Buttons 3")); RegisterModule(new CAlternatingDirectMode(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CCompassMode(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CStylusFilter(m_pEventHandler, m_pSettingsStore, this, 15, _("Stylus Control"))); // Register game mode with the module manager // TODO should this be wrapped in an "if game mode enabled" // conditional? // TODO: I don't know what a sensible module ID should be // for this, so I chose an arbitrary value // TODO: Put "Game Mode" in enumeration in Parameter.h RegisterModule(new CGameModule(m_pEventHandler, m_pSettingsStore, this, 21, _("Game Mode"))); } void CDasherInterfaceBase::GetPermittedValues(int iParameter, std::vector<std::string> &vList) { // TODO: Deprecate direct calls to these functions switch (iParameter) { case SP_ALPHABET_ID: if(m_AlphIO) m_AlphIO->GetAlphabets(&vList); break; case SP_COLOUR_ID: if(m_ColourIO) m_ColourIO->GetColours(&vList); break; case SP_INPUT_FILTER: m_oModuleManager.ListModules(1, vList); break; case SP_INPUT_DEVICE: m_oModuleManager.ListModules(0, vList); break; } } void CDasherInterfaceBase::StartShutdown() { ChangeState(TR_SHUTDOWN); } bool CDasherInterfaceBase::GetModuleSettings(const std::string &strName, SModuleSettings **pSettings, int *iCount) { return GetModuleByName(strName)->GetSettings(pSettings, iCount); } void CDasherInterfaceBase::SetupActionButtons() { m_vLeftButtons.push_back(new CActionButton(this, "Exit", true)); m_vLeftButtons.push_back(new CActionButton(this, "Preferences", false)); m_vLeftButtons.push_back(new CActionButton(this, "Help", false)); m_vLeftButtons.push_back(new CActionButton(this, "About", false)); } void CDasherInterfaceBase::DestroyActionButtons() { // TODO: implement and call this } void CDasherInterfaceBase::PositionActionButtons() { if(!m_DasherScreen) return; int iCurrentOffset(16); for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) { (*it)->SetPosition(16, iCurrentOffset, 32, 32); iCurrentOffset += 48; } iCurrentOffset = 16; for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) { (*it)->SetPosition(m_DasherScreen->GetWidth() - 144, iCurrentOffset, 128, 32); iCurrentOffset += 48; } } bool CDasherInterfaceBase::DrawActionButtons() { if(!m_DasherScreen) return false; bool bVisible(GetBoolParameter(BP_DASHER_PAUSED)); bool bRV(bVisible != m_bOldVisible); m_bOldVisible = bVisible; for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) (*it)->Draw(m_DasherScreen, bVisible); for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) (*it)->Draw(m_DasherScreen, bVisible); return bRV; } void CDasherInterfaceBase::HandleClickUp(int iTime, int iX, int iY) { #ifdef EXPERIMENTAL_FEATURES bool bVisible(GetBoolParameter(BP_DASHER_PAUSED)); for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) { if((*it)->HandleClickUp(iTime, iX, iY, bVisible)) return; } for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) { if((*it)->HandleClickUp(iTime, iX, iY, bVisible)) return; } #endif KeyUp(iTime, 100, true, iX, iY); } void CDasherInterfaceBase::HandleClickDown(int iTime, int iX, int iY) { #ifdef EXPERIMENTAL_FEATURES bool bVisible(GetBoolParameter(BP_DASHER_PAUSED)); for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) { if((*it)->HandleClickDown(iTime, iX, iY, bVisible)) return; } for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) { if((*it)->HandleClickDown(iTime, iX, iY, bVisible)) return; } #endif KeyDown(iTime, 100, true, iX, iY); } void CDasherInterfaceBase::ExecuteCommand(const std::string &strName) { // TODO: Pointless - just insert event directly CCommandEvent *pEvent = new CCommandEvent(strName); m_pEventHandler->InsertEvent(pEvent); delete pEvent; } double CDasherInterfaceBase::GetFramerate() { if(m_pDasherModel) return(m_pDasherModel->Framerate()); else return 0.0; } void CDasherInterfaceBase::AddActionButton(const std::string &strName) { m_vRightButtons.push_back(new CActionButton(this, strName, false)); } void CDasherInterfaceBase::OnUIRealised() { StartTimer(); ChangeState(TR_UI_INIT); } void CDasherInterfaceBase::ChangeState(ETransition iTransition) { static EState iTransitionTable[ST_NUM][TR_NUM] = { {ST_MODEL, ST_UI, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN},//ST_START {ST_FORBIDDEN, ST_NORMAL, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN},//ST_MODEL {ST_NORMAL, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN},//ST_UI {ST_FORBIDDEN, ST_FORBIDDEN, ST_LOCKED, ST_FORBIDDEN, ST_SHUTDOWN},//ST_NORMAL {ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_NORMAL, ST_FORBIDDEN},//ST_LOCKED {ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN}//ST_SHUTDOWN //TR_MODEL_INIT, TR_UI_INIT, TR_LOCK, TR_UNLOCK, TR_SHUTDOWN }; EState iNewState(iTransitionTable[m_iCurrentState][iTransition]); if(iNewState != ST_FORBIDDEN) { if (iNewState == ST_SHUTDOWN) { ShutdownTimer(); WriteTrainFileFull(); } m_iCurrentState = iNewState; } } void CDasherInterfaceBase::SetBuffer(int iOffset) { CreateModel(iOffset); } void CDasherInterfaceBase::UnsetBuffer() { // TODO: Write training file? if(m_pDasherModel) delete m_pDasherModel; m_pDasherModel = 0; } void CDasherInterfaceBase::SetOffset(int iOffset) { if(m_pDasherModel) m_pDasherModel->SetOffset(iOffset, m_pDasherView); } void CDasherInterfaceBase::SetControlOffset(int iOffset) { if(m_pDasherModel) m_pDasherModel->SetControlOffset(iOffset); } // Returns 0 on success, an error string on failure. const char* CDasherInterfaceBase::ClSet(const std::string &strKey, const std::string &strValue) { if(m_pSettingsStore) return m_pSettingsStore->ClSet(strKey, strValue); return 0; } void CDasherInterfaceBase::ImportTrainingText(const std::string &strPath) { if(m_pNCManager) m_pNCManager->ImportTrainingText(strPath); } diff --git a/Src/DasherCore/DasherInterfaceBase.h b/Src/DasherCore/DasherInterfaceBase.h index 7ea4099..d061403 100644 --- a/Src/DasherCore/DasherInterfaceBase.h +++ b/Src/DasherCore/DasherInterfaceBase.h @@ -1,567 +1,567 @@ // DasherInterfaceBase.h // // Copyright (c) 2008 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #ifndef __DasherInterfaceBase_h__ #define __DasherInterfaceBase_h__ /// /// \mainpage /// /// This is the Dasher source code documentation. Please try to keep /// it up to date! /// // TODO - there is a list of things to be configurable in my notes // Check that everything that is not self-contained within the GUI is covered. #include "../Common/NoClones.h" #include "../Common/ModuleSettings.h" #include "ActionButton.h" #include "Alphabet/Alphabet.h" #include "Alphabet/AlphIO.h" #include "AutoSpeedControl.h" #include "ColourIO.h" #include "InputFilter.h" #include "ModuleManager.h" #include "GameModule.h" #include <map> #include <algorithm> namespace Dasher { class CDasherScreen; class CDasherView; class CDasherInput; class CDasherModel; class CEventHandler; class CEvent; - + class CGameModule; class CDasherInterfaceBase; } class CSettingsStore; class CUserLogBase; class CNodeCreationManager; /// \defgroup Core Core Dasher classes /// @{ struct Dasher::SLockData { std::string strDisplay; int iPercent; }; /// The central class in the core of Dasher. Ties together the rest of /// the platform independent stuff and provides a single interface for /// the UI to use. class Dasher::CDasherInterfaceBase:private NoClones { public: CDasherInterfaceBase(); virtual ~CDasherInterfaceBase(); /// @name Access to internal member classes /// Access various classes contained within the interface. These /// should be considered dangerous and use minimised. Eventually to /// be replaced by properly encapsulated equivalents. /// @{ /// /// Return a pointer to the current EventHandler (the one /// which the CSettingsStore is using to notify parameter /// changes) /// virtual CEventHandler *GetEventHandler() { return m_pEventHandler; }; /// /// \deprecated In situ alphabet editing is no longer supported /// \todo Document this /// const CAlphIO::AlphInfo & GetInfo(const std::string & AlphID); /// \todo Document this void SetInfo(const CAlphIO::AlphInfo & NewInfo); /// \todo Document this void DeleteAlphabet(const std::string & AlphID); /// Get a pointer to the current alphabet object CAlphabet *GetAlphabet() { return m_Alphabet; } /// Gets a pointer to the object doing user logging CUserLogBase* GetUserLogPtr(); // @} /// /// @name Parameter manipulation /// Members for manipulating the parameters of the core Dasher object. /// //@{ /// /// Set a boolean parameter. /// \param iParameter The parameter to set. /// \param bValue The new value. /// void SetBoolParameter(int iParameter, bool bValue); /// /// Set a long integer parameter. /// \param iParameter The parameter to set. /// \param lValue The new value. /// void SetLongParameter(int iParameter, long lValue); /// /// Set a string parameter. /// \param iParameter The parameter to set. /// \param sValue The new value. /// void SetStringParameter(int iParameter, const std::string & sValue); /// Get a boolean parameter /// \param iParameter The parameter to get. /// \retval The current value. bool GetBoolParameter(int iParameter); /// Get a long integer parameter /// \param iParameter The parameter to get. /// \retval The current value. long GetLongParameter(int iParameter); /// Get a string parameter /// \param iParameter The parameter to get. /// \retval The current value. std::string GetStringParameter(int iParameter); /// /// Reset a parameter to the default value /// void ResetParameter(int iParmater); /// /// Obtain the permitted values for a string parameter - used to /// geneate preferences dialogues etc. /// void GetPermittedValues(int iParameter, std::vector<std::string> &vList); /// /// Get a list of settings which apply to a particular module /// bool GetModuleSettings(const std::string &strName, SModuleSettings **pSettings, int *iCount); //@} /// Forward events to listeners in the SettingsUI and Editbox. /// \param pEvent The event to forward. /// \todo Should be protected. virtual void ExternalEventHandler(Dasher::CEvent * pEvent) {}; /// Interface level event handler. For example, responsible for /// restarting the Dasher model whenever parameter changes make it /// invalid. /// \param pEvent The event. /// \todo Should be protected. void InterfaceEventHandler(Dasher::CEvent * pEvent); void PreSetNotify(int iParameter, const std::string &sValue); /// @name Starting and stopping /// Methods used to instruct dynamic motion of Dasher to start or stop /// @{ /// Resets the Dasher model. Doesn't actually unpause Dasher. /// \deprecated Use InvalidateContext() instead // void Start(); /// Pause Dasher. Sets BP_DASHER_PAUSED and broadcasts a StopEvent. /// (But does nothing if BP_DASHER_PAUSED is not set) void Pause(); // are required to make /// Unpause Dasher. Clears BP_DASHER_PAUSED, broadcasts a StartEvent. /// (But does nothing if BP_DASHER_PAUSED is currently set). /// \param Time Time in ms, used to keep a constant frame rate void Unpause(unsigned long Time); // Dasher run at the /// @} // App Interface // ----------------------------------------------------- // std::map<int, std::string>& GetAlphabets(); // map<key, value> int is a UID string can change. Store UID in preferences. Display string to user. // std::vector<std::string>& GetAlphabets(); // std::vector<std::string>& GetLangModels(); // std::vector<std::string>& GetViews(); /// Supply a new CDasherScreen object to do the rendering. /// \param NewScreen Pointer to the new CDasherScreen. void ChangeScreen(CDasherScreen * NewScreen); // We may change the widgets Dasher uses /// Train Dasher from a file /// All traing data must be in UTF-8 /// \param Filename File to load. /// \param iTotalBytes documentme /// \param iOffset Document me // int TrainFile(std::string Filename, int iTotalBytes, int iOffset); /// Set the context in which Dasher makes predictions /// \param strNewContext The new context (UTF-8) void SetContext(std::string strNewContext); /// New control mechanisms: void SetBuffer(int iOffset); void UnsetBuffer(); void SetOffset(int iOffset); /// @name Status reporting /// Get information about the runtime status of Dasher which might /// be of interest for debugging purposes etc. /// @{ /// Get the current rate of text entry. /// \retval The rate in characters per minute. /// TODO: Check that this is still used double GetCurCPM(); /// Get current refresh rate. /// \retval The rate in frames per second /// TODO: Check that this is still used double GetCurFPS(); /// Get the total number of nats (base-e bits) entered. /// \retval The current total /// \todo Obsolete since new logging code? double GetNats() const; /// Reset the count of nats entered. /// \todo Obsolete since new logging code? void ResetNats(); double GetFramerate(); /// @} /// @name Control hierarchy and action buttons /// Manipulate the hierarchy of commands presented in control mode etc /// @{ void RegisterNode( int iID, const std::string &strLabel, int iColour ); void ConnectNode(int iChild, int iParent, int iAfter); void DisconnectNode(int iChild, int iParent); void ExecuteCommand(const std::string &strName); void AddActionButton(const std::string &strName); /// @} /// @name User input /// Deals with forwarding user input to the core /// @{ void KeyDown(int iTime, int iId, bool bPos = false, int iX = 0, int iY = 0); void KeyUp(int iTime, int iId, bool bPos = false, int iX = 0, int iY = 0); void HandleClickUp(int iTime, int iX, int iY); void HandleClickDown(int iTime, int iX, int iY); /// @} // Module management functions CDasherModule *RegisterModule(CDasherModule *pModule); CDasherModule *GetModule(ModuleID_t iID); CDasherModule *GetModuleByName(const std::string &strName); CDasherModule *GetDefaultInputDevice(); CDasherModule *GetDefaultInputMethod(); void SetDefaultInputDevice(CDasherModule *); void SetDefaultInputMethod(CDasherModule *); void StartShutdown(); void AddGameModeString(const std::string &strText) { m_deGameModeStrings.push_back(strText); Pause(); // CreateDasherModel(); CreateNCManager(); // Start(); }; void GameMessageIn(int message, void* messagedata); virtual void GameMessageOut(int message, const void* messagedata) {} void ScheduleRedraw() { m_bRedrawScheduled = true; }; std::string GetContext(int iStart, int iLength); void SetControlOffset(int iOffset); /// Set a key value pair by name - designed to allow operation from /// the command line. Returns 0 on success, an error string on failure. /// const char* ClSet(const std::string &strKey, const std::string &strValue); void ImportTrainingText(const std::string &strPath); protected: /// @name Startup /// Interaction with the derived class during core startup /// @{ /// /// Allocate resources, create alphabets etc. This is a separate /// routine to the constructor to give us a chance to set up /// parameters before things are created. /// void Realize(); /// /// Notify the core that the UI has been realised. At this point drawing etc. is expected to work /// void OnUIRealised(); /// /// Creates a default set of modules. Override in subclasses to create any /// extra/different modules specific to the platform (eg input device drivers) /// virtual void CreateModules(); /// @} /// Draw a new Dasher frame, regardless of whether we're paused etc. /// \param iTime Current time in ms. /// \param bForceRedraw /// \todo See comments in cpp file for some functionality which needs to be re-implemented void NewFrame(unsigned long iTime, bool bForceRedraw); enum ETransition { TR_MODEL_INIT = 0, TR_UI_INIT, TR_LOCK, TR_UNLOCK, TR_SHUTDOWN, TR_NUM }; enum EState { ST_START = 0, ST_MODEL, ST_UI, ST_NORMAL, ST_LOCKED, ST_SHUTDOWN, ST_NUM, ST_FORBIDDEN, ST_DELAY }; /// @name State machine functions /// ... /// @{ void ChangeState(ETransition iTransition); /// @} CEventHandler *m_pEventHandler; CSettingsStore *m_pSettingsStore; private: //The default expansion policy to use - an amortized policy depending on the LP_NODE_BUDGET parameter. CExpansionPolicy *m_defaultPolicy; /// @name Platform dependent utility functions /// These functions provide various platform dependent functions /// required by the core. A derived class is created for each /// supported platform which implements these. // @{ /// /// Initialise the SP_SYSTEM_LOC and SP_USER_LOC paths - the exact /// method of doing this will be OS dependent /// virtual void SetupPaths() = 0; /// /// Produce a list of filenames for alphabet files /// virtual void ScanAlphabetFiles(std::vector<std::string> &vFileList) = 0; /// /// Produce a list of filenames for colour files /// virtual void ScanColourFiles(std::vector<std::string> &vFileList) = 0; /// /// Set up the platform dependent UI for the widget (not the wider /// app). Note that the constructor of the derived class will /// probably want to return details of what was created - this will /// have to happen separately, but we'll need to be careful with the /// semantics. /// virtual void SetupUI() = 0; /// /// Create settings store object, which will be platform dependent /// TODO: Can this not be done just by selecting which settings /// store implementation to instantiate? /// virtual void CreateSettingsStore() = 0; /// /// Obtain the size in bytes of a file - the way to do this is /// dependent on the OS (TODO: Check this - any posix on Windows?) /// virtual int GetFileSize(const std::string &strFileName) = 0; /// /// Start the callback timer /// virtual void StartTimer() = 0; /// /// Shutdown the callback timer (permenantly - this is called once /// Dasher is committed to closing). /// virtual void ShutdownTimer() = 0; /// /// Append text to the training file - used to store state between /// sessions /// @todo Pass file path to the function rather than having implementations work it out themselves /// virtual void WriteTrainFile(const std::string &strNewText) { }; /// @} /// Provide a new CDasherInput input device object. void CreateInput(); /* Initialize m_pGameModule by fetching the * constructed module from the module manager. */ void InitGameModule(); void CreateInputFilter(); void CreateModel(int iOffset); void CreateNCManager(); void ChangeAlphabet(); void ChangeColours(); void ChangeView(); void Redraw(bool bRedrawNodes, CExpansionPolicy &policy); void SetupActionButtons(); void DestroyActionButtons(); void PositionActionButtons(); bool DrawActionButtons(); void WriteTrainFileFull(); void WriteTrainFilePartial(); std::deque<std::string> m_deGameModeStrings; std::vector<CActionButton *> m_vLeftButtons; std::vector<CActionButton *> m_vRightButtons; /// @name Child components /// Various objects which are 'owned' by the core. /// @{ CAlphabet *m_Alphabet; CDasherModel *m_pDasherModel; CDasherScreen *m_DasherScreen; CDasherView *m_pDasherView; CDasherInput *m_pInput; CInputFilter* m_pInputFilter; CModuleManager m_oModuleManager; CAlphIO *m_AlphIO; CColourIO *m_ColourIO; CNodeCreationManager *m_pNCManager; CUserLogBase *m_pUserLog; // the game mode module - only // initialized if game mode is enabled diff --git a/Src/DasherCore/DasherView.h b/Src/DasherCore/DasherView.h index 9ef110a..8746051 100644 --- a/Src/DasherCore/DasherView.h +++ b/Src/DasherCore/DasherView.h @@ -1,212 +1,226 @@ // DasherView.h // // Copyright (c) 2001-2005 David Ward #ifndef __DasherView_h_ #define __DasherView_h_ namespace Dasher { class CDasherModel; class CDasherInput; // Why does DasherView care about input? - pconlon class CDasherComponent; class CDasherView; class CDasherNode; } #include "DasherTypes.h" #include "DasherComponent.h" #include "ExpansionPolicy.h" #include "DasherScreen.h" /// \defgroup View Visualisation of the model /// @{ /// \brief View base class. /// /// Dasher views represent the visualisation of a Dasher model on the screen. /// /// Note that we really should aim to avoid having to try and keep /// multiple pointers to the same object (model etc.) up-to-date at /// once. We should be able to avoid the need for this just by being /// sane about passing pointers as arguments to the relevant /// functions, for example we could pass a pointer to the canvas every /// time we call the render routine, rather than worrying about /// notifying this object every time it changes. The same logic can be /// applied in several other places. /// /// We should also attempt to try and remove the need for this class /// to know about the model. When we call render we should just pass a /// pointer to the root node, which we can obtain elsewhere, and make /// sure that the data structure contains all the info we need to do /// the rendering (eg make sure it contains strings as well as symbol /// IDs). /// /// There are really three roles played by CDasherView: providing high /// level drawing functions, providing a mapping between Dasher /// co-ordinates and screen co-ordinates and providing a mapping /// between true and effective Dasher co-ordinates (eg for eyetracking /// mode). We should probably consider creating separate classes for /// these. class Dasher::CDasherView : public Dasher::CDasherComponent { public: /// Constructor /// /// \param pEventHandler Pointer to the event handler /// \param pSettingsStore Pointer to the settings store /// \param DasherScreen Pointer to the CDasherScreen object used to do rendering CDasherView(CEventHandler * pEventHandler, CSettingsStore * pSettingsStore, CDasherScreen * DasherScreen); virtual ~CDasherView() { } /// @name Pointing device mappings /// @{ /// Set the input device class. Note that this class will now assume ownership of the pointer, ie it will delete the object when it's done with it. /// \param _pInput Pointer to the new CDasherInput. void SetInput(CDasherInput * _pInput); void SetDemoMode(bool); void SetGameMode(bool); /// Translates the screen coordinates to Dasher coordinates and calls /// dashermodel.TapOnDisplay virtual int GetCoordinates(myint &iDasherX, myint &iDasherY); /// Get the co-ordinate count from the input device int GetCoordinateCount(); /// @} /// /// @name Coordinate system conversion /// Convert between screen and Dasher coordinates /// @{ /// /// Convert a screen co-ordinate to Dasher co-ordinates /// virtual void Screen2Dasher(screenint iInputX, screenint iInputY, myint & iDasherX, myint & iDasherY) = 0; /// /// Convert Dasher co-ordinates to screen co-ordinates /// virtual void Dasher2Screen(myint iDasherX, myint iDasherY, screenint & iScreenX, screenint & iScreenY) = 0; /// /// Convert Dasher co-ordinates to polar co-ordinates (r,theta), with 0<r<1, 0<theta<2*pi /// virtual void Dasher2Polar(myint iDasherX, myint iDasherY, double &r, double &theta) = 0; virtual bool IsSpaceAroundNode(myint y1, myint y2)=0; virtual void VisibleRegion( myint &iDasherMinX, myint &iDasherMinY, myint &iDasherMaxX, myint &iDasherMaxY ) = 0; /// @} /// Change the screen - must be called if the Screen is replaced or resized /// \param NewScreen Pointer to the new CDasherScreen. virtual void ChangeScreen(CDasherScreen * NewScreen); /// @name High level drawing /// Drawing more complex structures, generally implemented by derived class /// @{ /// Renders Dasher with mouse-dependent items /// \todo Clarify relationship between Render functions and probably only expose one virtual void Render(CDasherNode *pRoot, myint iRootMin, myint iRootMax, CExpansionPolicy &policy, bool bRedrawDisplay); /// @} ////// Return a reference to the screen - can't be protected due to circlestarthandler CDasherScreen *Screen() { return m_pScreen; } /// /// @name Low level drawing /// Basic drawing primitives specified in Dasher coordinates. /// @{ ///Draw a straight line in Dasher-space - which may be curved on the screen... void DasherSpaceLine(myint x1, myint y1, myint x2, myint y2, int iWidth, int iColour); /// /// Draw a polyline specified in Dasher co-ordinates /// void DasherPolyline(myint * x, myint * y, int n, int iWidth, int iColour); - /// Draw a polyarrow + /** + * Draw an arrow in Dasher space. The parameters x and y allow the client to specify + * points through which the arrow's main line should be drawn. For example, to draw an + * arrow through the Dasher coordinates (1000, 2000) and (3000, 4000), one would pass in: + * + * myint x[2] = {1000, 3000}; + * myint y[2] = {2000, 4000}; + * + * @param x - an array of x coordinates to draw the arrow through + * @param y - an array of y coordinates to draw the arrow through + * @param iWidth - the width to make the arrow lines - typically of the form + * GetLongParameter(LP_LINE_WIDTH)*CONSTANT + * @param iColour - the color to make the arrow (in Dasher color) + * @param dArrowSizeFactor - the factor by which to scale the "hat" on the arrow + */ void DasherPolyarrow(myint * x, myint * y, int n, int iWidth, int iColour, double dArrowSizeFactor = 0.7071); /// /// Draw a rectangle specified in Dasher co-ordinates /// Color of -1 => no fill; any other value => fill in that color /// iOutlineColor of -1 => no outline; any other value => outline in that color, EXCEPT /// Thickness < 1 => no outline. /// void DasherDrawRectangle(myint iLeft, myint iTop, myint iRight, myint iBottom, const int Color, int iOutlineColour, Opts::ColorSchemes ColorScheme, int iThickness); /// /// Draw a centred rectangle specified in Dasher co-ordinates (used for mouse cursor) /// void DasherDrawCentredRectangle(myint iDasherX, myint iDasherY, screenint iSize, const int Color, Opts::ColorSchemes ColorScheme, bool bDrawOutline); void DrawText(const std::string & str, myint x, myint y, int Size, int iColor); /// Request the Screen to copy its buffer to the Display /// \todo Shouldn't be public? void Display(); /// @} protected: /// Clips a line (specified in Dasher co-ordinates) to the visible region /// by intersecting with all boundaries. /// \return true if any part of the line was within the visible region; in this case, (x1,y1)-(x2,y2) delineate exactly that part /// false if the line would be entirely outside the visible region; x1, y1, x2, y2 unaffected. bool ClipLineToVisible(myint &x1, myint &y1, myint &x2, myint &y2); ///Convert a straight line in Dasher-space, to coordinates for a corresponding polyline on the screen /// (because of nonlinearity, this may require multiple line segments) /// \param x1,y1 Dasher co-ordinates of start of line segment; note that these are guaranteed within VisibleRegion. /// \param x2,y2 Dasher co-ordinates of end of line segment; also guaranteed within VisibleRegion. /// \param vPoints vector to which to add screen points. Note that at the point that DasherLine2Screen is called, /// the screen coordinates of the first point should already have been added to this vector; DasherLine2Screen /// will then add exactly one CDasherScreen::point for each line segment required. virtual void DasherLine2Screen(myint x1, myint y1, myint x2, myint y2, std::vector<CDasherScreen::point> &vPoints)=0; // Orientation of Dasher Screen /* inline void MapScreen(screenint * DrawX, screenint * DrawY); */ /* inline void UnMapScreen(screenint * DrawX, screenint * DrawY); */ bool m_bVisibleRegionValid; int m_iRenderCount; private: CDasherScreen *m_pScreen; // provides the graphics (text, lines, rectangles): CDasherInput *m_pInput; // Input device abstraction /// Renders the Dasher node structure virtual void RenderNodes(CDasherNode *pRoot, myint iRootMin, myint iRootMax, CExpansionPolicy &policy) = 0; /// Get the co-ordinates from the input device int GetInputCoordinates(int iN, myint * pCoordinates); bool m_bDemoMode; bool m_bGameMode; }; /// @} #endif /* #ifndef __DasherView_h_ */ diff --git a/Src/DasherCore/GameModule.cpp b/Src/DasherCore/GameModule.cpp index 20358f9..5d41f21 100644 --- a/Src/DasherCore/GameModule.cpp +++ b/Src/DasherCore/GameModule.cpp @@ -1,61 +1,67 @@ #include "GameModule.h" using namespace Dasher; void CGameModule::HandleEvent(Dasher::CEvent *pEvent) { switch(pEvent->m_iEventType) { case EV_EDIT: - { - g_pLogger->Log("Capturing an edit event"); + { CEditEvent* evt = static_cast<CEditEvent*>(pEvent); switch(evt->m_iEditType) { // Added a new character (Stepped one node forward) case 0: m_stCurrentStringPos++; //pLastTypedNode = StringToNode(evt->m_sText); break; // Removed a character (Stepped one node back) case 1: break; default: break; } break; } case EV_TEXTDRAW: { CTextDrawEvent *evt = static_cast<CTextDrawEvent*>(pEvent); - if(!m_sTargetString.substr(m_stCurrentStringPos+1, 1).compare(evt->m_sDisplayText)) { - evt->m_pDasherView->Screen2Dasher(evt->m_iX, evt->m_iY, m_iTargetX, m_iTargetY); + if(!m_sTargetString.substr(m_stCurrentStringPos+1, 1).compare(evt->m_sDisplayText) + && evt->m_iY < GetLongParameter(LP_OX)) { + evt->m_pDasherView->Screen2Dasher(evt->m_iX, evt->m_iY, m_iTargetX, m_iTargetY); } } break; default: break; } return; } bool CGameModule::DecorateView(CDasherView *pView) { - pView->DasherPolyarrow(&m_iTargetX, &m_iTargetY, 20, GetLongParameter(LP_LINE_WIDTH)*4, 135); + + //set up the points for the arrow through - starts at the crosshair, ends at the target letter + myint x[2] = {GetLongParameter(LP_OX), m_iTargetX}; + myint y[2] = {GetLongParameter(LP_OY), m_iTargetY}; + + pView->DasherPolyarrow(x, y, m_iArrowNumPoints, GetLongParameter(LP_LINE_WIDTH)*4, m_iArrowColor, m_dArrowSizeFactor); + return true; } //CDasherNode CGameModule::StringToNode(std::string sText) { // //} std::string CGameModule::GetTypedTarget() { return m_sTargetString.substr(0, m_stCurrentStringPos - 1); } std::string CGameModule::GetUntypedTarget() { return m_sTargetString.substr(m_stCurrentStringPos); } diff --git a/Src/DasherCore/GameModule.h b/Src/DasherCore/GameModule.h index 82bb623..3241565 100644 --- a/Src/DasherCore/GameModule.h +++ b/Src/DasherCore/GameModule.h @@ -1,115 +1,143 @@ // GameModule.h #ifndef GAME_MODULE_H #define GAME_MODULE_H #include <string> #include <cstring> using namespace std; #include "DasherView.h" #include "DasherModel.h" #include "DasherModule.h" #include "DasherNode.h" #include "DasherView.h" #include "DasherTypes.h" #include "DasherInterfaceBase.h" namespace Dasher { /** * This Dasher Module encapsulates all game mode logic. In game mode, users will be given * a target string to type as well as visual feedback for their progress and a helpful * arrow to guide them in the right path through the dasher model. * * This class handles logic and drawing code with respect to the above. */ class CGameModule : public CDasherModule { public: // I don't actually know what the type is supposed to be for this...it's not an input method or an input filter. // Maybe we should define a new one. I've labeled it 0 for now. - rgee - CGameModule(Dasher::CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CDasherInterfaceBase *pInterface, ModuleID_t iID, const char *szName) - : CDasherModule(pEventHandler, pSettingsStore, iID, 0, szName) - { - g_pLogger->Log("Inside game module constructor"); - m_pInterface = pInterface; + CGameModule(Dasher::CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, + CDasherInterfaceBase *pInterface, ModuleID_t iID, const char *szName) + : m_iArrowColor(135), + m_dArrowSizeFactor(0.1), + m_iArrowNumPoints(2), + CDasherModule(pEventHandler, pSettingsStore, iID, 0, szName) + { + m_pInterface = pInterface; + + //TODO REMOVE THIS!!! + m_sTargetString = "My name is julian."; + + m_stCurrentStringPos = 0; + //m_iArrowColor = 135; + //m_dArrowSizeFactor = 0.1; + //m_iArrowNumPoints = 2; + } virtual ~CGameModule() {}; /** * Gets the typed portion of the target string * @return The string that represents the current word(s) that have not been typed */ std::string GetTypedTarget(); /** * Gets the portion of the target string that has yet to be completed * @return The string that represents the current word(s) that have been typed */ std::string GetUntypedTarget(); bool DecorateView(CDasherView *pView); void SetDasherModel(CDasherModel *pModel) { m_pModel = pModel; } /** * Handle events from the event processing system * @param pEvent The event to be processed. */ virtual void HandleEvent(Dasher::CEvent *pEvent); private: /** * Searches for the dasher node under the current root that represents the desired string * @param text The string to search for * @return The node representing the string parameter */ //Dasher::CDasherNode StringToNode(std::string sText); /** * The last node the user typed. */ CDasherNode *pLastTypedNode; /** * The next node (character) the user must type. */ CDasherNode *pNextTargetNode; /** * The target string the user must type. */ std::string m_sTargetString; /** * The current position in the string. * Stored as a size_t to easily use substrings to determine what's been typed and what hasn't. */ size_t m_stCurrentStringPos; /** * The dasher model. */ CDasherModel *m_pModel; /** * The dasher interface. */ CDasherInterfaceBase *m_pInterface; /** * The target x coordinate for the arrow to point to. */ myint m_iTargetX; /** * The target y coordinate for the arrow to point to. */ myint m_iTargetY; + + /** + * The color (in Dasher colors) to make the guiding arrow. + */ + const int m_iArrowColor; + + /** + * The factor by which the size the hat on the guiding arrow + */ + const double m_dArrowSizeFactor; + + /** + * The number of points that the guiding arrow passes through + */ + const int m_iArrowNumPoints; + }; } #endif
rgee/HFOSS-Dasher
590d512bb7e6470240315ad27da06067dba3d0b1
Added ability to add listeners. Set up new version of listener queue system.
diff --git a/Src/DasherCore/Event.h b/Src/DasherCore/Event.h index e3303ce..221aebd 100644 --- a/Src/DasherCore/Event.h +++ b/Src/DasherCore/Event.h @@ -1,179 +1,181 @@ #ifndef __event_h__ #define __event_h__ // Classes representing different event types. #include <string> #include "DasherTypes.h" namespace Dasher { class CEvent; class CTextDrawEvent; class CParameterNotificationEvent; class CEditEvent; class CEditContextEvent; class CStartEvent; class CStopEvent; class CControlEvent; class CLockEvent; class CMessageEvent; class CCommandEvent; class CDasherView; } enum { EV_PARAM_NOTIFY = 1, EV_EDIT, EV_EDIT_CONTEXT, EV_START, EV_STOP, EV_CONTROL, EV_LOCK, EV_MESSAGE, EV_COMMAND, EV_TEXTDRAW }; +int iNUM_EVENTS = 10; + /// \ingroup Core /// @{ /// \defgroup Events Events generated by Dasher modules. /// @{ class Dasher::CEvent { public: int m_iEventType; }; class Dasher::CParameterNotificationEvent:public Dasher::CEvent { public: CParameterNotificationEvent(int iParameter) { m_iEventType = EV_PARAM_NOTIFY; m_iParameter = iParameter; }; int m_iParameter; }; class Dasher::CEditEvent:public Dasher::CEvent { public: CEditEvent(int iEditType, const std::string & sText, int iOffset) { m_iEventType = EV_EDIT; m_iEditType = iEditType; m_sText = sText; m_iOffset = iOffset; }; int m_iEditType; std::string m_sText; int m_iOffset; }; class Dasher::CEditContextEvent:public Dasher::CEvent { public: CEditContextEvent(int iOffset, int iLength) { m_iEventType = EV_EDIT_CONTEXT; m_iOffset = iOffset; m_iLength = iLength; }; int m_iOffset; int m_iLength; }; /** * An event that signals text has been drawn. Useful for determining its location * because that information is only available at draw time. */ class Dasher::CTextDrawEvent : public Dasher::CEvent { public: CTextDrawEvent(std::string sDisplayText, CDasherView *pView, screenint iX, screenint iY, int iSize) :m_sDisplayText(sDisplayText), m_pDasherView(pView), m_iX(iX), m_iY(iY), m_iSize(iSize) { m_iEventType = EV_TEXTDRAW; }; /** * The text that has been drawn. */ std::string m_sDisplayText; /** * The dasher view that emitted this event. */ CDasherView* m_pDasherView; /** * The X position (in screen coordinates) of the center of the box surrounding the text. */ screenint m_iX; /** * The Y position (in screen coordinates) of the center of the box surrounding the text. */ screenint m_iY; /** * The size of the text. Useful for determining the boundaries of the text "box" */ int m_iSize; }; class Dasher::CStartEvent:public Dasher::CEvent { public: CStartEvent() { m_iEventType = EV_START; }; }; class Dasher::CStopEvent:public Dasher::CEvent { public: CStopEvent() { m_iEventType = EV_STOP; }; }; class Dasher::CControlEvent:public Dasher::CEvent { public: CControlEvent(int iID) { m_iEventType = EV_CONTROL; m_iID = iID; }; int m_iID; }; class Dasher::CLockEvent : public Dasher::CEvent { public: CLockEvent(const std::string &strMessage, bool bLock, int iPercent) { m_iEventType = EV_LOCK; m_strMessage = strMessage; m_bLock = bLock; m_iPercent = iPercent; }; std::string m_strMessage; bool m_bLock; int m_iPercent; }; class Dasher::CMessageEvent : public Dasher::CEvent { public: CMessageEvent(const std::string &strMessage, int iID, int iType) { m_iEventType = EV_MESSAGE; m_strMessage = strMessage; m_iID = iID; m_iType = iType; }; std::string m_strMessage; int m_iID; int m_iType; }; class Dasher::CCommandEvent : public Dasher::CEvent { public: CCommandEvent(const std::string &strCommand) { m_iEventType = EV_COMMAND; m_strCommand = strCommand; }; std::string m_strCommand; }; /// @} /// @} #endif diff --git a/Src/DasherCore/EventHandler.cpp b/Src/DasherCore/EventHandler.cpp index f3f4a04..a95740b 100644 --- a/Src/DasherCore/EventHandler.cpp +++ b/Src/DasherCore/EventHandler.cpp @@ -1,90 +1,131 @@ #include "../Common/Common.h" #include "EventHandler.h" #include "DasherComponent.h" #include "DasherInterfaceBase.h" #include "Event.h" #include <algorithm> #include <iostream> using namespace Dasher; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif void CEventHandler::InsertEvent(CEvent *pEvent) { - - // We may end up here recursively, so keep track of how far down we - // are, and only permit new handlers to be registered after all - // messages are processed. - - // An alternative approach would be a message queue - this might actually be a bit more sensible - ++m_iInHandler; - - // Loop through components and notify them of the event - for(std::vector < CDasherComponent * >::iterator iCurrent(m_vListeners.begin()); iCurrent != m_vListeners.end(); ++iCurrent) { - (*iCurrent)->HandleEvent(pEvent); - } - - // Call external handler last, to make sure that internal components are fully up to date before external events happen - - m_pInterface->InterfaceEventHandler(pEvent); - - m_pInterface->ExternalEventHandler(pEvent); - - --m_iInHandler; - - if(m_iInHandler == 0) { - for(std::vector < CDasherComponent * >::iterator iCurrent(m_vListenerQueue.begin()); iCurrent != m_vListenerQueue.end(); ++iCurrent) - m_vListeners.push_back(*iCurrent); - m_vListenerQueue.clear(); - } + ++m_iInHandler; + + for(std::vector<CdasherComponent*>::const_iterator it = m_vSpecificListeners[pEvent->m_iEventType].begin(); + it != m_vSpecificListeners[pEvent->m_iEventType].end(); + ++it) + { + (*it)->HandleEvent(pEvent); + } + + m_pInterface->InterfaceEventHandler(pEvent); + + m_pInterface->ExternalEventHandler(pEvent); + + --m_iInHandler; + + if(m_iInHandler == 0) { + + } + + +// +// // We may end up here recursively, so keep track of how far down we +// // are, and only permit new handlers to be registered after all +// // messages are processed. +// +// // An alternative approach would be a message queue - this might actually be a bit more sensible +// ++m_iInHandler; +// +// // Loop through components and notify them of the event +// for(std::vector < CDasherComponent * >::iterator iCurrent(m_vListeners.begin()); iCurrent != m_vListeners.end(); ++iCurrent) { +// (*iCurrent)->HandleEvent(pEvent); +// } +// +// // Call external handler last, to make sure that internal components are fully up to date before external events happen +// +// m_pInterface->InterfaceEventHandler(pEvent); +// +// m_pInterface->ExternalEventHandler(pEvent); +// +// --m_iInHandler; +// +// if(m_iInHandler == 0) { +// for(std::vector < CDasherComponent * >::iterator iCurrent(m_vListenerQueue.begin()); iCurrent != m_vListenerQueue.end(); ++iCurrent) +// m_vListeners.push_back(*iCurrent); +// m_vListenerQueue.clear(); +// } } void CEventHandler::RegisterListener(CDasherComponent *pListener) { - - if((std::find(m_vListeners.begin(), m_vListeners.end(), pListener) == m_vListeners.end()) && - (std::find(m_vListenerQueue.begin(), m_vListenerQueue.end(), pListener) == m_vListenerQueue.end())) { - if(!m_iInHandler > 0) - m_vListeners.push_back(pListener); - else - m_vListenerQueue.push_back(pListener); - } - else { - // Can't add the same listener twice - } + if((std::find(m_vSpecificListeners.begin(), m_vSpecificListeneres.end(), pListener) == m_vListeners.end()) && + (std::find(m_vSpecificListeners.begin(), m_vListenerQueue.end(), pListener) == m_vSpecificListenerQueue.end())) { + if(!m_viInHandler > 0) + for(std::vector<std::vector<CDasherComponent*>>::const_iterator it = m_vSpecificListeners.begin(); it != m_vSpecificListeners.end(); ++it) { + it.push_back(pListener); + } + else + for(std::vector<CDasherComponent*>>::cosnt_iterator it = m_vSpecificListenerQueue.begin(); it != m_vSpecificListenerQueue.end(); ++it) { + it.push_back(pListener); + } + } + else { + // Can't add the same listener twice + } +// ===OLD EVENT CODE== +// if((std::find(m_vListeners.begin(), m_vListeners.end(), pListener) == m_vListeners.end()) && +// (std::find(m_vListenerQueue.begin(), m_vListenerQueue.end(), pListener) == m_vListenerQueue.end())) { +// if(!m_iInHandler > 0) +// m_vListeners.push_back(pListener); +// else +// m_vListenerQueue.push_back(pListener); +// } +// else { +// // Can't add the same listener twice +// } } void CEventHandler::RegisterListener(CDasherComponent *pListener, int iEventType) { - if(iEventType >= m_vSpecificListeners.size()) { - m_vSpecificListeners.push_back(std::vector< Dasher::CDasherComponent * >(pListener)); - } - else { - m_vSpecificListeners[iEventType].push_back(pListener); - } + if((std::find(m_vSpecificListeners.begin(), m_vSpecificListeneres.end(), pListener) == m_vListeners.end()) && + (std::find(m_vSpecificListeners.begin(), m_vListenerQueue.end(), pListener) == m_vSpecificListenerQueue.end())) { + if(!m_vInHandler > 0) + m_vSpecificListener[iEventType].push_back(pListener); + else + m_vSpecificListenerQueue[iEventType].push_back(pListener); + } } +void CEventHandler::UnregisterListener(CDasherComponent *pListener, int iEventType) { + for(std::vector<CDasherComponent*>::const_iterator it = m_vSpecificListeners[iEventType].begin(); it != m_vSpecificListeners[iEventType].end(); ++it) { + if( (*it) == pListener) + m_vSpecificListeners[iEventType].erase(it); + } +} void CEventHandler::UnregisterListener(CDasherComponent *pListener) { std::vector < CDasherComponent * >::iterator iFound; iFound = std::find(m_vListeners.begin(), m_vListeners.end(), pListener); if(iFound != m_vListeners.end()) m_vListeners.erase(iFound); iFound = std::find(m_vListenerQueue.begin(), m_vListenerQueue.end(), pListener); if(iFound != m_vListenerQueue.end()) m_vListenerQueue.erase(iFound); } diff --git a/Src/DasherCore/EventHandler.h b/Src/DasherCore/EventHandler.h index 6c9edfe..3e45753 100644 --- a/Src/DasherCore/EventHandler.h +++ b/Src/DasherCore/EventHandler.h @@ -1,64 +1,87 @@ #ifndef __eventhandler_h__ #define __eventhandler_h__ #include <vector> namespace Dasher { class CEventHandler; class CDasherComponent; class CDasherInterfaceBase; class CEvent; } /// \ingroup Core /// @{ class Dasher::CEventHandler { public: CEventHandler(Dasher::CDasherInterfaceBase * pInterface):m_pInterface(pInterface) { m_iInHandler = 0; + + // Initialize the event listener container (and queue) so we can add elements without + // checking if the sub-vectors actually exist or not. + for(int i = 0; i < iNUM_EVENTS; i++) { + m_vSpecificListeners.push_back(new Vector<CDasherComponent*>()); + } + + for(int i = 0; it < iNUM_EVENTS; i++) { + m_vSpecificListenerQueue.push_back(new Vector<CDasherComponent*>()); + } }; ~CEventHandler() { }; // Insert an event, which will be propagated to all listeners. void InsertEvent(Dasher::CEvent * pEvent); // (Un)register a listener with the event handler. void RegisterListener(Dasher::CDasherComponent * pListener); /** * Register a listener to listen for specific events. * @param pListener A pointer to the dasher component that will listen for events * @param iEventType An integer defined in the event type enumeration in Event.h + * that represents the event to which you'd like to subscribe. */ void RegisterListener(Dasher::CDasherComponent * pListener, int iEventType); + + /** + * Unregister a listener from a specific event. + * @param pListener A pointer tot he dasher component to be unregistered + * @param iEventType An integer defined in the event type enumeration in Event.h + * that represents the event to which you'd like to unsubscribe. + */ + void UnregisterListener(Dasher::CDashercomponent * pListener, int iEventType); void UnregisterListener(Dasher::CDasherComponent * pListener); protected: // Vector containing all currently registered listeners. std::vector < Dasher::CDasherComponent * >m_vListeners; std::vector < Dasher::CDasherComponent * >m_vListenerQueue; + + /** * A 2-dimensional vector of listeners where each sub-vector represents * the listener for a specific event type (Defined in the event type enumeration * in Event.h. To access a vector for a specific event type, index into the top-level * vector using the event type as an index. */ std::vector < std::vector < Dasher::CDasherComponent * > > m_vSpecificListeners; + std::vector < std::vector < Dasher::CDasherComponent * > > m_vSpecificListenerQueue; + int m_iInHandler; Dasher::CDasherInterfaceBase * m_pInterface; }; /// @} #endif
rgee/HFOSS-Dasher
13143e0880d064dd755c5527cc44555e0629c603
wrote function to register component for a specific event. Eventhandler now maintains a vector of vectors of listeners for each event. Notification not functional yet.
diff --git a/Src/DasherCore/EventHandler.cpp b/Src/DasherCore/EventHandler.cpp index 2b9cafb..f3f4a04 100644 --- a/Src/DasherCore/EventHandler.cpp +++ b/Src/DasherCore/EventHandler.cpp @@ -1,79 +1,90 @@ #include "../Common/Common.h" #include "EventHandler.h" #include "DasherComponent.h" #include "DasherInterfaceBase.h" +#include "Event.h" #include <algorithm> #include <iostream> using namespace Dasher; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif void CEventHandler::InsertEvent(CEvent *pEvent) { // We may end up here recursively, so keep track of how far down we // are, and only permit new handlers to be registered after all // messages are processed. // An alternative approach would be a message queue - this might actually be a bit more sensible ++m_iInHandler; // Loop through components and notify them of the event for(std::vector < CDasherComponent * >::iterator iCurrent(m_vListeners.begin()); iCurrent != m_vListeners.end(); ++iCurrent) { (*iCurrent)->HandleEvent(pEvent); } // Call external handler last, to make sure that internal components are fully up to date before external events happen m_pInterface->InterfaceEventHandler(pEvent); m_pInterface->ExternalEventHandler(pEvent); --m_iInHandler; if(m_iInHandler == 0) { for(std::vector < CDasherComponent * >::iterator iCurrent(m_vListenerQueue.begin()); iCurrent != m_vListenerQueue.end(); ++iCurrent) m_vListeners.push_back(*iCurrent); m_vListenerQueue.clear(); } } void CEventHandler::RegisterListener(CDasherComponent *pListener) { if((std::find(m_vListeners.begin(), m_vListeners.end(), pListener) == m_vListeners.end()) && (std::find(m_vListenerQueue.begin(), m_vListenerQueue.end(), pListener) == m_vListenerQueue.end())) { if(!m_iInHandler > 0) m_vListeners.push_back(pListener); else m_vListenerQueue.push_back(pListener); } else { // Can't add the same listener twice } } +void CEventHandler::RegisterListener(CDasherComponent *pListener, int iEventType) { + if(iEventType >= m_vSpecificListeners.size()) { + m_vSpecificListeners.push_back(std::vector< Dasher::CDasherComponent * >(pListener)); + } + else { + m_vSpecificListeners[iEventType].push_back(pListener); + } +} + + void CEventHandler::UnregisterListener(CDasherComponent *pListener) { std::vector < CDasherComponent * >::iterator iFound; iFound = std::find(m_vListeners.begin(), m_vListeners.end(), pListener); if(iFound != m_vListeners.end()) m_vListeners.erase(iFound); iFound = std::find(m_vListenerQueue.begin(), m_vListenerQueue.end(), pListener); if(iFound != m_vListenerQueue.end()) m_vListenerQueue.erase(iFound); } diff --git a/Src/DasherCore/EventHandler.h b/Src/DasherCore/EventHandler.h index 4bb79b4..6c9edfe 100644 --- a/Src/DasherCore/EventHandler.h +++ b/Src/DasherCore/EventHandler.h @@ -1,49 +1,64 @@ #ifndef __eventhandler_h__ #define __eventhandler_h__ #include <vector> namespace Dasher { class CEventHandler; class CDasherComponent; class CDasherInterfaceBase; class CEvent; } /// \ingroup Core /// @{ class Dasher::CEventHandler { public: CEventHandler(Dasher::CDasherInterfaceBase * pInterface):m_pInterface(pInterface) { m_iInHandler = 0; }; ~CEventHandler() { }; // Insert an event, which will be propagated to all listeners. void InsertEvent(Dasher::CEvent * pEvent); // (Un)register a listener with the event handler. void RegisterListener(Dasher::CDasherComponent * pListener); + + /** + * Register a listener to listen for specific events. + * @param pListener A pointer to the dasher component that will listen for events + * @param iEventType An integer defined in the event type enumeration in Event.h + */ + void RegisterListener(Dasher::CDasherComponent * pListener, int iEventType); void UnregisterListener(Dasher::CDasherComponent * pListener); protected: // Vector containing all currently registered listeners. std::vector < Dasher::CDasherComponent * >m_vListeners; std::vector < Dasher::CDasherComponent * >m_vListenerQueue; + /** + * A 2-dimensional vector of listeners where each sub-vector represents + * the listener for a specific event type (Defined in the event type enumeration + * in Event.h. To access a vector for a specific event type, index into the top-level + * vector using the event type as an index. + */ + std::vector < std::vector < Dasher::CDasherComponent * > > m_vSpecificListeners; + int m_iInHandler; Dasher::CDasherInterfaceBase * m_pInterface; }; /// @} #endif
rgee/HFOSS-Dasher
3009eae517c045e1a9724688681c222350abf8c6
Forgot to assign Text draw events their proper event type. Fixed that.
diff --git a/Src/DasherCore/Event.h b/Src/DasherCore/Event.h index 9af0f4a..e3303ce 100644 --- a/Src/DasherCore/Event.h +++ b/Src/DasherCore/Event.h @@ -1,177 +1,179 @@ #ifndef __event_h__ #define __event_h__ // Classes representing different event types. #include <string> #include "DasherTypes.h" namespace Dasher { class CEvent; class CTextDrawEvent; class CParameterNotificationEvent; class CEditEvent; class CEditContextEvent; class CStartEvent; class CStopEvent; class CControlEvent; class CLockEvent; class CMessageEvent; class CCommandEvent; class CDasherView; } enum { EV_PARAM_NOTIFY = 1, EV_EDIT, EV_EDIT_CONTEXT, EV_START, EV_STOP, EV_CONTROL, EV_LOCK, EV_MESSAGE, EV_COMMAND, EV_TEXTDRAW }; /// \ingroup Core /// @{ /// \defgroup Events Events generated by Dasher modules. /// @{ class Dasher::CEvent { public: int m_iEventType; }; class Dasher::CParameterNotificationEvent:public Dasher::CEvent { public: CParameterNotificationEvent(int iParameter) { m_iEventType = EV_PARAM_NOTIFY; m_iParameter = iParameter; }; int m_iParameter; }; class Dasher::CEditEvent:public Dasher::CEvent { public: CEditEvent(int iEditType, const std::string & sText, int iOffset) { m_iEventType = EV_EDIT; m_iEditType = iEditType; m_sText = sText; m_iOffset = iOffset; }; int m_iEditType; std::string m_sText; int m_iOffset; }; class Dasher::CEditContextEvent:public Dasher::CEvent { public: CEditContextEvent(int iOffset, int iLength) { m_iEventType = EV_EDIT_CONTEXT; m_iOffset = iOffset; m_iLength = iLength; }; int m_iOffset; int m_iLength; }; /** * An event that signals text has been drawn. Useful for determining its location * because that information is only available at draw time. */ class Dasher::CTextDrawEvent : public Dasher::CEvent { public: CTextDrawEvent(std::string sDisplayText, CDasherView *pView, screenint iX, screenint iY, int iSize) :m_sDisplayText(sDisplayText), m_pDasherView(pView), m_iX(iX), m_iY(iY), m_iSize(iSize) - { }; + { + m_iEventType = EV_TEXTDRAW; + }; /** * The text that has been drawn. */ std::string m_sDisplayText; /** * The dasher view that emitted this event. */ CDasherView* m_pDasherView; /** * The X position (in screen coordinates) of the center of the box surrounding the text. */ screenint m_iX; /** * The Y position (in screen coordinates) of the center of the box surrounding the text. */ screenint m_iY; /** * The size of the text. Useful for determining the boundaries of the text "box" */ int m_iSize; }; class Dasher::CStartEvent:public Dasher::CEvent { public: CStartEvent() { m_iEventType = EV_START; }; }; class Dasher::CStopEvent:public Dasher::CEvent { public: CStopEvent() { m_iEventType = EV_STOP; }; }; class Dasher::CControlEvent:public Dasher::CEvent { public: CControlEvent(int iID) { m_iEventType = EV_CONTROL; m_iID = iID; }; int m_iID; }; class Dasher::CLockEvent : public Dasher::CEvent { public: CLockEvent(const std::string &strMessage, bool bLock, int iPercent) { m_iEventType = EV_LOCK; m_strMessage = strMessage; m_bLock = bLock; m_iPercent = iPercent; }; std::string m_strMessage; bool m_bLock; int m_iPercent; }; class Dasher::CMessageEvent : public Dasher::CEvent { public: CMessageEvent(const std::string &strMessage, int iID, int iType) { m_iEventType = EV_MESSAGE; m_strMessage = strMessage; m_iID = iID; m_iType = iType; }; std::string m_strMessage; int m_iID; int m_iType; }; class Dasher::CCommandEvent : public Dasher::CEvent { public: CCommandEvent(const std::string &strCommand) { m_iEventType = EV_COMMAND; m_strCommand = strCommand; }; std::string m_strCommand; }; /// @} /// @} #endif
rgee/HFOSS-Dasher
e159abda0d5219072f1eb7d10c6f77a983777989
Fixed more bugs blocking compilation
diff --git a/Src/DasherCore/DasherViewSquare.cpp b/Src/DasherCore/DasherViewSquare.cpp index d244d58..c89cb47 100644 --- a/Src/DasherCore/DasherViewSquare.cpp +++ b/Src/DasherCore/DasherViewSquare.cpp @@ -1,729 +1,728 @@ // DasherViewSquare.cpp // // Copyright (c) 2008 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" #ifdef _WIN32 #include "..\Win32\Common\WinCommon.h" #endif //#include "DasherGameMode.h" #include "DasherViewSquare.h" #include "DasherModel.h" #include "DasherView.h" #include "DasherTypes.h" #include "Event.h" #include "EventHandler.h" #include <algorithm> #include <iostream> #include <limits> #include <stdlib.h> using namespace Dasher; using namespace Opts; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG_MEMLEAKS #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif // FIXME - quite a lot of the code here probably should be moved to // the parent class (DasherView). I think we really should make the // parent class less general - we're probably not going to implement // anything which uses radically different co-ordinate transforms, and // we can always override if necessary. // FIXME - duplicated 'mode' code throught - needs to be fixed (actually, mode related stuff, Input2Dasher etc should probably be at least partially in some other class) CDasherViewSquare::CDasherViewSquare(CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CDasherScreen *DasherScreen) : CDasherView(pEventHandler, pSettingsStore, DasherScreen), m_Y1(4), m_Y2(0.95 * GetLongParameter(LP_MAX_Y)), m_Y3(0.05 * GetLongParameter((LP_MAX_Y))) { // TODO - AutoOffset should be part of the eyetracker input filter // Make sure that the auto calibration is set to zero berfore we start // m_yAutoOffset = 0; ChangeScreen(DasherScreen); //Note, nonlinearity parameters set in SetScaleFactor m_bVisibleRegionValid = false; } CDasherViewSquare::~CDasherViewSquare() {} void CDasherViewSquare::HandleEvent(Dasher::CEvent *pEvent) { // Let the parent class do its stuff CDasherView::HandleEvent(pEvent); // And then interpret events for ourself if(pEvent->m_iEventType == 1) { Dasher::CParameterNotificationEvent * pEvt(static_cast < Dasher::CParameterNotificationEvent * >(pEvent)); switch (pEvt->m_iParameter) { case LP_REAL_ORIENTATION: case LP_MARGIN_WIDTH: case BP_NONLINEAR_Y: case LP_NONLINEAR_X: m_bVisibleRegionValid = false; SetScaleFactor(); break; default: break; } } } /// Draw text specified in Dasher co-ordinates. The position is /// specified as two co-ordinates, intended to the be the corners of /// the leading edge of the containing box. void CDasherViewSquare::DasherDrawText(myint iAnchorX1, myint iAnchorY1, myint iAnchorX2, myint iAnchorY2, const std::string &sDisplayText, int &mostleft, bool bShove) { // Don't draw text which will overlap with text in an ancestor. if(iAnchorX1 > mostleft) iAnchorX1 = mostleft; if(iAnchorX2 > mostleft) iAnchorX2 = mostleft; myint iDasherMinX; myint iDasherMinY; myint iDasherMaxX; myint iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); iAnchorY1 = std::min( iDasherMaxY, std::max( iDasherMinY, iAnchorY1 ) ); iAnchorY2 = std::min( iDasherMaxY, std::max( iDasherMinY, iAnchorY2 ) ); screenint iScreenAnchorX1; screenint iScreenAnchorY1; screenint iScreenAnchorX2; screenint iScreenAnchorY2; // FIXME - Truncate here before converting - otherwise we risk integer overflow in screen coordinates Dasher2Screen(iAnchorX1, iAnchorY1, iScreenAnchorX1, iScreenAnchorY1); Dasher2Screen(iAnchorX2, iAnchorY2, iScreenAnchorX2, iScreenAnchorY2); // Truncate the ends of the anchor line to be on the screen - this // prevents us from loosing characters off the top and bottom of the // screen // TruncateToScreen(iScreenAnchorX1, iScreenAnchorY1); // TruncateToScreen(iScreenAnchorX2, iScreenAnchorY2); // Actual anchor point is the midpoint of the anchor line screenint iScreenAnchorX((iScreenAnchorX1 + iScreenAnchorX2) / 2); screenint iScreenAnchorY((iScreenAnchorY1 + iScreenAnchorY2) / 2); // Compute font size based on position int Size = GetLongParameter( LP_DASHER_FONTSIZE ); // FIXME - this could be much more elegant, and probably needs a // rethink anyway - behvaiour here is too dependent on screen size screenint iLeftTimesFontSize = ((myint)GetLongParameter(LP_MAX_Y) - (iAnchorX1 + iAnchorX2)/ 2 )*Size; if(iLeftTimesFontSize < (myint)GetLongParameter(LP_MAX_Y) * 19/ 20) Size *= 20; else if(iLeftTimesFontSize < (myint)GetLongParameter(LP_MAX_Y) * 159 / 160) Size *= 14; else Size *= 11; screenint TextWidth, TextHeight; Screen()->TextSize(sDisplayText, &TextWidth, &TextHeight, Size); // Poistion of text box relative to anchor depends on orientation screenint newleft2 = 0; screenint newtop2 = 0; screenint newright2 = 0; screenint newbottom2 = 0; switch (Dasher::Opts::ScreenOrientations(GetLongParameter(LP_REAL_ORIENTATION))) { case (Dasher::Opts::LeftToRight): newleft2 = iScreenAnchorX; newtop2 = iScreenAnchorY - TextHeight / 2; newright2 = iScreenAnchorX + TextWidth; newbottom2 = iScreenAnchorY + TextHeight / 2; break; case (Dasher::Opts::RightToLeft): newleft2 = iScreenAnchorX - TextWidth; newtop2 = iScreenAnchorY - TextHeight / 2; newright2 = iScreenAnchorX; newbottom2 = iScreenAnchorY + TextHeight / 2; break; case (Dasher::Opts::TopToBottom): newleft2 = iScreenAnchorX - TextWidth / 2; newtop2 = iScreenAnchorY; newright2 = iScreenAnchorX + TextWidth / 2; newbottom2 = iScreenAnchorY + TextHeight; break; case (Dasher::Opts::BottomToTop): newleft2 = iScreenAnchorX - TextWidth / 2; newtop2 = iScreenAnchorY - TextHeight; newright2 = iScreenAnchorX + TextWidth / 2; newbottom2 = iScreenAnchorY; break; default: break; } // Update the value of mostleft to take into account the new text if(bShove) { myint iDasherNewLeft; myint iDasherNewTop; myint iDasherNewRight; myint iDasherNewBottom; Screen2Dasher(newleft2, newtop2, iDasherNewLeft, iDasherNewTop); Screen2Dasher(newright2, newbottom2, iDasherNewRight, iDasherNewBottom); mostleft = std::min(iDasherNewRight, iDasherNewLeft); } // Tell other listeners that text has been drawn and provide some information // about the draw call. - m_pEventHandler->InsertEvent(new CTextDrawEvent(sDisplayText, newleft2, newtop2, Size)); - m_pEventHandler->InsertEvent(new CTextDrawEvent(sDisplaytext,this, newleft2, newtop2, Size)); + m_pEventHandler->InsertEvent(new CTextDrawEvent(sDisplayText,this, newleft2, newtop2, Size)); // Actually draw the text. We use DelayDrawText as the text should // be overlayed once all of the boxes have been drawn. m_DelayDraw.DelayDrawText(sDisplayText, newleft2, newtop2, Size); } void CDasherViewSquare::RenderNodes(CDasherNode *pRoot, myint iRootMin, myint iRootMax, CExpansionPolicy &policy) { DASHER_ASSERT(pRoot != 0); myint iDasherMinX; myint iDasherMinY; myint iDasherMaxX; myint iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); // screenint iScreenLeft; screenint iScreenTop; screenint iScreenRight; screenint iScreenBottom; Dasher2Screen(iRootMax-iRootMin, iRootMin, iScreenLeft, iScreenTop); Dasher2Screen(0, iRootMax, iScreenRight, iScreenBottom); //ifiScreenTop < 0) // iScreenTop = 0; //if(iScreenLeft < 0) // iScreenLeft=0; //// TODO: Should these be right on the boundary? //if(iScreenBottom > Screen()->GetHeight()) // iScreenBottom=Screen()->GetHeight(); //if(iScreenRight > Screen()->GetWidth()) // iScreenRight=Screen()->GetWidth(); // Blank the region around the root node: if(iRootMin > iDasherMinY) DasherDrawRectangle(iDasherMaxX, iDasherMinY, iDasherMinX, iRootMin, 0, -1, Nodes1, 0); //if(iScreenTop > 0) // Screen()->DrawRectangle(0, 0, Screen()->GetWidth(), iScreenTop, 0, -1, Nodes1, false, true, 1); if(iRootMax < iDasherMaxY) DasherDrawRectangle(iDasherMaxX, iRootMax, iDasherMinX, iDasherMaxY, 0, -1, Nodes1, 0); //if(iScreenBottom <= Screen()->GetHeight()) // Screen()->DrawRectangle(0, iScreenBottom, Screen()->GetWidth(), Screen()->GetHeight(), 0, -1, Nodes1, false, true, 1); DasherDrawRectangle(0, iDasherMinY, iDasherMinX, iDasherMaxY, 0, -1, Nodes1, 0); // Screen()->DrawRectangle(iScreenRight, std::max(0, (int)iScreenTop), // Screen()->GetWidth(), std::min(Screen()->GetHeight(), (int)iScreenBottom), // 0, -1, Nodes1, false, true, 1); // Render the root node (and children) RecursiveRender(pRoot, iRootMin, iRootMax, iDasherMaxX, policy, std::numeric_limits<double>::infinity(), iDasherMaxX,0,0); // Labels are drawn in a second parse to get the overlapping right m_DelayDraw.Draw(Screen()); // Finally decorate the view Crosshair((myint)GetLongParameter(LP_OX)); } //min size in *Dasher co-ordinates* to consider rendering a node #define QUICK_REJECT 50 //min size in *screen* (pixel) co-ordinates to render a node #define MIN_SIZE 2 bool CDasherViewSquare::CheckRender(CDasherNode *pRender, myint y1, myint y2, int mostleft, CExpansionPolicy &policy, double dMaxCost, myint parent_width, int parent_color, int iDepth) { if (y2-y1 >= QUICK_REJECT) { myint iDasherMinX; myint iDasherMinY; myint iDasherMaxX; myint iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); if (y1 <= iDasherMaxY && y2 >= iDasherMinY) { screenint iScreenX1; screenint iScreenY1; screenint iScreenX2; screenint iScreenY2; Dasher2Screen(0, std::max(y1, iDasherMinY), iScreenX1, iScreenY1); Dasher2Screen(0, std::min(y2, iDasherMaxY), iScreenX2, iScreenY2); Cint32 iHeight = std::max(myint(iScreenY2 - iScreenY1),myint( 0)); if (iHeight >= MIN_SIZE) { //node should be rendered! RecursiveRender(pRender, y1, y2, mostleft, policy, dMaxCost, parent_width, parent_color, iDepth); return true; } } } // We get here if the node is too small to render or is off-screen. // So, collapse it immediately. // // In game mode, we get here if the child is too small to draw, but we need the // coordinates - if this is the case then we shouldn't delete any children. // // TODO: Should probably render the parent segment here anyway (or // in the above) if(!pRender->GetFlag(NF_GAME)) pRender->Delete_children(); return false; } void CDasherViewSquare::RecursiveRender(CDasherNode *pRender, myint y1, myint y2, int mostleft, CExpansionPolicy &policy, double dMaxCost, myint parent_width,int parent_color, int iDepth) { DASHER_ASSERT_VALIDPTR_RW(pRender); // if(iDepth == 2) // std::cout << pRender->GetDisplayInfo()->strDisplayText << std::endl; // TODO: We need an overhall of the node creation/deletion logic - // make sure that we only maintain the minimum number of nodes which // are actually needed. This is especially true at the moment in // Game mode, which feels very sluggish. Node creation also feels // slower in Windows than Linux, especially if many nodes are // created at once (eg untrained Hiragana) ++m_iRenderCount; // myint trange = y2 - y1; // Attempt to draw the region to the left of this node inside its parent. // if(iDepth == 2) { // std::cout << "y1: " << y1 << " y2: " << y2 << std::endl; // Set the NF_SUPER flag if this node entirely frames the visual // area. // TODO: too slow? // TODO: use flags more rather than delete/reparent lists myint iDasherMinX; myint iDasherMinY; myint iDasherMaxX; myint iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); DasherDrawRectangle(std::min(parent_width,iDasherMaxX), std::max(y1,iDasherMinY), std::min(y2-y1,iDasherMaxX), std::min(y2,iDasherMaxY), parent_color, -1, Nodes1, 0); const std::string &sDisplayText(pRender->getDisplayText()); if( sDisplayText.size() > 0 ) { DasherDrawText(y2-y1, y1, y2-y1, y2, sDisplayText, mostleft, pRender->bShove()); } pRender->SetFlag(NF_SUPER, !IsSpaceAroundNode(y1,y2)); // If there are no children then we still need to render the parent if(pRender->ChildCount() == 0) { DasherDrawRectangle(std::min(y2-y1,iDasherMaxX), std::min(y2,iDasherMaxY),0, std::max(y1,iDasherMinY), pRender->getColour(), -1, Nodes1, 0); //also allow it to be expanded, it's big enough. policy.pushNode(pRender, y1, y2, true, dMaxCost); return; } //Node has children. It can therefore be collapsed...however, // we don't allow a node covering the crosshair to be collapsed // (at best this'll mean there's nowhere useful to go forwards; // at worst, all kinds of crashes trying to do text output!) if (!pRender->GetFlag(NF_GAME) && !pRender->GetFlag(NF_SEEN)) dMaxCost = policy.pushNode(pRender, y1, y2, false, dMaxCost); // Render children int norm = (myint)GetLongParameter(LP_NORMALIZATION); myint lasty=y1; int id=-1; // int lower=-1,upper=-1; myint temp_parentwidth=y2-y1; int temp_parentcolor = pRender->getColour(); const myint Range(y2 - y1); if (CDasherNode *pChild = pRender->onlyChildRendered) { //if child still covers screen, render _just_ it and return myint newy1 = y1 + (Range * (myint)pChild->Lbnd()) / (myint)norm; myint newy2 = y1 + (Range * (myint)pChild->Hbnd()) / (myint)norm; if (newy1 < iDasherMinY && newy2 > iDasherMaxY) { //still covers entire screen. Parent should too... DASHER_ASSERT(dMaxCost == std::numeric_limits<double>::infinity()); //don't inc iDepth, meaningless when covers the screen RecursiveRender(pChild, newy1, newy2, mostleft, policy, dMaxCost, temp_parentwidth, temp_parentcolor, iDepth); //leave pRender->onlyChildRendered set, so remaining children are skipped } else pRender->onlyChildRendered = NULL; } if (!pRender->onlyChildRendered) { //render all children... for(CDasherNode::ChildMap::const_iterator i = pRender->GetChildren().begin(); i != pRender->GetChildren().end(); i++) { id++; CDasherNode *pChild = *i; myint newy1 = y1 + (Range * (myint)pChild->Lbnd()) / (myint)norm;/// norm and lbnd are simple ints myint newy2 = y1 + (Range * (myint)pChild->Hbnd()) / (myint)norm; if (newy1 < iDasherMinY && newy2 > iDasherMaxY) { DASHER_ASSERT(dMaxCost == std::numeric_limits<double>::infinity()); pRender->onlyChildRendered = pChild; RecursiveRender(pChild, newy1, newy2, mostleft, policy, dMaxCost, temp_parentwidth, temp_parentcolor, iDepth); //ensure we don't blank over this child in "finishing off" the parent (!) lasty=newy2; break; //no need to render any more children! } if (CheckRender(pChild, newy1, newy2, mostleft, policy, dMaxCost, temp_parentwidth, temp_parentcolor, iDepth+1)) { if (lasty<newy1) { //if child has been drawn then the interval between him and the //last drawn child should be drawn too. //std::cout << "Fill in: " << lasty << " " << newy1 << std::endl; RenderNodePartFast(temp_parentcolor, lasty, newy1, mostleft, pRender->getDisplayText(), pRender->bShove(), temp_parentwidth); } lasty = newy2; } } // Finish off the drawing process // if(iDepth == 1) { // Theres a chance that we haven't yet filled the entire parent, so finish things off if necessary. if(lasty<y2) { RenderNodePartFast(temp_parentcolor, lasty, y2, mostleft, pRender->getDisplayText(), pRender->bShove(), temp_parentwidth); } } // Draw the outline if(pRender->getColour() != -1) {//-1 = invisible RenderNodeOutlineFast(pRender->getColour(), y1, y2, mostleft, pRender->getDisplayText(), pRender->bShove()); } // } } bool CDasherViewSquare::IsSpaceAroundNode(myint y1, myint y2) { myint iDasherMinX; myint iDasherMinY; myint iDasherMaxX; myint iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); return ((y2 - y1) < iDasherMaxX) || (y1 > iDasherMinY) || (y2 < iDasherMaxY); } // Draw the outline of a node int CDasherViewSquare::RenderNodeOutlineFast(const int Color, myint y1, myint y2, int &mostleft, const std::string &sDisplayText, bool bShove) { // Commenting because click mode occasionally fails this assert. // I don't know why. -- cjb. if (!(y2 >= y1)) { return 1; } // TODO - Get sensible limits here (to allow for non-linearities) myint iDasherMinX; myint iDasherMinY; myint iDasherMaxX; myint iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); screenint iScreenX1; screenint iScreenY1; screenint iScreenX2; screenint iScreenY2; Dasher2Screen(0, std::max(y1, iDasherMinY), iScreenX1, iScreenY1); Dasher2Screen(0, std::min(y2, iDasherMaxY), iScreenX2, iScreenY2); Cint32 iHeight = std::max(myint(iScreenY2 - iScreenY1),myint( 0)); Cint32 iWidth = std::max(myint(iScreenX2 - iScreenX1),myint( 0)); if((iHeight <= 1) && (iWidth <= 1)) return 0; // We're too small to render if((y1 > iDasherMaxY) || (y2 < iDasherMinY)){ return 0; // We're entirely off screen, so don't render. } // TODO: This should be earlier? if(!GetBoolParameter(BP_OUTLINE_MODE)) return 1; myint iDasherSize(y2 - y1); // std::cout << std::min(iDasherSize,iDasherMaxX) << " " << std::min(y2,iDasherMaxY) << " 0 " << std::max(y1,iDasherMinY) << std::endl; DasherDrawRectangle(0, std::min(y1,iDasherMaxY),std::min(iDasherSize,iDasherMaxX), std::max(y2,iDasherMinY), -1, Color, Nodes1, 1); // // FIXME - get rid of pointless assignment below // int iTruncation(GetLongParameter(LP_TRUNCATION)); // Trucation farction times 100; // if(iTruncation == 0) { // Regular squares // } // else { // // TODO: Put something back here? // } return 1; } // Draw a filled block of a node right down to the baseline (intended // for the case when you have no visible child) int CDasherViewSquare::RenderNodePartFast(const int Color, myint y1, myint y2, int &mostleft, const std::string &sDisplayText, bool bShove,myint iParentWidth ) { // Commenting because click mode occasionally fails this assert. // I don't know why. -- cjb. if (!(y2 >= y1)) { return 1; } // TODO - Get sensible limits here (to allow for non-linearities) myint iDasherMinX; myint iDasherMinY; myint iDasherMaxX; myint iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); screenint iScreenX1; screenint iScreenY1; screenint iScreenX2; screenint iScreenY2; Dasher2Screen(0, std::max(y1, iDasherMinY), iScreenX1, iScreenY1); Dasher2Screen(0, std::min(y2, iDasherMaxY), iScreenX2, iScreenY2); // std::cout << "Fill in components: " << iScreenY1 << " " << iScreenY2 << std::endl; Cint32 iHeight = std::max(myint(iScreenY2 - iScreenY1),myint( 0)); Cint32 iWidth = std::max(myint(iScreenX2 - iScreenX1),myint( 0)); if((iHeight < 1) && (iWidth < 1)) { // std::cout << "b" << std::endl; return 0; // We're too small to render } if((y1 > iDasherMaxY) || (y2 < iDasherMinY)){ //std::cout << "a" << std::endl; return 0; // We're entirely off screen, so don't render. } DasherDrawRectangle(std::min(iParentWidth,iDasherMaxX), std::min(y2,iDasherMaxY),0, std::max(y1,iDasherMinY), Color, -1, Nodes1, 0); return 1; } /// Convert screen co-ordinates to dasher co-ordinates. This doesn't /// include the nonlinear mapping for eyetracking mode etc - it is /// just the inverse of the mapping used to calculate the screen /// positions of boxes etc. void CDasherViewSquare::Screen2Dasher(screenint iInputX, screenint iInputY, myint &iDasherX, myint &iDasherY) { // Things we're likely to need: //myint iDasherWidth = (myint)GetLongParameter(LP_MAX_Y); myint iDasherHeight = (myint)GetLongParameter(LP_MAX_Y); screenint iScreenWidth = Screen()->GetWidth(); screenint iScreenHeight = Screen()->GetHeight(); int eOrientation(GetLongParameter(LP_REAL_ORIENTATION)); switch(eOrientation) { case Dasher::Opts::LeftToRight: iDasherX = iCenterX - ( iInputX - iScreenWidth / 2 ) * m_iScalingFactor / iScaleFactorX; iDasherY = iDasherHeight / 2 + ( iInputY - iScreenHeight / 2 ) * m_iScalingFactor / iScaleFactorY; break; case Dasher::Opts::RightToLeft: iDasherX = myint(iCenterX + ( iInputX - iScreenWidth / 2 ) * m_iScalingFactor/ iScaleFactorX); iDasherY = myint(iDasherHeight / 2 + ( iInputY - iScreenHeight / 2 ) * m_iScalingFactor/ iScaleFactorY); break; case Dasher::Opts::TopToBottom: iDasherX = myint(iCenterX - ( iInputY - iScreenHeight / 2 ) * m_iScalingFactor/ iScaleFactorY); iDasherY = myint(iDasherHeight / 2 + ( iInputX - iScreenWidth / 2 ) * m_iScalingFactor/ iScaleFactorX); break; case Dasher::Opts::BottomToTop: iDasherX = myint(iCenterX + ( iInputY - iScreenHeight / 2 ) * m_iScalingFactor/ iScaleFactorY); iDasherY = myint(iDasherHeight / 2 + ( iInputX - iScreenWidth / 2 ) * m_iScalingFactor/ iScaleFactorX); break; } iDasherX = ixmap(iDasherX); iDasherY = iymap(iDasherY); } void CDasherViewSquare::SetScaleFactor( void ) { //Parameters for X non-linearity. // Set some defaults here, in case we change(d) them later... m_dXmpb = 0.5; //threshold: DasherX's less than (m_dXmpb * MAX_Y) are linear... m_dXmpc = 0.9; //...but multiplied by m_dXmpc; DasherX's above that, are logarithmic... //set log scaling coefficient (unused if LP_NONLINEAR_X==0) // note previous value of m_dXmpa = 0.2, i.e. a value of LP_NONLINEAR_X =~= 4.8 m_dXmpa = exp(GetLongParameter(LP_NONLINEAR_X)/-3.0); myint iDasherWidth = (myint)GetLongParameter(LP_MAX_Y); myint iDasherHeight = iDasherWidth; screenint iScreenWidth = Screen()->GetWidth(); screenint iScreenHeight = Screen()->GetHeight(); // Try doing this a different way: myint iDasherMargin( GetLongParameter(LP_MARGIN_WIDTH) ); // Make this a parameter myint iMinX( 0-iDasherMargin ); myint iMaxX( iDasherWidth ); iCenterX = (iMinX + iMaxX)/2; myint iMinY( 0 ); myint iMaxY( iDasherHeight ); Dasher::Opts::ScreenOrientations eOrientation(Dasher::Opts::ScreenOrientations(GetLongParameter(LP_REAL_ORIENTATION))); double dScaleFactorX, dScaleFactorY; if (eOrientation == Dasher::Opts::LeftToRight || eOrientation == Dasher::Opts::RightToLeft) { dScaleFactorX = iScreenWidth / static_cast<double>( iMaxX - iMinX ); dScaleFactorY = iScreenHeight / static_cast<double>( iMaxY - iMinY ); } else { dScaleFactorX = iScreenHeight / static_cast<double>( iMaxX - iMinX ); dScaleFactorY = iScreenWidth / static_cast<double>( iMaxY - iMinY ); } if (dScaleFactorX < dScaleFactorY) { //fewer (pixels per dasher coord) in X direction - i.e., X is more compressed. //So, use X scale for Y too...except first, we'll _try_ to reduce the difference // by changing the relative scaling of X and Y (by at most 20%): double dMul = max(0.8, dScaleFactorX / dScaleFactorY); m_dXmpc *= dMul; dScaleFactorX /= dMul; iScaleFactorX = myint(dScaleFactorX * m_iScalingFactor); iScaleFactorY = myint(std::max(dScaleFactorX, dScaleFactorY / 4.0) * m_iScalingFactor); } else { //X has more room; use Y scale for both -> will get lots history iScaleFactorX = myint(std::max(dScaleFactorY, dScaleFactorX / 4.0) * m_iScalingFactor); iScaleFactorY = myint(dScaleFactorY * m_iScalingFactor); // however, "compensate" by relaxing the default "relative scaling" of X // (normally only 90% of Y) towards 1... m_dXmpc = std::min(1.0,0.9 * dScaleFactorX / dScaleFactorY); } iCenterX *= m_dXmpc; } inline myint CDasherViewSquare::CustomIDiv(myint iNumerator, myint iDenominator) { // Integer division rounding away from zero long long int num, denom, quot, rem; myint res; num = iNumerator; denom = iDenominator; DASHER_ASSERT(denom != 0); #ifdef HAVE_LLDIV lldiv_t ans = ::lldiv(num, denom); quot = ans.quot; rem = ans.rem; #else quot = num / denom; rem = num % denom; #endif if (rem < 0) res = quot - 1; else if (rem > 0) res = quot + 1; else diff --git a/Src/DasherCore/Event.h b/Src/DasherCore/Event.h index dcaa0af..9af0f4a 100644 --- a/Src/DasherCore/Event.h +++ b/Src/DasherCore/Event.h @@ -1,176 +1,177 @@ #ifndef __event_h__ #define __event_h__ // Classes representing different event types. #include <string> #include "DasherTypes.h" namespace Dasher { class CEvent; class CTextDrawEvent; class CParameterNotificationEvent; class CEditEvent; class CEditContextEvent; class CStartEvent; class CStopEvent; class CControlEvent; class CLockEvent; class CMessageEvent; class CCommandEvent; + class CDasherView; } enum { EV_PARAM_NOTIFY = 1, EV_EDIT, EV_EDIT_CONTEXT, EV_START, EV_STOP, EV_CONTROL, EV_LOCK, EV_MESSAGE, EV_COMMAND, EV_TEXTDRAW }; /// \ingroup Core /// @{ /// \defgroup Events Events generated by Dasher modules. /// @{ class Dasher::CEvent { public: int m_iEventType; }; class Dasher::CParameterNotificationEvent:public Dasher::CEvent { public: CParameterNotificationEvent(int iParameter) { m_iEventType = EV_PARAM_NOTIFY; m_iParameter = iParameter; }; int m_iParameter; }; class Dasher::CEditEvent:public Dasher::CEvent { public: CEditEvent(int iEditType, const std::string & sText, int iOffset) { m_iEventType = EV_EDIT; m_iEditType = iEditType; m_sText = sText; m_iOffset = iOffset; }; int m_iEditType; std::string m_sText; int m_iOffset; }; class Dasher::CEditContextEvent:public Dasher::CEvent { public: CEditContextEvent(int iOffset, int iLength) { m_iEventType = EV_EDIT_CONTEXT; m_iOffset = iOffset; m_iLength = iLength; }; int m_iOffset; int m_iLength; }; /** * An event that signals text has been drawn. Useful for determining its location * because that information is only available at draw time. */ class Dasher::CTextDrawEvent : public Dasher::CEvent { public: - CTextDrawEvent(std::string sDisplayText, CDasherView pView, screenint iX, screenint iY, int iSize) + CTextDrawEvent(std::string sDisplayText, CDasherView *pView, screenint iX, screenint iY, int iSize) :m_sDisplayText(sDisplayText), m_pDasherView(pView), m_iX(iX), m_iY(iY), m_iSize(iSize) { }; /** * The text that has been drawn. */ std::string m_sDisplayText; /** * The dasher view that emitted this event. */ CDasherView* m_pDasherView; /** * The X position (in screen coordinates) of the center of the box surrounding the text. */ screenint m_iX; /** * The Y position (in screen coordinates) of the center of the box surrounding the text. */ screenint m_iY; /** * The size of the text. Useful for determining the boundaries of the text "box" */ int m_iSize; }; class Dasher::CStartEvent:public Dasher::CEvent { public: CStartEvent() { m_iEventType = EV_START; }; }; class Dasher::CStopEvent:public Dasher::CEvent { public: CStopEvent() { m_iEventType = EV_STOP; }; }; class Dasher::CControlEvent:public Dasher::CEvent { public: CControlEvent(int iID) { m_iEventType = EV_CONTROL; m_iID = iID; }; int m_iID; }; class Dasher::CLockEvent : public Dasher::CEvent { public: CLockEvent(const std::string &strMessage, bool bLock, int iPercent) { m_iEventType = EV_LOCK; m_strMessage = strMessage; m_bLock = bLock; m_iPercent = iPercent; }; std::string m_strMessage; bool m_bLock; int m_iPercent; }; class Dasher::CMessageEvent : public Dasher::CEvent { public: CMessageEvent(const std::string &strMessage, int iID, int iType) { m_iEventType = EV_MESSAGE; m_strMessage = strMessage; m_iID = iID; m_iType = iType; }; std::string m_strMessage; int m_iID; int m_iType; }; class Dasher::CCommandEvent : public Dasher::CEvent { public: CCommandEvent(const std::string &strCommand) { m_iEventType = EV_COMMAND; m_strCommand = strCommand; }; std::string m_strCommand; }; /// @} /// @} #endif diff --git a/Src/DasherCore/GameModule.cpp b/Src/DasherCore/GameModule.cpp index 6ef7ca2..20358f9 100644 --- a/Src/DasherCore/GameModule.cpp +++ b/Src/DasherCore/GameModule.cpp @@ -1,61 +1,61 @@ #include "GameModule.h" using namespace Dasher; void CGameModule::HandleEvent(Dasher::CEvent *pEvent) { switch(pEvent->m_iEventType) { case EV_EDIT: { g_pLogger->Log("Capturing an edit event"); CEditEvent* evt = static_cast<CEditEvent*>(pEvent); switch(evt->m_iEditType) { // Added a new character (Stepped one node forward) case 0: m_stCurrentStringPos++; //pLastTypedNode = StringToNode(evt->m_sText); break; // Removed a character (Stepped one node back) case 1: break; default: break; } break; } case EV_TEXTDRAW: { CTextDrawEvent *evt = static_cast<CTextDrawEvent*>(pEvent); if(!m_sTargetString.substr(m_stCurrentStringPos+1, 1).compare(evt->m_sDisplayText)) { - m_pInterface->m_pDasherView->Screen2Dasher(evt->m_iX, evt->m_iY, m_iTargetX, m_iTargetY); + evt->m_pDasherView->Screen2Dasher(evt->m_iX, evt->m_iY, m_iTargetX, m_iTargetY); } } break; default: break; } return; } bool CGameModule::DecorateView(CDasherView *pView) { pView->DasherPolyarrow(&m_iTargetX, &m_iTargetY, 20, GetLongParameter(LP_LINE_WIDTH)*4, 135); return true; } //CDasherNode CGameModule::StringToNode(std::string sText) { // //} std::string CGameModule::GetTypedTarget() { return m_sTargetString.substr(0, m_stCurrentStringPos - 1); } std::string CGameModule::GetUntypedTarget() { return m_sTargetString.substr(m_stCurrentStringPos); }
rgee/HFOSS-Dasher
50dac4ba3fa066e1a254308b86b3752e038387d3
Continued de-bugging GameModule code.
diff --git a/Src/DasherCore/DasherInterfaceBase.cpp b/Src/DasherCore/DasherInterfaceBase.cpp index f341066..5412ab2 100644 --- a/Src/DasherCore/DasherInterfaceBase.cpp +++ b/Src/DasherCore/DasherInterfaceBase.cpp @@ -449,716 +449,715 @@ void CDasherInterfaceBase::Pause() { m_pEventHandler->InsertEvent(&oEvent); #ifndef _WIN32_WCE if (m_pUserLog != NULL) m_pUserLog->StopWriting((float) GetNats()); #endif } void CDasherInterfaceBase::GameMessageIn(int message, void* messagedata) { GameMode::CDasherGameMode::GetTeacher()->Message(message, messagedata); } void CDasherInterfaceBase::Unpause(unsigned long Time) { if (!GetBoolParameter(BP_DASHER_PAUSED)) return; //already running, no need to do anything SetBoolParameter(BP_DASHER_PAUSED, false); if(m_pDasherModel != 0) m_pDasherModel->Reset_framerate(Time); Dasher::CStartEvent oEvent; m_pEventHandler->InsertEvent(&oEvent); // Commenting this out, can't see a good reason to ResetNats, // just because we are not paused anymore - pconlon // ResetNats(); #ifndef _WIN32_WCE if (m_pUserLog != NULL) m_pUserLog->StartWriting(); #endif } void CDasherInterfaceBase::CreateInput() { if(m_pInput) { m_pInput->Deactivate(); } m_pInput = (CDasherInput *)GetModuleByName(GetStringParameter(SP_INPUT_DEVICE)); if (m_pInput == NULL) m_pInput = (CDasherInput *)GetDefaultInputDevice(); if(m_pInput) { m_pInput->Activate(); } if(m_pDasherView != 0) m_pDasherView->SetInput(m_pInput); } void CDasherInterfaceBase::NewFrame(unsigned long iTime, bool bForceRedraw) { // Prevent NewFrame from being reentered. This can happen occasionally and // cause crashes. static bool bReentered=false; if (bReentered) { #ifdef DEBUG std::cout << "CDasherInterfaceBase::NewFrame was re-entered" << std::endl; #endif return; } bReentered=true; // Fail if Dasher is locked // if(m_iCurrentState != ST_NORMAL) // return; bool bChanged(false), bWasPaused(GetBoolParameter(BP_DASHER_PAUSED)); CExpansionPolicy *pol=m_defaultPolicy; if(m_pDasherView != 0) { if(!GetBoolParameter(BP_TRAINING)) { if (m_pUserLog != NULL) { //ACL note that as of 15/5/09, splitting UpdatePosition into two, //DasherModel no longer guarantees to empty these two if it didn't do anything. //So initialise appropriately... Dasher::VECTOR_SYMBOL_PROB vAdded; int iNumDeleted = 0; if(m_pInputFilter) { bChanged = m_pInputFilter->Timer(iTime, m_pDasherView, m_pDasherModel, &vAdded, &iNumDeleted, &pol); } #ifndef _WIN32_WCE if (iNumDeleted > 0) m_pUserLog->DeleteSymbols(iNumDeleted); if (vAdded.size() > 0) m_pUserLog->AddSymbols(&vAdded); #endif } else { if(m_pInputFilter) { bChanged = m_pInputFilter->Timer(iTime, m_pDasherView, m_pDasherModel, 0, 0, &pol); } } m_pDasherModel->CheckForNewRoot(m_pDasherView); } } //check: if we were paused before, and the input filter didn't unpause, // then nothing can have changed: DASHER_ASSERT(!bWasPaused || !GetBoolParameter(BP_DASHER_PAUSED) || !bChanged); // Flags at this stage: // // - bChanged = the display was updated, so needs to be rendered to the display // - m_bLastChanged = bChanged was true last time around // - m_bRedrawScheduled = Display invalidated internally // - bForceRedraw = Display invalidated externally // TODO: This is a bit hacky - we really need to sort out the redraw logic if((!bChanged && m_bLastChanged) || m_bRedrawScheduled || bForceRedraw) { m_pDasherView->Screen()->SetCaptureBackground(true); m_pDasherView->Screen()->SetLoadBackground(true); } bForceRedraw |= m_bLastChanged; m_bLastChanged = bChanged; //will also be set in Redraw if any nodes were expanded. Redraw(bChanged || m_bRedrawScheduled || bForceRedraw, *pol); m_bRedrawScheduled = false; // This just passes the time through to the framerate tracker, so we // know how often new frames are being drawn. if(m_pDasherModel != 0) m_pDasherModel->RecordFrame(iTime); bReentered=false; } void CDasherInterfaceBase::Redraw(bool bRedrawNodes, CExpansionPolicy &policy) { // No point continuing if there's nothing to draw on... if(!m_pDasherView) return; // Draw the nodes if(bRedrawNodes) { m_pDasherView->Screen()->SendMarker(0); if (m_pDasherModel) m_bLastChanged |= m_pDasherModel->RenderToView(m_pDasherView,policy); } // Draw the decorations m_pDasherView->Screen()->SendMarker(1); if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) pTeacher->DrawGameDecorations(m_pDasherView); bool bDecorationsChanged(false); if(m_pInputFilter) { bDecorationsChanged = m_pInputFilter->DecorateView(m_pDasherView); } if(m_pGameModule) { bDecorationsChanged = m_pGameModule->DecorateView(m_pDasherView) || bDecorationsChanged; } bool bActionButtonsChanged(false); #ifdef EXPERIMENTAL_FEATURES bActionButtonsChanged = DrawActionButtons(); #endif // Only blit the image to the display if something has actually changed if(bRedrawNodes || bDecorationsChanged || bActionButtonsChanged) m_pDasherView->Display(); } void CDasherInterfaceBase::ChangeAlphabet() { if(GetStringParameter(SP_ALPHABET_ID) == "") { SetStringParameter(SP_ALPHABET_ID, m_AlphIO->GetDefault()); // This will result in ChangeAlphabet() being called again, so // exit from the first recursion return; } // Send a lock event WriteTrainFileFull(); // Lock Dasher to prevent changes from happening while we're training. SetBoolParameter( BP_TRAINING, true ); CreateNCManager(); #ifndef _WIN32_WCE // Let our user log object know about the new alphabet since // it needs to convert symbols into text for the log file. if (m_pUserLog != NULL) m_pUserLog->SetAlphabetPtr(m_Alphabet); #endif // Apply options from alphabet SetBoolParameter( BP_TRAINING, false ); //} } void CDasherInterfaceBase::ChangeColours() { if(!m_ColourIO || !m_DasherScreen) return; // TODO: Make fuction return a pointer directly m_DasherScreen->SetColourScheme(&(m_ColourIO->GetInfo(GetStringParameter(SP_COLOUR_ID)))); } void CDasherInterfaceBase::ChangeScreen(CDasherScreen *NewScreen) { // What does ChangeScreen do? m_DasherScreen = NewScreen; ChangeColours(); if(m_pDasherView != 0) { m_pDasherView->ChangeScreen(m_DasherScreen); } else if(GetLongParameter(LP_VIEW_ID) != -1) { ChangeView(); } PositionActionButtons(); BudgettingPolicy pol(GetLongParameter(LP_NODE_BUDGET)); //maintain budget, but allow arbitrary amount of work. Redraw(true, pol); // (we're assuming resolution changes are occasional, i.e. // we don't need to worry about maintaining the frame rate, so we can do // as much work as necessary. However, it'd probably be better still to // get a node queue from the input filter, as that might have a different // policy / budget. } void CDasherInterfaceBase::ChangeView() { // TODO: Actually respond to LP_VIEW_ID parameter (although there is only one view at the moment) // removed condition that m_pDasherModel != 0. Surely the view can exist without the model?-pconlon if(m_DasherScreen != 0 /*&& m_pDasherModel != 0*/) { delete m_pDasherView; m_pDasherView = new CDasherViewSquare(m_pEventHandler, m_pSettingsStore, m_DasherScreen); if (m_pInput) m_pDasherView->SetInput(m_pInput); // Tell the Teacher which view we are using if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) pTeacher->SetDasherView(m_pDasherView); } } const CAlphIO::AlphInfo & CDasherInterfaceBase::GetInfo(const std::string &AlphID) { return m_AlphIO->GetInfo(AlphID); } void CDasherInterfaceBase::SetInfo(const CAlphIO::AlphInfo &NewInfo) { m_AlphIO->SetInfo(NewInfo); } void CDasherInterfaceBase::DeleteAlphabet(const std::string &AlphID) { m_AlphIO->Delete(AlphID); } double CDasherInterfaceBase::GetCurCPM() { // return 0; } double CDasherInterfaceBase::GetCurFPS() { // return 0; } // int CDasherInterfaceBase::GetAutoOffset() { // if(m_pDasherView != 0) { // return m_pDasherView->GetAutoOffset(); // } // return -1; // } double CDasherInterfaceBase::GetNats() const { if(m_pDasherModel) return m_pDasherModel->GetNats(); else return 0.0; } void CDasherInterfaceBase::ResetNats() { if(m_pDasherModel) m_pDasherModel->ResetNats(); } // TODO: Check that none of this needs to be reimplemented // void CDasherInterfaceBase::InvalidateContext(bool bForceStart) { // m_pDasherModel->m_strContextBuffer = ""; // Dasher::CEditContextEvent oEvent(10); // m_pEventHandler->InsertEvent(&oEvent); // std::string strNewContext(m_pDasherModel->m_strContextBuffer); // // We keep track of an internal context and compare that to what // // we are given - don't restart Dasher if nothing has changed. // // This should really be integrated with DasherModel, which // // probably will be the case when we start to deal with being able // // to back off indefinitely. For now though we'll keep it in a // // separate string. // int iContextLength( 6 ); // The 'important' context length - should really get from language model // // FIXME - use unicode lengths // if(bForceStart || (strNewContext.substr( std::max(static_cast<int>(strNewContext.size()) - iContextLength, 0)) != strCurrentContext.substr( std::max(static_cast<int>(strCurrentContext.size()) - iContextLength, 0)))) { // if(m_pDasherModel != NULL) { // // TODO: Reimplement this // // if(m_pDasherModel->m_bContextSensitive || bForceStart) { // { // m_pDasherModel->SetContext(strNewContext); // PauseAt(0,0); // } // } // strCurrentContext = strNewContext; // WriteTrainFileFull(); // } // if(bForceStart) { // int iMinWidth; // if(m_pInputFilter && m_pInputFilter->GetMinWidth(iMinWidth)) { // m_pDasherModel->LimitRoot(iMinWidth); // } // } // if(m_pDasherView) // while( m_pDasherModel->CheckForNewRoot(m_pDasherView) ) { // // Do nothing // } // ScheduleRedraw(); // } // TODO: Fix this std::string CDasherInterfaceBase::GetContext(int iStart, int iLength) { m_strContext = ""; CEditContextEvent oEvent(iStart, iLength); m_pEventHandler->InsertEvent(&oEvent); return m_strContext; } void CDasherInterfaceBase::SetContext(std::string strNewContext) { m_strContext = strNewContext; } // Control mode stuff void CDasherInterfaceBase::RegisterNode( int iID, const std::string &strLabel, int iColour ) { m_pNCManager->RegisterNode(iID, strLabel, iColour); } void CDasherInterfaceBase::ConnectNode(int iChild, int iParent, int iAfter) { m_pNCManager->ConnectNode(iChild, iParent, iAfter); } void CDasherInterfaceBase::DisconnectNode(int iChild, int iParent) { m_pNCManager->DisconnectNode(iChild, iParent); } void CDasherInterfaceBase::SetBoolParameter(int iParameter, bool bValue) { m_pSettingsStore->SetBoolParameter(iParameter, bValue); }; void CDasherInterfaceBase::SetLongParameter(int iParameter, long lValue) { m_pSettingsStore->SetLongParameter(iParameter, lValue); }; void CDasherInterfaceBase::SetStringParameter(int iParameter, const std::string & sValue) { PreSetNotify(iParameter, sValue); m_pSettingsStore->SetStringParameter(iParameter, sValue); }; bool CDasherInterfaceBase::GetBoolParameter(int iParameter) { return m_pSettingsStore->GetBoolParameter(iParameter); } long CDasherInterfaceBase::GetLongParameter(int iParameter) { return m_pSettingsStore->GetLongParameter(iParameter); } std::string CDasherInterfaceBase::GetStringParameter(int iParameter) { return m_pSettingsStore->GetStringParameter(iParameter); } void CDasherInterfaceBase::ResetParameter(int iParameter) { m_pSettingsStore->ResetParameter(iParameter); } // We need to be able to get at the UserLog object from outside the interface CUserLogBase* CDasherInterfaceBase::GetUserLogPtr() { return m_pUserLog; } void CDasherInterfaceBase::KeyDown(int iTime, int iId, bool bPos, int iX, int iY) { if(m_iCurrentState != ST_NORMAL) return; if(m_pInputFilter && !GetBoolParameter(BP_TRAINING)) { m_pInputFilter->KeyDown(iTime, iId, m_pDasherView, m_pDasherModel, m_pUserLog, bPos, iX, iY); } if(m_pInput && !GetBoolParameter(BP_TRAINING)) { m_pInput->KeyDown(iTime, iId); } } void CDasherInterfaceBase::KeyUp(int iTime, int iId, bool bPos, int iX, int iY) { if(m_iCurrentState != ST_NORMAL) return; if(m_pInputFilter && !GetBoolParameter(BP_TRAINING)) { m_pInputFilter->KeyUp(iTime, iId, m_pDasherView, m_pDasherModel, bPos, iX, iY); } if(m_pInput && !GetBoolParameter(BP_TRAINING)) { m_pInput->KeyUp(iTime, iId); } } void CDasherInterfaceBase::InitGameModule() { if(m_pGameModule == NULL) { g_pLogger->Log("Initializing the game module."); m_pGameModule = (CGameModule*) GetModuleByName("Game Mode"); } } void CDasherInterfaceBase::CreateInputFilter() { if(m_pInputFilter) { m_pInputFilter->Deactivate(); m_pInputFilter = NULL; } #ifndef _WIN32_WCE m_pInputFilter = (CInputFilter *)GetModuleByName(GetStringParameter(SP_INPUT_FILTER)); #endif if (m_pInputFilter == NULL) m_pInputFilter = (CInputFilter *)GetDefaultInputMethod(); m_pInputFilter->Activate(); } CDasherModule *CDasherInterfaceBase::RegisterModule(CDasherModule *pModule) { return m_oModuleManager.RegisterModule(pModule); } CDasherModule *CDasherInterfaceBase::GetModule(ModuleID_t iID) { return m_oModuleManager.GetModule(iID); } CDasherModule *CDasherInterfaceBase::GetModuleByName(const std::string &strName) { return m_oModuleManager.GetModuleByName(strName); } CDasherModule *CDasherInterfaceBase::GetDefaultInputDevice() { return m_oModuleManager.GetDefaultInputDevice(); } CDasherModule *CDasherInterfaceBase::GetDefaultInputMethod() { return m_oModuleManager.GetDefaultInputMethod(); } void CDasherInterfaceBase::SetDefaultInputDevice(CDasherModule *pModule) { m_oModuleManager.SetDefaultInputDevice(pModule); } void CDasherInterfaceBase::SetDefaultInputMethod(CDasherModule *pModule) { m_oModuleManager.SetDefaultInputMethod(pModule); } void CDasherInterfaceBase::CreateModules() { SetDefaultInputMethod( RegisterModule(new CDefaultFilter(m_pEventHandler, m_pSettingsStore, this, 3, _("Normal Control"))) ); RegisterModule(new COneDimensionalFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CEyetrackerFilter(m_pEventHandler, m_pSettingsStore, this)); #ifndef _WIN32_WCE RegisterModule(new CClickFilter(m_pEventHandler, m_pSettingsStore, this)); #else SetDefaultInputMethod( RegisterModule(new CClickFilter(m_pEventHandler, m_pSettingsStore, this)); ); #endif RegisterModule(new COneButtonFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new COneButtonDynamicFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CTwoButtonDynamicFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CTwoPushDynamicFilter(m_pEventHandler, m_pSettingsStore, this)); // TODO: specialist factory for button mode RegisterModule(new CButtonMode(m_pEventHandler, m_pSettingsStore, this, true, 8, _("Menu Mode"))); RegisterModule(new CButtonMode(m_pEventHandler, m_pSettingsStore, this, false,10, _("Direct Mode"))); // RegisterModule(new CDasherButtons(m_pEventHandler, m_pSettingsStore, this, 4, 0, false,11, "Buttons 3")); RegisterModule(new CAlternatingDirectMode(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CCompassMode(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CStylusFilter(m_pEventHandler, m_pSettingsStore, this, 15, _("Stylus Control"))); // Register game mode with the module manager // TODO should this be wrapped in an "if game mode enabled" // conditional? // TODO: I don't know what a sensible module ID should be // for this, so I chose an arbitrary value - // TODO: Put "Game Mode" in enumeration in Parameter.h - + // TODO: Put "Game Mode" in enumeration in Parameter.h RegisterModule(new CGameModule(m_pEventHandler, m_pSettingsStore, this, 21, _("Game Mode"))); } void CDasherInterfaceBase::GetPermittedValues(int iParameter, std::vector<std::string> &vList) { // TODO: Deprecate direct calls to these functions switch (iParameter) { case SP_ALPHABET_ID: if(m_AlphIO) m_AlphIO->GetAlphabets(&vList); break; case SP_COLOUR_ID: if(m_ColourIO) m_ColourIO->GetColours(&vList); break; case SP_INPUT_FILTER: m_oModuleManager.ListModules(1, vList); break; case SP_INPUT_DEVICE: m_oModuleManager.ListModules(0, vList); break; } } void CDasherInterfaceBase::StartShutdown() { ChangeState(TR_SHUTDOWN); } bool CDasherInterfaceBase::GetModuleSettings(const std::string &strName, SModuleSettings **pSettings, int *iCount) { return GetModuleByName(strName)->GetSettings(pSettings, iCount); } void CDasherInterfaceBase::SetupActionButtons() { m_vLeftButtons.push_back(new CActionButton(this, "Exit", true)); m_vLeftButtons.push_back(new CActionButton(this, "Preferences", false)); m_vLeftButtons.push_back(new CActionButton(this, "Help", false)); m_vLeftButtons.push_back(new CActionButton(this, "About", false)); } void CDasherInterfaceBase::DestroyActionButtons() { // TODO: implement and call this } void CDasherInterfaceBase::PositionActionButtons() { if(!m_DasherScreen) return; int iCurrentOffset(16); for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) { (*it)->SetPosition(16, iCurrentOffset, 32, 32); iCurrentOffset += 48; } iCurrentOffset = 16; for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) { (*it)->SetPosition(m_DasherScreen->GetWidth() - 144, iCurrentOffset, 128, 32); iCurrentOffset += 48; } } bool CDasherInterfaceBase::DrawActionButtons() { if(!m_DasherScreen) return false; bool bVisible(GetBoolParameter(BP_DASHER_PAUSED)); bool bRV(bVisible != m_bOldVisible); m_bOldVisible = bVisible; for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) (*it)->Draw(m_DasherScreen, bVisible); for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) (*it)->Draw(m_DasherScreen, bVisible); return bRV; } void CDasherInterfaceBase::HandleClickUp(int iTime, int iX, int iY) { #ifdef EXPERIMENTAL_FEATURES bool bVisible(GetBoolParameter(BP_DASHER_PAUSED)); for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) { if((*it)->HandleClickUp(iTime, iX, iY, bVisible)) return; } for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) { if((*it)->HandleClickUp(iTime, iX, iY, bVisible)) return; } #endif KeyUp(iTime, 100, true, iX, iY); } void CDasherInterfaceBase::HandleClickDown(int iTime, int iX, int iY) { #ifdef EXPERIMENTAL_FEATURES bool bVisible(GetBoolParameter(BP_DASHER_PAUSED)); for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) { if((*it)->HandleClickDown(iTime, iX, iY, bVisible)) return; } for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) { if((*it)->HandleClickDown(iTime, iX, iY, bVisible)) return; } #endif KeyDown(iTime, 100, true, iX, iY); } void CDasherInterfaceBase::ExecuteCommand(const std::string &strName) { // TODO: Pointless - just insert event directly CCommandEvent *pEvent = new CCommandEvent(strName); m_pEventHandler->InsertEvent(pEvent); delete pEvent; } double CDasherInterfaceBase::GetFramerate() { if(m_pDasherModel) return(m_pDasherModel->Framerate()); else return 0.0; } void CDasherInterfaceBase::AddActionButton(const std::string &strName) { m_vRightButtons.push_back(new CActionButton(this, strName, false)); } void CDasherInterfaceBase::OnUIRealised() { StartTimer(); ChangeState(TR_UI_INIT); } void CDasherInterfaceBase::ChangeState(ETransition iTransition) { static EState iTransitionTable[ST_NUM][TR_NUM] = { {ST_MODEL, ST_UI, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN},//ST_START {ST_FORBIDDEN, ST_NORMAL, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN},//ST_MODEL {ST_NORMAL, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN},//ST_UI {ST_FORBIDDEN, ST_FORBIDDEN, ST_LOCKED, ST_FORBIDDEN, ST_SHUTDOWN},//ST_NORMAL {ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_NORMAL, ST_FORBIDDEN},//ST_LOCKED {ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN}//ST_SHUTDOWN //TR_MODEL_INIT, TR_UI_INIT, TR_LOCK, TR_UNLOCK, TR_SHUTDOWN }; EState iNewState(iTransitionTable[m_iCurrentState][iTransition]); if(iNewState != ST_FORBIDDEN) { if (iNewState == ST_SHUTDOWN) { ShutdownTimer(); WriteTrainFileFull(); } m_iCurrentState = iNewState; } } void CDasherInterfaceBase::SetBuffer(int iOffset) { CreateModel(iOffset); } void CDasherInterfaceBase::UnsetBuffer() { // TODO: Write training file? if(m_pDasherModel) delete m_pDasherModel; m_pDasherModel = 0; } void CDasherInterfaceBase::SetOffset(int iOffset) { if(m_pDasherModel) m_pDasherModel->SetOffset(iOffset, m_pDasherView); } void CDasherInterfaceBase::SetControlOffset(int iOffset) { if(m_pDasherModel) m_pDasherModel->SetControlOffset(iOffset); } // Returns 0 on success, an error string on failure. const char* CDasherInterfaceBase::ClSet(const std::string &strKey, const std::string &strValue) { if(m_pSettingsStore) return m_pSettingsStore->ClSet(strKey, strValue); return 0; } void CDasherInterfaceBase::ImportTrainingText(const std::string &strPath) { if(m_pNCManager) m_pNCManager->ImportTrainingText(strPath); } diff --git a/Src/DasherCore/DasherViewSquare.cpp b/Src/DasherCore/DasherViewSquare.cpp index bb963e5..a1c341a 100644 --- a/Src/DasherCore/DasherViewSquare.cpp +++ b/Src/DasherCore/DasherViewSquare.cpp @@ -1,728 +1,728 @@ // DasherViewSquare.cpp // // Copyright (c) 2008 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" #ifdef _WIN32 #include "..\Win32\Common\WinCommon.h" #endif //#include "DasherGameMode.h" #include "DasherViewSquare.h" #include "DasherModel.h" #include "DasherView.h" #include "DasherTypes.h" #include "Event.h" #include "EventHandler.h" #include <algorithm> #include <iostream> #include <limits> #include <stdlib.h> using namespace Dasher; using namespace Opts; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG_MEMLEAKS #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif // FIXME - quite a lot of the code here probably should be moved to // the parent class (DasherView). I think we really should make the // parent class less general - we're probably not going to implement // anything which uses radically different co-ordinate transforms, and // we can always override if necessary. // FIXME - duplicated 'mode' code throught - needs to be fixed (actually, mode related stuff, Input2Dasher etc should probably be at least partially in some other class) CDasherViewSquare::CDasherViewSquare(CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CDasherScreen *DasherScreen) : CDasherView(pEventHandler, pSettingsStore, DasherScreen), m_Y1(4), m_Y2(0.95 * GetLongParameter(LP_MAX_Y)), m_Y3(0.05 * GetLongParameter((LP_MAX_Y))) { // TODO - AutoOffset should be part of the eyetracker input filter // Make sure that the auto calibration is set to zero berfore we start // m_yAutoOffset = 0; ChangeScreen(DasherScreen); //Note, nonlinearity parameters set in SetScaleFactor m_bVisibleRegionValid = false; } CDasherViewSquare::~CDasherViewSquare() {} void CDasherViewSquare::HandleEvent(Dasher::CEvent *pEvent) { // Let the parent class do its stuff CDasherView::HandleEvent(pEvent); // And then interpret events for ourself if(pEvent->m_iEventType == 1) { Dasher::CParameterNotificationEvent * pEvt(static_cast < Dasher::CParameterNotificationEvent * >(pEvent)); switch (pEvt->m_iParameter) { case LP_REAL_ORIENTATION: case LP_MARGIN_WIDTH: case BP_NONLINEAR_Y: case LP_NONLINEAR_X: m_bVisibleRegionValid = false; SetScaleFactor(); break; default: break; } } } /// Draw text specified in Dasher co-ordinates. The position is /// specified as two co-ordinates, intended to the be the corners of /// the leading edge of the containing box. void CDasherViewSquare::DasherDrawText(myint iAnchorX1, myint iAnchorY1, myint iAnchorX2, myint iAnchorY2, const std::string &sDisplayText, int &mostleft, bool bShove) { // Don't draw text which will overlap with text in an ancestor. if(iAnchorX1 > mostleft) iAnchorX1 = mostleft; if(iAnchorX2 > mostleft) iAnchorX2 = mostleft; myint iDasherMinX; myint iDasherMinY; myint iDasherMaxX; myint iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); iAnchorY1 = std::min( iDasherMaxY, std::max( iDasherMinY, iAnchorY1 ) ); iAnchorY2 = std::min( iDasherMaxY, std::max( iDasherMinY, iAnchorY2 ) ); screenint iScreenAnchorX1; screenint iScreenAnchorY1; screenint iScreenAnchorX2; screenint iScreenAnchorY2; // FIXME - Truncate here before converting - otherwise we risk integer overflow in screen coordinates Dasher2Screen(iAnchorX1, iAnchorY1, iScreenAnchorX1, iScreenAnchorY1); Dasher2Screen(iAnchorX2, iAnchorY2, iScreenAnchorX2, iScreenAnchorY2); // Truncate the ends of the anchor line to be on the screen - this // prevents us from loosing characters off the top and bottom of the // screen // TruncateToScreen(iScreenAnchorX1, iScreenAnchorY1); // TruncateToScreen(iScreenAnchorX2, iScreenAnchorY2); // Actual anchor point is the midpoint of the anchor line screenint iScreenAnchorX((iScreenAnchorX1 + iScreenAnchorX2) / 2); screenint iScreenAnchorY((iScreenAnchorY1 + iScreenAnchorY2) / 2); // Compute font size based on position int Size = GetLongParameter( LP_DASHER_FONTSIZE ); // FIXME - this could be much more elegant, and probably needs a // rethink anyway - behvaiour here is too dependent on screen size screenint iLeftTimesFontSize = ((myint)GetLongParameter(LP_MAX_Y) - (iAnchorX1 + iAnchorX2)/ 2 )*Size; if(iLeftTimesFontSize < (myint)GetLongParameter(LP_MAX_Y) * 19/ 20) Size *= 20; else if(iLeftTimesFontSize < (myint)GetLongParameter(LP_MAX_Y) * 159 / 160) Size *= 14; else Size *= 11; screenint TextWidth, TextHeight; Screen()->TextSize(sDisplayText, &TextWidth, &TextHeight, Size); // Poistion of text box relative to anchor depends on orientation screenint newleft2 = 0; screenint newtop2 = 0; screenint newright2 = 0; screenint newbottom2 = 0; switch (Dasher::Opts::ScreenOrientations(GetLongParameter(LP_REAL_ORIENTATION))) { case (Dasher::Opts::LeftToRight): newleft2 = iScreenAnchorX; newtop2 = iScreenAnchorY - TextHeight / 2; newright2 = iScreenAnchorX + TextWidth; newbottom2 = iScreenAnchorY + TextHeight / 2; break; case (Dasher::Opts::RightToLeft): newleft2 = iScreenAnchorX - TextWidth; newtop2 = iScreenAnchorY - TextHeight / 2; newright2 = iScreenAnchorX; newbottom2 = iScreenAnchorY + TextHeight / 2; break; case (Dasher::Opts::TopToBottom): newleft2 = iScreenAnchorX - TextWidth / 2; newtop2 = iScreenAnchorY; newright2 = iScreenAnchorX + TextWidth / 2; newbottom2 = iScreenAnchorY + TextHeight; break; case (Dasher::Opts::BottomToTop): newleft2 = iScreenAnchorX - TextWidth / 2; newtop2 = iScreenAnchorY - TextHeight; newright2 = iScreenAnchorX + TextWidth / 2; newbottom2 = iScreenAnchorY; break; default: break; } // Update the value of mostleft to take into account the new text if(bShove) { myint iDasherNewLeft; myint iDasherNewTop; myint iDasherNewRight; myint iDasherNewBottom; Screen2Dasher(newleft2, newtop2, iDasherNewLeft, iDasherNewTop); Screen2Dasher(newright2, newbottom2, iDasherNewRight, iDasherNewBottom); mostleft = std::min(iDasherNewRight, iDasherNewLeft); } // Tell other listeners that text has been drawn and provide some information // about the draw call. - m_pEventHandler->InsertEvent(new CTextDrawEvent(sDisplaytext, newleft2, newtop2, Size)); + m_pEventHandler->InsertEvent(new CTextDrawEvent(sDisplayText, newleft2, newtop2, Size)); // Actually draw the text. We use DelayDrawText as the text should // be overlayed once all of the boxes have been drawn. m_DelayDraw.DelayDrawText(sDisplayText, newleft2, newtop2, Size); } void CDasherViewSquare::RenderNodes(CDasherNode *pRoot, myint iRootMin, myint iRootMax, CExpansionPolicy &policy) { DASHER_ASSERT(pRoot != 0); myint iDasherMinX; myint iDasherMinY; myint iDasherMaxX; myint iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); // screenint iScreenLeft; screenint iScreenTop; screenint iScreenRight; screenint iScreenBottom; Dasher2Screen(iRootMax-iRootMin, iRootMin, iScreenLeft, iScreenTop); Dasher2Screen(0, iRootMax, iScreenRight, iScreenBottom); //ifiScreenTop < 0) // iScreenTop = 0; //if(iScreenLeft < 0) // iScreenLeft=0; //// TODO: Should these be right on the boundary? //if(iScreenBottom > Screen()->GetHeight()) // iScreenBottom=Screen()->GetHeight(); //if(iScreenRight > Screen()->GetWidth()) // iScreenRight=Screen()->GetWidth(); // Blank the region around the root node: if(iRootMin > iDasherMinY) DasherDrawRectangle(iDasherMaxX, iDasherMinY, iDasherMinX, iRootMin, 0, -1, Nodes1, 0); //if(iScreenTop > 0) // Screen()->DrawRectangle(0, 0, Screen()->GetWidth(), iScreenTop, 0, -1, Nodes1, false, true, 1); if(iRootMax < iDasherMaxY) DasherDrawRectangle(iDasherMaxX, iRootMax, iDasherMinX, iDasherMaxY, 0, -1, Nodes1, 0); //if(iScreenBottom <= Screen()->GetHeight()) // Screen()->DrawRectangle(0, iScreenBottom, Screen()->GetWidth(), Screen()->GetHeight(), 0, -1, Nodes1, false, true, 1); DasherDrawRectangle(0, iDasherMinY, iDasherMinX, iDasherMaxY, 0, -1, Nodes1, 0); // Screen()->DrawRectangle(iScreenRight, std::max(0, (int)iScreenTop), // Screen()->GetWidth(), std::min(Screen()->GetHeight(), (int)iScreenBottom), // 0, -1, Nodes1, false, true, 1); // Render the root node (and children) RecursiveRender(pRoot, iRootMin, iRootMax, iDasherMaxX, policy, std::numeric_limits<double>::infinity(), iDasherMaxX,0,0); // Labels are drawn in a second parse to get the overlapping right m_DelayDraw.Draw(Screen()); // Finally decorate the view Crosshair((myint)GetLongParameter(LP_OX)); } //min size in *Dasher co-ordinates* to consider rendering a node #define QUICK_REJECT 50 //min size in *screen* (pixel) co-ordinates to render a node #define MIN_SIZE 2 bool CDasherViewSquare::CheckRender(CDasherNode *pRender, myint y1, myint y2, int mostleft, CExpansionPolicy &policy, double dMaxCost, myint parent_width, int parent_color, int iDepth) { if (y2-y1 >= QUICK_REJECT) { myint iDasherMinX; myint iDasherMinY; myint iDasherMaxX; myint iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); if (y1 <= iDasherMaxY && y2 >= iDasherMinY) { screenint iScreenX1; screenint iScreenY1; screenint iScreenX2; screenint iScreenY2; Dasher2Screen(0, std::max(y1, iDasherMinY), iScreenX1, iScreenY1); Dasher2Screen(0, std::min(y2, iDasherMaxY), iScreenX2, iScreenY2); Cint32 iHeight = std::max(myint(iScreenY2 - iScreenY1),myint( 0)); if (iHeight >= MIN_SIZE) { //node should be rendered! RecursiveRender(pRender, y1, y2, mostleft, policy, dMaxCost, parent_width, parent_color, iDepth); return true; } } } // We get here if the node is too small to render or is off-screen. // So, collapse it immediately. // // In game mode, we get here if the child is too small to draw, but we need the // coordinates - if this is the case then we shouldn't delete any children. // // TODO: Should probably render the parent segment here anyway (or // in the above) if(!pRender->GetFlag(NF_GAME)) pRender->Delete_children(); return false; } void CDasherViewSquare::RecursiveRender(CDasherNode *pRender, myint y1, myint y2, int mostleft, CExpansionPolicy &policy, double dMaxCost, myint parent_width,int parent_color, int iDepth) { DASHER_ASSERT_VALIDPTR_RW(pRender); // if(iDepth == 2) // std::cout << pRender->GetDisplayInfo()->strDisplayText << std::endl; // TODO: We need an overhall of the node creation/deletion logic - // make sure that we only maintain the minimum number of nodes which // are actually needed. This is especially true at the moment in // Game mode, which feels very sluggish. Node creation also feels // slower in Windows than Linux, especially if many nodes are // created at once (eg untrained Hiragana) ++m_iRenderCount; // myint trange = y2 - y1; // Attempt to draw the region to the left of this node inside its parent. // if(iDepth == 2) { // std::cout << "y1: " << y1 << " y2: " << y2 << std::endl; // Set the NF_SUPER flag if this node entirely frames the visual // area. // TODO: too slow? // TODO: use flags more rather than delete/reparent lists myint iDasherMinX; myint iDasherMinY; myint iDasherMaxX; myint iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); DasherDrawRectangle(std::min(parent_width,iDasherMaxX), std::max(y1,iDasherMinY), std::min(y2-y1,iDasherMaxX), std::min(y2,iDasherMaxY), parent_color, -1, Nodes1, 0); const std::string &sDisplayText(pRender->getDisplayText()); if( sDisplayText.size() > 0 ) { DasherDrawText(y2-y1, y1, y2-y1, y2, sDisplayText, mostleft, pRender->bShove()); } pRender->SetFlag(NF_SUPER, !IsSpaceAroundNode(y1,y2)); // If there are no children then we still need to render the parent if(pRender->ChildCount() == 0) { DasherDrawRectangle(std::min(y2-y1,iDasherMaxX), std::min(y2,iDasherMaxY),0, std::max(y1,iDasherMinY), pRender->getColour(), -1, Nodes1, 0); //also allow it to be expanded, it's big enough. policy.pushNode(pRender, y1, y2, true, dMaxCost); return; } //Node has children. It can therefore be collapsed...however, // we don't allow a node covering the crosshair to be collapsed // (at best this'll mean there's nowhere useful to go forwards; // at worst, all kinds of crashes trying to do text output!) if (!pRender->GetFlag(NF_GAME) && !pRender->GetFlag(NF_SEEN)) dMaxCost = policy.pushNode(pRender, y1, y2, false, dMaxCost); // Render children int norm = (myint)GetLongParameter(LP_NORMALIZATION); myint lasty=y1; int id=-1; // int lower=-1,upper=-1; myint temp_parentwidth=y2-y1; int temp_parentcolor = pRender->getColour(); const myint Range(y2 - y1); if (CDasherNode *pChild = pRender->onlyChildRendered) { //if child still covers screen, render _just_ it and return myint newy1 = y1 + (Range * (myint)pChild->Lbnd()) / (myint)norm; myint newy2 = y1 + (Range * (myint)pChild->Hbnd()) / (myint)norm; if (newy1 < iDasherMinY && newy2 > iDasherMaxY) { //still covers entire screen. Parent should too... DASHER_ASSERT(dMaxCost == std::numeric_limits<double>::infinity()); //don't inc iDepth, meaningless when covers the screen RecursiveRender(pChild, newy1, newy2, mostleft, policy, dMaxCost, temp_parentwidth, temp_parentcolor, iDepth); //leave pRender->onlyChildRendered set, so remaining children are skipped } else pRender->onlyChildRendered = NULL; } if (!pRender->onlyChildRendered) { //render all children... for(CDasherNode::ChildMap::const_iterator i = pRender->GetChildren().begin(); i != pRender->GetChildren().end(); i++) { id++; CDasherNode *pChild = *i; myint newy1 = y1 + (Range * (myint)pChild->Lbnd()) / (myint)norm;/// norm and lbnd are simple ints myint newy2 = y1 + (Range * (myint)pChild->Hbnd()) / (myint)norm; if (newy1 < iDasherMinY && newy2 > iDasherMaxY) { DASHER_ASSERT(dMaxCost == std::numeric_limits<double>::infinity()); pRender->onlyChildRendered = pChild; RecursiveRender(pChild, newy1, newy2, mostleft, policy, dMaxCost, temp_parentwidth, temp_parentcolor, iDepth); //ensure we don't blank over this child in "finishing off" the parent (!) lasty=newy2; break; //no need to render any more children! } if (CheckRender(pChild, newy1, newy2, mostleft, policy, dMaxCost, temp_parentwidth, temp_parentcolor, iDepth+1)) { if (lasty<newy1) { //if child has been drawn then the interval between him and the //last drawn child should be drawn too. //std::cout << "Fill in: " << lasty << " " << newy1 << std::endl; RenderNodePartFast(temp_parentcolor, lasty, newy1, mostleft, pRender->getDisplayText(), pRender->bShove(), temp_parentwidth); } lasty = newy2; } } // Finish off the drawing process // if(iDepth == 1) { // Theres a chance that we haven't yet filled the entire parent, so finish things off if necessary. if(lasty<y2) { RenderNodePartFast(temp_parentcolor, lasty, y2, mostleft, pRender->getDisplayText(), pRender->bShove(), temp_parentwidth); } } // Draw the outline if(pRender->getColour() != -1) {//-1 = invisible RenderNodeOutlineFast(pRender->getColour(), y1, y2, mostleft, pRender->getDisplayText(), pRender->bShove()); } // } } bool CDasherViewSquare::IsSpaceAroundNode(myint y1, myint y2) { myint iDasherMinX; myint iDasherMinY; myint iDasherMaxX; myint iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); return ((y2 - y1) < iDasherMaxX) || (y1 > iDasherMinY) || (y2 < iDasherMaxY); } // Draw the outline of a node int CDasherViewSquare::RenderNodeOutlineFast(const int Color, myint y1, myint y2, int &mostleft, const std::string &sDisplayText, bool bShove) { // Commenting because click mode occasionally fails this assert. // I don't know why. -- cjb. if (!(y2 >= y1)) { return 1; } // TODO - Get sensible limits here (to allow for non-linearities) myint iDasherMinX; myint iDasherMinY; myint iDasherMaxX; myint iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); screenint iScreenX1; screenint iScreenY1; screenint iScreenX2; screenint iScreenY2; Dasher2Screen(0, std::max(y1, iDasherMinY), iScreenX1, iScreenY1); Dasher2Screen(0, std::min(y2, iDasherMaxY), iScreenX2, iScreenY2); Cint32 iHeight = std::max(myint(iScreenY2 - iScreenY1),myint( 0)); Cint32 iWidth = std::max(myint(iScreenX2 - iScreenX1),myint( 0)); if((iHeight <= 1) && (iWidth <= 1)) return 0; // We're too small to render if((y1 > iDasherMaxY) || (y2 < iDasherMinY)){ return 0; // We're entirely off screen, so don't render. } // TODO: This should be earlier? if(!GetBoolParameter(BP_OUTLINE_MODE)) return 1; myint iDasherSize(y2 - y1); // std::cout << std::min(iDasherSize,iDasherMaxX) << " " << std::min(y2,iDasherMaxY) << " 0 " << std::max(y1,iDasherMinY) << std::endl; DasherDrawRectangle(0, std::min(y1,iDasherMaxY),std::min(iDasherSize,iDasherMaxX), std::max(y2,iDasherMinY), -1, Color, Nodes1, 1); // // FIXME - get rid of pointless assignment below // int iTruncation(GetLongParameter(LP_TRUNCATION)); // Trucation farction times 100; // if(iTruncation == 0) { // Regular squares // } // else { // // TODO: Put something back here? // } return 1; } // Draw a filled block of a node right down to the baseline (intended // for the case when you have no visible child) int CDasherViewSquare::RenderNodePartFast(const int Color, myint y1, myint y2, int &mostleft, const std::string &sDisplayText, bool bShove,myint iParentWidth ) { // Commenting because click mode occasionally fails this assert. // I don't know why. -- cjb. if (!(y2 >= y1)) { return 1; } // TODO - Get sensible limits here (to allow for non-linearities) myint iDasherMinX; myint iDasherMinY; myint iDasherMaxX; myint iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); screenint iScreenX1; screenint iScreenY1; screenint iScreenX2; screenint iScreenY2; Dasher2Screen(0, std::max(y1, iDasherMinY), iScreenX1, iScreenY1); Dasher2Screen(0, std::min(y2, iDasherMaxY), iScreenX2, iScreenY2); // std::cout << "Fill in components: " << iScreenY1 << " " << iScreenY2 << std::endl; Cint32 iHeight = std::max(myint(iScreenY2 - iScreenY1),myint( 0)); Cint32 iWidth = std::max(myint(iScreenX2 - iScreenX1),myint( 0)); if((iHeight < 1) && (iWidth < 1)) { // std::cout << "b" << std::endl; return 0; // We're too small to render } if((y1 > iDasherMaxY) || (y2 < iDasherMinY)){ //std::cout << "a" << std::endl; return 0; // We're entirely off screen, so don't render. } DasherDrawRectangle(std::min(iParentWidth,iDasherMaxX), std::min(y2,iDasherMaxY),0, std::max(y1,iDasherMinY), Color, -1, Nodes1, 0); return 1; } /// Convert screen co-ordinates to dasher co-ordinates. This doesn't /// include the nonlinear mapping for eyetracking mode etc - it is /// just the inverse of the mapping used to calculate the screen /// positions of boxes etc. void CDasherViewSquare::Screen2Dasher(screenint iInputX, screenint iInputY, myint &iDasherX, myint &iDasherY) { // Things we're likely to need: //myint iDasherWidth = (myint)GetLongParameter(LP_MAX_Y); myint iDasherHeight = (myint)GetLongParameter(LP_MAX_Y); screenint iScreenWidth = Screen()->GetWidth(); screenint iScreenHeight = Screen()->GetHeight(); int eOrientation(GetLongParameter(LP_REAL_ORIENTATION)); switch(eOrientation) { case Dasher::Opts::LeftToRight: iDasherX = iCenterX - ( iInputX - iScreenWidth / 2 ) * m_iScalingFactor / iScaleFactorX; iDasherY = iDasherHeight / 2 + ( iInputY - iScreenHeight / 2 ) * m_iScalingFactor / iScaleFactorY; break; case Dasher::Opts::RightToLeft: iDasherX = myint(iCenterX + ( iInputX - iScreenWidth / 2 ) * m_iScalingFactor/ iScaleFactorX); iDasherY = myint(iDasherHeight / 2 + ( iInputY - iScreenHeight / 2 ) * m_iScalingFactor/ iScaleFactorY); break; case Dasher::Opts::TopToBottom: iDasherX = myint(iCenterX - ( iInputY - iScreenHeight / 2 ) * m_iScalingFactor/ iScaleFactorY); iDasherY = myint(iDasherHeight / 2 + ( iInputX - iScreenWidth / 2 ) * m_iScalingFactor/ iScaleFactorX); break; case Dasher::Opts::BottomToTop: iDasherX = myint(iCenterX + ( iInputY - iScreenHeight / 2 ) * m_iScalingFactor/ iScaleFactorY); iDasherY = myint(iDasherHeight / 2 + ( iInputX - iScreenWidth / 2 ) * m_iScalingFactor/ iScaleFactorX); break; } iDasherX = ixmap(iDasherX); iDasherY = iymap(iDasherY); } void CDasherViewSquare::SetScaleFactor( void ) { //Parameters for X non-linearity. // Set some defaults here, in case we change(d) them later... m_dXmpb = 0.5; //threshold: DasherX's less than (m_dXmpb * MAX_Y) are linear... m_dXmpc = 0.9; //...but multiplied by m_dXmpc; DasherX's above that, are logarithmic... //set log scaling coefficient (unused if LP_NONLINEAR_X==0) // note previous value of m_dXmpa = 0.2, i.e. a value of LP_NONLINEAR_X =~= 4.8 m_dXmpa = exp(GetLongParameter(LP_NONLINEAR_X)/-3.0); myint iDasherWidth = (myint)GetLongParameter(LP_MAX_Y); myint iDasherHeight = iDasherWidth; screenint iScreenWidth = Screen()->GetWidth(); screenint iScreenHeight = Screen()->GetHeight(); // Try doing this a different way: myint iDasherMargin( GetLongParameter(LP_MARGIN_WIDTH) ); // Make this a parameter myint iMinX( 0-iDasherMargin ); myint iMaxX( iDasherWidth ); iCenterX = (iMinX + iMaxX)/2; myint iMinY( 0 ); myint iMaxY( iDasherHeight ); Dasher::Opts::ScreenOrientations eOrientation(Dasher::Opts::ScreenOrientations(GetLongParameter(LP_REAL_ORIENTATION))); double dScaleFactorX, dScaleFactorY; if (eOrientation == Dasher::Opts::LeftToRight || eOrientation == Dasher::Opts::RightToLeft) { dScaleFactorX = iScreenWidth / static_cast<double>( iMaxX - iMinX ); dScaleFactorY = iScreenHeight / static_cast<double>( iMaxY - iMinY ); } else { dScaleFactorX = iScreenHeight / static_cast<double>( iMaxX - iMinX ); dScaleFactorY = iScreenWidth / static_cast<double>( iMaxY - iMinY ); } if (dScaleFactorX < dScaleFactorY) { //fewer (pixels per dasher coord) in X direction - i.e., X is more compressed. //So, use X scale for Y too...except first, we'll _try_ to reduce the difference // by changing the relative scaling of X and Y (by at most 20%): double dMul = max(0.8, dScaleFactorX / dScaleFactorY); m_dXmpc *= dMul; dScaleFactorX /= dMul; iScaleFactorX = myint(dScaleFactorX * m_iScalingFactor); iScaleFactorY = myint(std::max(dScaleFactorX, dScaleFactorY / 4.0) * m_iScalingFactor); } else { //X has more room; use Y scale for both -> will get lots history iScaleFactorX = myint(std::max(dScaleFactorY, dScaleFactorX / 4.0) * m_iScalingFactor); iScaleFactorY = myint(dScaleFactorY * m_iScalingFactor); // however, "compensate" by relaxing the default "relative scaling" of X // (normally only 90% of Y) towards 1... m_dXmpc = std::min(1.0,0.9 * dScaleFactorX / dScaleFactorY); } iCenterX *= m_dXmpc; } inline myint CDasherViewSquare::CustomIDiv(myint iNumerator, myint iDenominator) { // Integer division rounding away from zero long long int num, denom, quot, rem; myint res; num = iNumerator; denom = iDenominator; DASHER_ASSERT(denom != 0); #ifdef HAVE_LLDIV lldiv_t ans = ::lldiv(num, denom); quot = ans.quot; rem = ans.rem; #else quot = num / denom; rem = num % denom; #endif if (rem < 0) res = quot - 1; else if (rem > 0) res = quot + 1; else diff --git a/Src/DasherCore/Event.h b/Src/DasherCore/Event.h index 2194ceb..7be63bd 100644 --- a/Src/DasherCore/Event.h +++ b/Src/DasherCore/Event.h @@ -1,170 +1,170 @@ #ifndef __event_h__ #define __event_h__ // Classes representing different event types. #include <string> #include "DasherTypes.h" namespace Dasher { class CEvent; - class CTextdrawEvent; + class CTextDrawEvent; class CParameterNotificationEvent; class CEditEvent; class CEditContextEvent; class CStartEvent; class CStopEvent; class CControlEvent; class CLockEvent; class CMessageEvent; class CCommandEvent; } enum { EV_PARAM_NOTIFY = 1, EV_EDIT, EV_EDIT_CONTEXT, EV_START, EV_STOP, EV_CONTROL, EV_LOCK, EV_MESSAGE, EV_COMMAND, EV_TEXTDRAW }; /// \ingroup Core /// @{ /// \defgroup Events Events generated by Dasher modules. /// @{ class Dasher::CEvent { public: int m_iEventType; }; class Dasher::CParameterNotificationEvent:public Dasher::CEvent { public: CParameterNotificationEvent(int iParameter) { m_iEventType = EV_PARAM_NOTIFY; m_iParameter = iParameter; }; int m_iParameter; }; class Dasher::CEditEvent:public Dasher::CEvent { public: CEditEvent(int iEditType, const std::string & sText, int iOffset) { m_iEventType = EV_EDIT; m_iEditType = iEditType; m_sText = sText; m_iOffset = iOffset; }; int m_iEditType; std::string m_sText; int m_iOffset; }; class Dasher::CEditContextEvent:public Dasher::CEvent { public: CEditContextEvent(int iOffset, int iLength) { m_iEventType = EV_EDIT_CONTEXT; m_iOffset = iOffset; m_iLength = iLength; }; int m_iOffset; int m_iLength; }; /** * An event that signals text has been drawn. Useful for determining its location * because that information is only available at draw time. */ class Dasher::CTextDrawEvent : public Dasher::CEvent { public: CTextDrawEvent(std::string sDisplayText, screenint iX, screenint iY, int iSize) :m_sDisplayText(sDisplayText), m_iX(iX), m_iY(iY), m_iSize(iSize) { }; /** * The text that has been drawn. */ std::string m_sDisplayText; /** * The X position (in screen coordinates) of the center of the box surrounding the text. */ screenint m_iX; /** * The Y position (in screen coordinates) of the center of the box surrounding the text. */ screenint m_iY; /** * The size of the text. Useful for determining the boundaries of the text "box" */ int m_iSize; }; class Dasher::CStartEvent:public Dasher::CEvent { public: CStartEvent() { m_iEventType = EV_START; }; }; class Dasher::CStopEvent:public Dasher::CEvent { public: CStopEvent() { m_iEventType = EV_STOP; }; }; class Dasher::CControlEvent:public Dasher::CEvent { public: CControlEvent(int iID) { m_iEventType = EV_CONTROL; m_iID = iID; }; int m_iID; }; class Dasher::CLockEvent : public Dasher::CEvent { public: CLockEvent(const std::string &strMessage, bool bLock, int iPercent) { m_iEventType = EV_LOCK; m_strMessage = strMessage; m_bLock = bLock; m_iPercent = iPercent; }; std::string m_strMessage; bool m_bLock; int m_iPercent; }; class Dasher::CMessageEvent : public Dasher::CEvent { public: CMessageEvent(const std::string &strMessage, int iID, int iType) { m_iEventType = EV_MESSAGE; m_strMessage = strMessage; m_iID = iID; m_iType = iType; }; std::string m_strMessage; int m_iID; int m_iType; }; class Dasher::CCommandEvent : public Dasher::CEvent { public: CCommandEvent(const std::string &strCommand) { m_iEventType = EV_COMMAND; m_strCommand = strCommand; }; std::string m_strCommand; }; /// @} /// @} #endif diff --git a/Src/DasherCore/FileWordGenerator.cpp b/Src/DasherCore/FileWordGenerator.cpp index 833685e..f359a81 100644 --- a/Src/DasherCore/FileWordGenerator.cpp +++ b/Src/DasherCore/FileWordGenerator.cpp @@ -1,31 +1,33 @@ #include "FileWordGenerator.h" +using namespace Dasher; + bool CFileWordGenerator::Generate() { if(!m_bWordsReady) { ifstream file_in; - file_in.open(path.c_str()); + file_in.open(m_sPath.c_str()); char buffer; while(file_in.good()) { - buffer = file_in.get(); - m_sGeneratedString.append(buffer); + file_in.get(buffer); + m_sGeneratedString.append(&buffer); } m_uiPos = 0; } } std::string CFileWordGenerator::GetPath() { return m_sPath; } std::string CFileWordGenerator::GetFilename() { return m_sPath.substr(m_sPath.rfind("/")); } void CFileWordGenerator::SetSource(std::string newPath) { m_sPath = newPath; m_bWordsReady = false; Generate(); } -virtual std::string CFileWordGenerator::GetNextWord() { +std::string CFileWordGenerator::GetNextWord() { return m_sGeneratedString.substr(m_uiPos, m_sGeneratedString.find(" ")); } diff --git a/Src/DasherCore/FileWordGenerator.h b/Src/DasherCore/FileWordGenerator.h index d17e959..1d5eee5 100644 --- a/Src/DasherCore/FileWordGenerator.h +++ b/Src/DasherCore/FileWordGenerator.h @@ -1,59 +1,59 @@ #include <string> -#include <iostream.h> -#include <fstream.h> +#include <iostream> +#include <fstream> using namespace std; #include "WordGeneratorBase.h" namespace Dasher { class CFileWordGenerator : public CWordGeneratorBase { public: CFileWordGenerator(std::string path, int regen) : CWordGeneratorBase(regen) { } /** * The generator function. In this implementation, it reads from a file to produce strings. * @see CWordGeneratorBase::Generate */ virtual bool Generate(); /** * Returns the next word that was read */ virtual std::string GetNextWord(); /** * File path getter * @return The path to the file this generator reads from. */ std::string GetPath(); /** * File name getter * @return The actual name of the file being read from */ std::string GetFilename(); /** * Sets the source file this generator reads from. * @warning This method regenerates the model and gets rid of the old data. * @param newPath The path to the file to load from. */ void SetSource(std::string newPath); -prviate: +private: /** * The string that has been generated. */ - std::string m_sGeneratedString + std::string m_sGeneratedString; /** * The path to the file this generator reads from. */ std::string m_sPath; /** * The position we're currently reading from in the string. */ size_t m_uiPos; }; } diff --git a/Src/DasherCore/GameModule.cpp b/Src/DasherCore/GameModule.cpp index 24e7295..6ef7ca2 100644 --- a/Src/DasherCore/GameModule.cpp +++ b/Src/DasherCore/GameModule.cpp @@ -1,58 +1,61 @@ #include "GameModule.h" using namespace Dasher; void CGameModule::HandleEvent(Dasher::CEvent *pEvent) { switch(pEvent->m_iEventType) { case EV_EDIT: - - g_pLogger->Log("Capturing an edit event"); - CEditEvent* evt = static_cast<CEditEvent*>(pEvent); + { + g_pLogger->Log("Capturing an edit event"); + CEditEvent* evt = static_cast<CEditEvent*>(pEvent); switch(evt->m_iEditType) { // Added a new character (Stepped one node forward) case 0: m_stCurrentStringPos++; - pLastTypedNode = StringToNode(evt->m_sText); + //pLastTypedNode = StringToNode(evt->m_sText); break; // Removed a character (Stepped one node back) case 1: break; default: break; } break; + } case EV_TEXTDRAW: - CTextDrawEvent* evt = static_cast<CTextDrawEvent*>(pEvent); - if(!m_sTargetString[m_stCurrentStringPos + 1].compare(evt->m_sDisplayText)) { - myint X, Y; - - m_pView->DasherPolyarrow(Screen2Dasher(evt->m_iX, evt->m_iY, X, Y)); - DasherPolyarrow(X, Y, 20, GetLongParameter(LP_LINE_WIDTH)*4 135); + { + CTextDrawEvent *evt = static_cast<CTextDrawEvent*>(pEvent); + if(!m_sTargetString.substr(m_stCurrentStringPos+1, 1).compare(evt->m_sDisplayText)) { + m_pInterface->m_pDasherView->Screen2Dasher(evt->m_iX, evt->m_iY, m_iTargetX, m_iTargetY); + } } break; default: break; } return; - } +} +bool CGameModule::DecorateView(CDasherView *pView) { + pView->DasherPolyarrow(&m_iTargetX, &m_iTargetY, 20, GetLongParameter(LP_LINE_WIDTH)*4, 135); + return true; } //CDasherNode CGameModule::StringToNode(std::string sText) { // //} std::string CGameModule::GetTypedTarget() { return m_sTargetString.substr(0, m_stCurrentStringPos - 1); } -std::string CGameModule::GetUntypedtarget() { +std::string CGameModule::GetUntypedTarget() { return m_sTargetString.substr(m_stCurrentStringPos); } diff --git a/Src/DasherCore/GameModule.h b/Src/DasherCore/GameModule.h index 089a67c..82bb623 100644 --- a/Src/DasherCore/GameModule.h +++ b/Src/DasherCore/GameModule.h @@ -1,106 +1,115 @@ // GameModule.h #ifndef GAME_MODULE_H #define GAME_MODULE_H #include <string> +#include <cstring> using namespace std; #include "DasherView.h" #include "DasherModel.h" #include "DasherModule.h" #include "DasherNode.h" #include "DasherView.h" #include "DasherTypes.h" +#include "DasherInterfaceBase.h" namespace Dasher { /** * This Dasher Module encapsulates all game mode logic. In game mode, users will be given * a target string to type as well as visual feedback for their progress and a helpful * arrow to guide them in the right path through the dasher model. * * This class handles logic and drawing code with respect to the above. */ class CGameModule : public CDasherModule { public: // I don't actually know what the type is supposed to be for this...it's not an input method or an input filter. // Maybe we should define a new one. I've labeled it 0 for now. - rgee CGameModule(Dasher::CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CDasherInterfaceBase *pInterface, ModuleID_t iID, const char *szName) : CDasherModule(pEventHandler, pSettingsStore, iID, 0, szName) { g_pLogger->Log("Inside game module constructor"); m_pInterface = pInterface; } virtual ~CGameModule() {}; /** * Gets the typed portion of the target string * @return The string that represents the current word(s) that have not been typed */ std::string GetTypedTarget(); /** * Gets the portion of the target string that has yet to be completed * @return The string that represents the current word(s) that have been typed */ std::string GetUntypedTarget(); - bool DecorateView(CDasherView *pView) { - //g_pLogger->Log("Decorating the view"); - return false; - } + bool DecorateView(CDasherView *pView); void SetDasherModel(CDasherModel *pModel) { m_pModel = pModel; } /** * Handle events from the event processing system * @param pEvent The event to be processed. */ virtual void HandleEvent(Dasher::CEvent *pEvent); private: /** * Searches for the dasher node under the current root that represents the desired string * @param text The string to search for * @return The node representing the string parameter */ //Dasher::CDasherNode StringToNode(std::string sText); /** * The last node the user typed. */ CDasherNode *pLastTypedNode; /** * The next node (character) the user must type. */ CDasherNode *pNextTargetNode; /** * The target string the user must type. */ std::string m_sTargetString; /** * The current position in the string. * Stored as a size_t to easily use substrings to determine what's been typed and what hasn't. */ size_t m_stCurrentStringPos; /** * The dasher model. */ CDasherModel *m_pModel; /** * The dasher interface. */ CDasherInterfaceBase *m_pInterface; + + /** + * The target x coordinate for the arrow to point to. + */ + myint m_iTargetX; + + /** + * The target y coordinate for the arrow to point to. + */ + myint m_iTargetY; }; } #endif diff --git a/Src/DasherCore/Makefile.am b/Src/DasherCore/Makefile.am index 4bd4363..c8c91c4 100644 --- a/Src/DasherCore/Makefile.am +++ b/Src/DasherCore/Makefile.am @@ -1,169 +1,169 @@ SUBDIRS = LanguageModelling noinst_LIBRARIES = libdashercore.a libdasherprefs.a libdasherprefs_a_SOURCES = \ Parameters.h \ SettingsStore.cpp \ SettingsStore.h libdashercore_a_SOURCES = \ Alphabet/AlphIO.cpp \ Alphabet/AlphIO.h \ Alphabet/Alphabet.cpp \ Alphabet/Alphabet.h \ Alphabet/AlphabetMap.cpp \ Alphabet/AlphabetMap.h \ Alphabet/GroupInfo.h \ AlternatingDirectMode.cpp \ AlternatingDirectMode.h \ ActionButton.cpp \ ActionButton.h \ AlphabetManager.cpp \ AlphabetManager.h \ AutoSpeedControl.cpp \ AutoSpeedControl.h \ BasicLog.cpp \ BasicLog.h \ ButtonMode.cpp \ ButtonMode.h \ ButtonMultiPress.h \ ButtonMultiPress.cpp \ CircleStartHandler.cpp \ CircleStartHandler.h \ ClickFilter.cpp \ ClickFilter.h \ ColourIO.cpp \ ColourIO.h \ CompassMode.cpp \ CompassMode.h \ ControlManager.cpp \ ControlManager.h \ ConversionHelper.cpp \ ConversionHelper.h \ ConversionManager.cpp \ ConversionManager.h \ DasherButtons.cpp \ DasherButtons.h \ DasherComponent.cpp \ DasherComponent.h \ DasherGameMode.cpp \ DasherGameMode.h \ DasherInput.h \ DasherInterfaceBase.cpp \ DasherInterfaceBase.h \ DasherModel.cpp \ DasherModel.h \ DasherModule.cpp \ DasherModule.h \ DasherNode.cpp \ DasherNode.h \ DasherScreen.h \ DasherTypes.h \ DasherView.cpp \ DasherView.h \ DasherViewSquare.cpp \ DasherViewSquare.h \ DasherViewSquare.inl \ DefaultFilter.cpp \ DefaultFilter.h \ DelayedDraw.cpp \ DelayedDraw.h \ DynamicFilter.h \ DynamicFilter.cpp \ Event.h \ EventHandler.cpp \ EventHandler.h \ EyetrackerFilter.cpp \ EyetrackerFilter.h \ FileLogger.cpp \ FileLogger.h \ - FileWordGenerator.h \ FileWordGenerator.cpp \ + FileWordGenerator.h \ FrameRate.h \ FrameRate.cpp \ GameLevel.cpp \ GameLevel.h \ GameMessages.h \ - GameModule.h \ GameModule.cpp \ + GameModule.h \ GameScorer.cpp \ GameScorer.h \ GameStatistics.h \ GnomeSettingsStore.cpp \ GnomeSettingsStore.h \ InputFilter.h \ MandarinAlphMgr.cpp \ MandarinAlphMgr.h \ MemoryLeak.cpp \ MemoryLeak.h \ ModuleManager.cpp \ ModuleManager.h \ NodeCreationManager.cpp \ NodeCreationManager.h \ ExpansionPolicy.cpp \ ExpansionPolicy.h \ OneButtonDynamicFilter.cpp \ OneButtonDynamicFilter.h \ OneButtonFilter.cpp \ OneButtonFilter.h \ OneDimensionalFilter.cpp \ OneDimensionalFilter.h \ PinyinParser.cpp \ PinyinParser.h \ SCENode.cpp \ SCENode.h \ SimpleTimer.cpp \ SimpleTimer.h \ SocketInput.cpp \ SocketInput.h \ SocketInputBase.cpp \ SocketInputBase.h \ StartHandler.h \ StylusFilter.cpp \ StylusFilter.h \ TimeSpan.cpp \ TimeSpan.h \ Trainer.cpp \ Trainer.h \ TrainingHelper.cpp \ TrainingHelper.h \ TwoBoxStartHandler.cpp \ TwoBoxStartHandler.h \ TwoButtonDynamicFilter.cpp \ TwoButtonDynamicFilter.h \ TwoPushDynamicFilter.cpp \ TwoPushDynamicFilter.h \ UserButton.cpp \ UserButton.h \ UserLocation.cpp \ UserLocation.h \ UserLog.cpp \ UserLog.h \ UserLogBase.h \ UserLogParam.cpp \ UserLogParam.h \ UserLogTrial.cpp \ UserLogTrial.h \ WordGeneratorBase.h \ XMLUtil.cpp \ XMLUtil.h libdashercore_a_LIBADD = @JAPANESE_SOURCES@ libdashercore_a_DEPENDENCIES = @JAPANESE_SOURCES@ EXTRA_libdashercore_a_SOURCES = \ CannaConversionHelper.cpp \ CannaConversionHelper.h AM_CXXFLAGS = -I$(srcdir)/../DasherCore -DPROGDATA=\"$(pkgdatadir)\" -I../../intl -I$(top_srcdir)/intl $(GTK2_CFLAGS) $(SETTINGS_CFLAGS) $(gnome_speech_CFLAGS) $(gnome_a11y_CFLAGS) $(gnome_CFLAGS) EXTRA_DIST = \ LanguageModelling/BigramLanguageModel.cpp \ LanguageModelling/BigramLanguageModel.h \ LanguageModelling/KanjiConversionIME.cpp \ LanguageModelling/KanjiConversionIME.h \ DasherCore.vcproj \ DasherCore_vc80.vcproj \ IMEConversionHelper.cpp \ IMEConversionHelper.h
rgee/HFOSS-Dasher
4d0ae96847211396e671cc8d60cbdca250b10425
Gave TextDraw events a pointer to the view
diff --git a/Src/DasherCore/DasherViewSquare.cpp b/Src/DasherCore/DasherViewSquare.cpp index bb963e5..d60dee3 100644 --- a/Src/DasherCore/DasherViewSquare.cpp +++ b/Src/DasherCore/DasherViewSquare.cpp @@ -1,728 +1,728 @@ // DasherViewSquare.cpp // // Copyright (c) 2008 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" #ifdef _WIN32 #include "..\Win32\Common\WinCommon.h" #endif //#include "DasherGameMode.h" #include "DasherViewSquare.h" #include "DasherModel.h" #include "DasherView.h" #include "DasherTypes.h" #include "Event.h" #include "EventHandler.h" #include <algorithm> #include <iostream> #include <limits> #include <stdlib.h> using namespace Dasher; using namespace Opts; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG_MEMLEAKS #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif // FIXME - quite a lot of the code here probably should be moved to // the parent class (DasherView). I think we really should make the // parent class less general - we're probably not going to implement // anything which uses radically different co-ordinate transforms, and // we can always override if necessary. // FIXME - duplicated 'mode' code throught - needs to be fixed (actually, mode related stuff, Input2Dasher etc should probably be at least partially in some other class) CDasherViewSquare::CDasherViewSquare(CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CDasherScreen *DasherScreen) : CDasherView(pEventHandler, pSettingsStore, DasherScreen), m_Y1(4), m_Y2(0.95 * GetLongParameter(LP_MAX_Y)), m_Y3(0.05 * GetLongParameter((LP_MAX_Y))) { // TODO - AutoOffset should be part of the eyetracker input filter // Make sure that the auto calibration is set to zero berfore we start // m_yAutoOffset = 0; ChangeScreen(DasherScreen); //Note, nonlinearity parameters set in SetScaleFactor m_bVisibleRegionValid = false; } CDasherViewSquare::~CDasherViewSquare() {} void CDasherViewSquare::HandleEvent(Dasher::CEvent *pEvent) { // Let the parent class do its stuff CDasherView::HandleEvent(pEvent); // And then interpret events for ourself if(pEvent->m_iEventType == 1) { Dasher::CParameterNotificationEvent * pEvt(static_cast < Dasher::CParameterNotificationEvent * >(pEvent)); switch (pEvt->m_iParameter) { case LP_REAL_ORIENTATION: case LP_MARGIN_WIDTH: case BP_NONLINEAR_Y: case LP_NONLINEAR_X: m_bVisibleRegionValid = false; SetScaleFactor(); break; default: break; } } } /// Draw text specified in Dasher co-ordinates. The position is /// specified as two co-ordinates, intended to the be the corners of /// the leading edge of the containing box. void CDasherViewSquare::DasherDrawText(myint iAnchorX1, myint iAnchorY1, myint iAnchorX2, myint iAnchorY2, const std::string &sDisplayText, int &mostleft, bool bShove) { // Don't draw text which will overlap with text in an ancestor. if(iAnchorX1 > mostleft) iAnchorX1 = mostleft; if(iAnchorX2 > mostleft) iAnchorX2 = mostleft; myint iDasherMinX; myint iDasherMinY; myint iDasherMaxX; myint iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); iAnchorY1 = std::min( iDasherMaxY, std::max( iDasherMinY, iAnchorY1 ) ); iAnchorY2 = std::min( iDasherMaxY, std::max( iDasherMinY, iAnchorY2 ) ); screenint iScreenAnchorX1; screenint iScreenAnchorY1; screenint iScreenAnchorX2; screenint iScreenAnchorY2; // FIXME - Truncate here before converting - otherwise we risk integer overflow in screen coordinates Dasher2Screen(iAnchorX1, iAnchorY1, iScreenAnchorX1, iScreenAnchorY1); Dasher2Screen(iAnchorX2, iAnchorY2, iScreenAnchorX2, iScreenAnchorY2); // Truncate the ends of the anchor line to be on the screen - this // prevents us from loosing characters off the top and bottom of the // screen // TruncateToScreen(iScreenAnchorX1, iScreenAnchorY1); // TruncateToScreen(iScreenAnchorX2, iScreenAnchorY2); // Actual anchor point is the midpoint of the anchor line screenint iScreenAnchorX((iScreenAnchorX1 + iScreenAnchorX2) / 2); screenint iScreenAnchorY((iScreenAnchorY1 + iScreenAnchorY2) / 2); // Compute font size based on position int Size = GetLongParameter( LP_DASHER_FONTSIZE ); // FIXME - this could be much more elegant, and probably needs a // rethink anyway - behvaiour here is too dependent on screen size screenint iLeftTimesFontSize = ((myint)GetLongParameter(LP_MAX_Y) - (iAnchorX1 + iAnchorX2)/ 2 )*Size; if(iLeftTimesFontSize < (myint)GetLongParameter(LP_MAX_Y) * 19/ 20) Size *= 20; else if(iLeftTimesFontSize < (myint)GetLongParameter(LP_MAX_Y) * 159 / 160) Size *= 14; else Size *= 11; screenint TextWidth, TextHeight; Screen()->TextSize(sDisplayText, &TextWidth, &TextHeight, Size); // Poistion of text box relative to anchor depends on orientation screenint newleft2 = 0; screenint newtop2 = 0; screenint newright2 = 0; screenint newbottom2 = 0; switch (Dasher::Opts::ScreenOrientations(GetLongParameter(LP_REAL_ORIENTATION))) { case (Dasher::Opts::LeftToRight): newleft2 = iScreenAnchorX; newtop2 = iScreenAnchorY - TextHeight / 2; newright2 = iScreenAnchorX + TextWidth; newbottom2 = iScreenAnchorY + TextHeight / 2; break; case (Dasher::Opts::RightToLeft): newleft2 = iScreenAnchorX - TextWidth; newtop2 = iScreenAnchorY - TextHeight / 2; newright2 = iScreenAnchorX; newbottom2 = iScreenAnchorY + TextHeight / 2; break; case (Dasher::Opts::TopToBottom): newleft2 = iScreenAnchorX - TextWidth / 2; newtop2 = iScreenAnchorY; newright2 = iScreenAnchorX + TextWidth / 2; newbottom2 = iScreenAnchorY + TextHeight; break; case (Dasher::Opts::BottomToTop): newleft2 = iScreenAnchorX - TextWidth / 2; newtop2 = iScreenAnchorY - TextHeight; newright2 = iScreenAnchorX + TextWidth / 2; newbottom2 = iScreenAnchorY; break; default: break; } // Update the value of mostleft to take into account the new text if(bShove) { myint iDasherNewLeft; myint iDasherNewTop; myint iDasherNewRight; myint iDasherNewBottom; Screen2Dasher(newleft2, newtop2, iDasherNewLeft, iDasherNewTop); Screen2Dasher(newright2, newbottom2, iDasherNewRight, iDasherNewBottom); mostleft = std::min(iDasherNewRight, iDasherNewLeft); } // Tell other listeners that text has been drawn and provide some information // about the draw call. - m_pEventHandler->InsertEvent(new CTextDrawEvent(sDisplaytext, newleft2, newtop2, Size)); + m_pEventHandler->InsertEvent(new CTextDrawEvent(sDisplaytext,this, newleft2, newtop2, Size)); // Actually draw the text. We use DelayDrawText as the text should // be overlayed once all of the boxes have been drawn. m_DelayDraw.DelayDrawText(sDisplayText, newleft2, newtop2, Size); } void CDasherViewSquare::RenderNodes(CDasherNode *pRoot, myint iRootMin, myint iRootMax, CExpansionPolicy &policy) { DASHER_ASSERT(pRoot != 0); myint iDasherMinX; myint iDasherMinY; myint iDasherMaxX; myint iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); // screenint iScreenLeft; screenint iScreenTop; screenint iScreenRight; screenint iScreenBottom; Dasher2Screen(iRootMax-iRootMin, iRootMin, iScreenLeft, iScreenTop); Dasher2Screen(0, iRootMax, iScreenRight, iScreenBottom); //ifiScreenTop < 0) // iScreenTop = 0; //if(iScreenLeft < 0) // iScreenLeft=0; //// TODO: Should these be right on the boundary? //if(iScreenBottom > Screen()->GetHeight()) // iScreenBottom=Screen()->GetHeight(); //if(iScreenRight > Screen()->GetWidth()) // iScreenRight=Screen()->GetWidth(); // Blank the region around the root node: if(iRootMin > iDasherMinY) DasherDrawRectangle(iDasherMaxX, iDasherMinY, iDasherMinX, iRootMin, 0, -1, Nodes1, 0); //if(iScreenTop > 0) // Screen()->DrawRectangle(0, 0, Screen()->GetWidth(), iScreenTop, 0, -1, Nodes1, false, true, 1); if(iRootMax < iDasherMaxY) DasherDrawRectangle(iDasherMaxX, iRootMax, iDasherMinX, iDasherMaxY, 0, -1, Nodes1, 0); //if(iScreenBottom <= Screen()->GetHeight()) // Screen()->DrawRectangle(0, iScreenBottom, Screen()->GetWidth(), Screen()->GetHeight(), 0, -1, Nodes1, false, true, 1); DasherDrawRectangle(0, iDasherMinY, iDasherMinX, iDasherMaxY, 0, -1, Nodes1, 0); // Screen()->DrawRectangle(iScreenRight, std::max(0, (int)iScreenTop), // Screen()->GetWidth(), std::min(Screen()->GetHeight(), (int)iScreenBottom), // 0, -1, Nodes1, false, true, 1); // Render the root node (and children) RecursiveRender(pRoot, iRootMin, iRootMax, iDasherMaxX, policy, std::numeric_limits<double>::infinity(), iDasherMaxX,0,0); // Labels are drawn in a second parse to get the overlapping right m_DelayDraw.Draw(Screen()); // Finally decorate the view Crosshair((myint)GetLongParameter(LP_OX)); } //min size in *Dasher co-ordinates* to consider rendering a node #define QUICK_REJECT 50 //min size in *screen* (pixel) co-ordinates to render a node #define MIN_SIZE 2 bool CDasherViewSquare::CheckRender(CDasherNode *pRender, myint y1, myint y2, int mostleft, CExpansionPolicy &policy, double dMaxCost, myint parent_width, int parent_color, int iDepth) { if (y2-y1 >= QUICK_REJECT) { myint iDasherMinX; myint iDasherMinY; myint iDasherMaxX; myint iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); if (y1 <= iDasherMaxY && y2 >= iDasherMinY) { screenint iScreenX1; screenint iScreenY1; screenint iScreenX2; screenint iScreenY2; Dasher2Screen(0, std::max(y1, iDasherMinY), iScreenX1, iScreenY1); Dasher2Screen(0, std::min(y2, iDasherMaxY), iScreenX2, iScreenY2); Cint32 iHeight = std::max(myint(iScreenY2 - iScreenY1),myint( 0)); if (iHeight >= MIN_SIZE) { //node should be rendered! RecursiveRender(pRender, y1, y2, mostleft, policy, dMaxCost, parent_width, parent_color, iDepth); return true; } } } // We get here if the node is too small to render or is off-screen. // So, collapse it immediately. // // In game mode, we get here if the child is too small to draw, but we need the // coordinates - if this is the case then we shouldn't delete any children. // // TODO: Should probably render the parent segment here anyway (or // in the above) if(!pRender->GetFlag(NF_GAME)) pRender->Delete_children(); return false; } void CDasherViewSquare::RecursiveRender(CDasherNode *pRender, myint y1, myint y2, int mostleft, CExpansionPolicy &policy, double dMaxCost, myint parent_width,int parent_color, int iDepth) { DASHER_ASSERT_VALIDPTR_RW(pRender); // if(iDepth == 2) // std::cout << pRender->GetDisplayInfo()->strDisplayText << std::endl; // TODO: We need an overhall of the node creation/deletion logic - // make sure that we only maintain the minimum number of nodes which // are actually needed. This is especially true at the moment in // Game mode, which feels very sluggish. Node creation also feels // slower in Windows than Linux, especially if many nodes are // created at once (eg untrained Hiragana) ++m_iRenderCount; // myint trange = y2 - y1; // Attempt to draw the region to the left of this node inside its parent. // if(iDepth == 2) { // std::cout << "y1: " << y1 << " y2: " << y2 << std::endl; // Set the NF_SUPER flag if this node entirely frames the visual // area. // TODO: too slow? // TODO: use flags more rather than delete/reparent lists myint iDasherMinX; myint iDasherMinY; myint iDasherMaxX; myint iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); DasherDrawRectangle(std::min(parent_width,iDasherMaxX), std::max(y1,iDasherMinY), std::min(y2-y1,iDasherMaxX), std::min(y2,iDasherMaxY), parent_color, -1, Nodes1, 0); const std::string &sDisplayText(pRender->getDisplayText()); if( sDisplayText.size() > 0 ) { DasherDrawText(y2-y1, y1, y2-y1, y2, sDisplayText, mostleft, pRender->bShove()); } pRender->SetFlag(NF_SUPER, !IsSpaceAroundNode(y1,y2)); // If there are no children then we still need to render the parent if(pRender->ChildCount() == 0) { DasherDrawRectangle(std::min(y2-y1,iDasherMaxX), std::min(y2,iDasherMaxY),0, std::max(y1,iDasherMinY), pRender->getColour(), -1, Nodes1, 0); //also allow it to be expanded, it's big enough. policy.pushNode(pRender, y1, y2, true, dMaxCost); return; } //Node has children. It can therefore be collapsed...however, // we don't allow a node covering the crosshair to be collapsed // (at best this'll mean there's nowhere useful to go forwards; // at worst, all kinds of crashes trying to do text output!) if (!pRender->GetFlag(NF_GAME) && !pRender->GetFlag(NF_SEEN)) dMaxCost = policy.pushNode(pRender, y1, y2, false, dMaxCost); // Render children int norm = (myint)GetLongParameter(LP_NORMALIZATION); myint lasty=y1; int id=-1; // int lower=-1,upper=-1; myint temp_parentwidth=y2-y1; int temp_parentcolor = pRender->getColour(); const myint Range(y2 - y1); if (CDasherNode *pChild = pRender->onlyChildRendered) { //if child still covers screen, render _just_ it and return myint newy1 = y1 + (Range * (myint)pChild->Lbnd()) / (myint)norm; myint newy2 = y1 + (Range * (myint)pChild->Hbnd()) / (myint)norm; if (newy1 < iDasherMinY && newy2 > iDasherMaxY) { //still covers entire screen. Parent should too... DASHER_ASSERT(dMaxCost == std::numeric_limits<double>::infinity()); //don't inc iDepth, meaningless when covers the screen RecursiveRender(pChild, newy1, newy2, mostleft, policy, dMaxCost, temp_parentwidth, temp_parentcolor, iDepth); //leave pRender->onlyChildRendered set, so remaining children are skipped } else pRender->onlyChildRendered = NULL; } if (!pRender->onlyChildRendered) { //render all children... for(CDasherNode::ChildMap::const_iterator i = pRender->GetChildren().begin(); i != pRender->GetChildren().end(); i++) { id++; CDasherNode *pChild = *i; myint newy1 = y1 + (Range * (myint)pChild->Lbnd()) / (myint)norm;/// norm and lbnd are simple ints myint newy2 = y1 + (Range * (myint)pChild->Hbnd()) / (myint)norm; if (newy1 < iDasherMinY && newy2 > iDasherMaxY) { DASHER_ASSERT(dMaxCost == std::numeric_limits<double>::infinity()); pRender->onlyChildRendered = pChild; RecursiveRender(pChild, newy1, newy2, mostleft, policy, dMaxCost, temp_parentwidth, temp_parentcolor, iDepth); //ensure we don't blank over this child in "finishing off" the parent (!) lasty=newy2; break; //no need to render any more children! } if (CheckRender(pChild, newy1, newy2, mostleft, policy, dMaxCost, temp_parentwidth, temp_parentcolor, iDepth+1)) { if (lasty<newy1) { //if child has been drawn then the interval between him and the //last drawn child should be drawn too. //std::cout << "Fill in: " << lasty << " " << newy1 << std::endl; RenderNodePartFast(temp_parentcolor, lasty, newy1, mostleft, pRender->getDisplayText(), pRender->bShove(), temp_parentwidth); } lasty = newy2; } } // Finish off the drawing process // if(iDepth == 1) { // Theres a chance that we haven't yet filled the entire parent, so finish things off if necessary. if(lasty<y2) { RenderNodePartFast(temp_parentcolor, lasty, y2, mostleft, pRender->getDisplayText(), pRender->bShove(), temp_parentwidth); } } // Draw the outline if(pRender->getColour() != -1) {//-1 = invisible RenderNodeOutlineFast(pRender->getColour(), y1, y2, mostleft, pRender->getDisplayText(), pRender->bShove()); } // } } bool CDasherViewSquare::IsSpaceAroundNode(myint y1, myint y2) { myint iDasherMinX; myint iDasherMinY; myint iDasherMaxX; myint iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); return ((y2 - y1) < iDasherMaxX) || (y1 > iDasherMinY) || (y2 < iDasherMaxY); } // Draw the outline of a node int CDasherViewSquare::RenderNodeOutlineFast(const int Color, myint y1, myint y2, int &mostleft, const std::string &sDisplayText, bool bShove) { // Commenting because click mode occasionally fails this assert. // I don't know why. -- cjb. if (!(y2 >= y1)) { return 1; } // TODO - Get sensible limits here (to allow for non-linearities) myint iDasherMinX; myint iDasherMinY; myint iDasherMaxX; myint iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); screenint iScreenX1; screenint iScreenY1; screenint iScreenX2; screenint iScreenY2; Dasher2Screen(0, std::max(y1, iDasherMinY), iScreenX1, iScreenY1); Dasher2Screen(0, std::min(y2, iDasherMaxY), iScreenX2, iScreenY2); Cint32 iHeight = std::max(myint(iScreenY2 - iScreenY1),myint( 0)); Cint32 iWidth = std::max(myint(iScreenX2 - iScreenX1),myint( 0)); if((iHeight <= 1) && (iWidth <= 1)) return 0; // We're too small to render if((y1 > iDasherMaxY) || (y2 < iDasherMinY)){ return 0; // We're entirely off screen, so don't render. } // TODO: This should be earlier? if(!GetBoolParameter(BP_OUTLINE_MODE)) return 1; myint iDasherSize(y2 - y1); // std::cout << std::min(iDasherSize,iDasherMaxX) << " " << std::min(y2,iDasherMaxY) << " 0 " << std::max(y1,iDasherMinY) << std::endl; DasherDrawRectangle(0, std::min(y1,iDasherMaxY),std::min(iDasherSize,iDasherMaxX), std::max(y2,iDasherMinY), -1, Color, Nodes1, 1); // // FIXME - get rid of pointless assignment below // int iTruncation(GetLongParameter(LP_TRUNCATION)); // Trucation farction times 100; // if(iTruncation == 0) { // Regular squares // } // else { // // TODO: Put something back here? // } return 1; } // Draw a filled block of a node right down to the baseline (intended // for the case when you have no visible child) int CDasherViewSquare::RenderNodePartFast(const int Color, myint y1, myint y2, int &mostleft, const std::string &sDisplayText, bool bShove,myint iParentWidth ) { // Commenting because click mode occasionally fails this assert. // I don't know why. -- cjb. if (!(y2 >= y1)) { return 1; } // TODO - Get sensible limits here (to allow for non-linearities) myint iDasherMinX; myint iDasherMinY; myint iDasherMaxX; myint iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); screenint iScreenX1; screenint iScreenY1; screenint iScreenX2; screenint iScreenY2; Dasher2Screen(0, std::max(y1, iDasherMinY), iScreenX1, iScreenY1); Dasher2Screen(0, std::min(y2, iDasherMaxY), iScreenX2, iScreenY2); // std::cout << "Fill in components: " << iScreenY1 << " " << iScreenY2 << std::endl; Cint32 iHeight = std::max(myint(iScreenY2 - iScreenY1),myint( 0)); Cint32 iWidth = std::max(myint(iScreenX2 - iScreenX1),myint( 0)); if((iHeight < 1) && (iWidth < 1)) { // std::cout << "b" << std::endl; return 0; // We're too small to render } if((y1 > iDasherMaxY) || (y2 < iDasherMinY)){ //std::cout << "a" << std::endl; return 0; // We're entirely off screen, so don't render. } DasherDrawRectangle(std::min(iParentWidth,iDasherMaxX), std::min(y2,iDasherMaxY),0, std::max(y1,iDasherMinY), Color, -1, Nodes1, 0); return 1; } /// Convert screen co-ordinates to dasher co-ordinates. This doesn't /// include the nonlinear mapping for eyetracking mode etc - it is /// just the inverse of the mapping used to calculate the screen /// positions of boxes etc. void CDasherViewSquare::Screen2Dasher(screenint iInputX, screenint iInputY, myint &iDasherX, myint &iDasherY) { // Things we're likely to need: //myint iDasherWidth = (myint)GetLongParameter(LP_MAX_Y); myint iDasherHeight = (myint)GetLongParameter(LP_MAX_Y); screenint iScreenWidth = Screen()->GetWidth(); screenint iScreenHeight = Screen()->GetHeight(); int eOrientation(GetLongParameter(LP_REAL_ORIENTATION)); switch(eOrientation) { case Dasher::Opts::LeftToRight: iDasherX = iCenterX - ( iInputX - iScreenWidth / 2 ) * m_iScalingFactor / iScaleFactorX; iDasherY = iDasherHeight / 2 + ( iInputY - iScreenHeight / 2 ) * m_iScalingFactor / iScaleFactorY; break; case Dasher::Opts::RightToLeft: iDasherX = myint(iCenterX + ( iInputX - iScreenWidth / 2 ) * m_iScalingFactor/ iScaleFactorX); iDasherY = myint(iDasherHeight / 2 + ( iInputY - iScreenHeight / 2 ) * m_iScalingFactor/ iScaleFactorY); break; case Dasher::Opts::TopToBottom: iDasherX = myint(iCenterX - ( iInputY - iScreenHeight / 2 ) * m_iScalingFactor/ iScaleFactorY); iDasherY = myint(iDasherHeight / 2 + ( iInputX - iScreenWidth / 2 ) * m_iScalingFactor/ iScaleFactorX); break; case Dasher::Opts::BottomToTop: iDasherX = myint(iCenterX + ( iInputY - iScreenHeight / 2 ) * m_iScalingFactor/ iScaleFactorY); iDasherY = myint(iDasherHeight / 2 + ( iInputX - iScreenWidth / 2 ) * m_iScalingFactor/ iScaleFactorX); break; } iDasherX = ixmap(iDasherX); iDasherY = iymap(iDasherY); } void CDasherViewSquare::SetScaleFactor( void ) { //Parameters for X non-linearity. // Set some defaults here, in case we change(d) them later... m_dXmpb = 0.5; //threshold: DasherX's less than (m_dXmpb * MAX_Y) are linear... m_dXmpc = 0.9; //...but multiplied by m_dXmpc; DasherX's above that, are logarithmic... //set log scaling coefficient (unused if LP_NONLINEAR_X==0) // note previous value of m_dXmpa = 0.2, i.e. a value of LP_NONLINEAR_X =~= 4.8 m_dXmpa = exp(GetLongParameter(LP_NONLINEAR_X)/-3.0); myint iDasherWidth = (myint)GetLongParameter(LP_MAX_Y); myint iDasherHeight = iDasherWidth; screenint iScreenWidth = Screen()->GetWidth(); screenint iScreenHeight = Screen()->GetHeight(); // Try doing this a different way: myint iDasherMargin( GetLongParameter(LP_MARGIN_WIDTH) ); // Make this a parameter myint iMinX( 0-iDasherMargin ); myint iMaxX( iDasherWidth ); iCenterX = (iMinX + iMaxX)/2; myint iMinY( 0 ); myint iMaxY( iDasherHeight ); Dasher::Opts::ScreenOrientations eOrientation(Dasher::Opts::ScreenOrientations(GetLongParameter(LP_REAL_ORIENTATION))); double dScaleFactorX, dScaleFactorY; if (eOrientation == Dasher::Opts::LeftToRight || eOrientation == Dasher::Opts::RightToLeft) { dScaleFactorX = iScreenWidth / static_cast<double>( iMaxX - iMinX ); dScaleFactorY = iScreenHeight / static_cast<double>( iMaxY - iMinY ); } else { dScaleFactorX = iScreenHeight / static_cast<double>( iMaxX - iMinX ); dScaleFactorY = iScreenWidth / static_cast<double>( iMaxY - iMinY ); } if (dScaleFactorX < dScaleFactorY) { //fewer (pixels per dasher coord) in X direction - i.e., X is more compressed. //So, use X scale for Y too...except first, we'll _try_ to reduce the difference // by changing the relative scaling of X and Y (by at most 20%): double dMul = max(0.8, dScaleFactorX / dScaleFactorY); m_dXmpc *= dMul; dScaleFactorX /= dMul; iScaleFactorX = myint(dScaleFactorX * m_iScalingFactor); iScaleFactorY = myint(std::max(dScaleFactorX, dScaleFactorY / 4.0) * m_iScalingFactor); } else { //X has more room; use Y scale for both -> will get lots history iScaleFactorX = myint(std::max(dScaleFactorY, dScaleFactorX / 4.0) * m_iScalingFactor); iScaleFactorY = myint(dScaleFactorY * m_iScalingFactor); // however, "compensate" by relaxing the default "relative scaling" of X // (normally only 90% of Y) towards 1... m_dXmpc = std::min(1.0,0.9 * dScaleFactorX / dScaleFactorY); } iCenterX *= m_dXmpc; } inline myint CDasherViewSquare::CustomIDiv(myint iNumerator, myint iDenominator) { // Integer division rounding away from zero long long int num, denom, quot, rem; myint res; num = iNumerator; denom = iDenominator; DASHER_ASSERT(denom != 0); #ifdef HAVE_LLDIV lldiv_t ans = ::lldiv(num, denom); quot = ans.quot; rem = ans.rem; #else quot = num / denom; rem = num % denom; #endif if (rem < 0) res = quot - 1; else if (rem > 0) res = quot + 1; else diff --git a/Src/DasherCore/Event.h b/Src/DasherCore/Event.h index 2194ceb..bedc48f 100644 --- a/Src/DasherCore/Event.h +++ b/Src/DasherCore/Event.h @@ -1,170 +1,176 @@ #ifndef __event_h__ #define __event_h__ // Classes representing different event types. #include <string> #include "DasherTypes.h" namespace Dasher { class CEvent; class CTextdrawEvent; class CParameterNotificationEvent; class CEditEvent; class CEditContextEvent; class CStartEvent; class CStopEvent; class CControlEvent; class CLockEvent; class CMessageEvent; class CCommandEvent; } enum { EV_PARAM_NOTIFY = 1, EV_EDIT, EV_EDIT_CONTEXT, EV_START, EV_STOP, EV_CONTROL, EV_LOCK, EV_MESSAGE, EV_COMMAND, EV_TEXTDRAW }; /// \ingroup Core /// @{ /// \defgroup Events Events generated by Dasher modules. /// @{ class Dasher::CEvent { public: int m_iEventType; }; class Dasher::CParameterNotificationEvent:public Dasher::CEvent { public: CParameterNotificationEvent(int iParameter) { m_iEventType = EV_PARAM_NOTIFY; m_iParameter = iParameter; }; int m_iParameter; }; class Dasher::CEditEvent:public Dasher::CEvent { public: CEditEvent(int iEditType, const std::string & sText, int iOffset) { m_iEventType = EV_EDIT; m_iEditType = iEditType; m_sText = sText; m_iOffset = iOffset; }; int m_iEditType; std::string m_sText; int m_iOffset; }; class Dasher::CEditContextEvent:public Dasher::CEvent { public: CEditContextEvent(int iOffset, int iLength) { m_iEventType = EV_EDIT_CONTEXT; m_iOffset = iOffset; m_iLength = iLength; }; int m_iOffset; int m_iLength; }; /** * An event that signals text has been drawn. Useful for determining its location * because that information is only available at draw time. */ class Dasher::CTextDrawEvent : public Dasher::CEvent { public: - CTextDrawEvent(std::string sDisplayText, screenint iX, screenint iY, int iSize) + CTextDrawEvent(std::string sDisplayText, CDasherView pView, screenint iX, screenint iY, int iSize) :m_sDisplayText(sDisplayText), + m_pDasherView(pView), m_iX(iX), m_iY(iY), m_iSize(iSize) { }; /** * The text that has been drawn. */ std::string m_sDisplayText; + /** + * The dasher view that emitted this event. + */ + CDasherView* m_pDasherView; + /** * The X position (in screen coordinates) of the center of the box surrounding the text. */ screenint m_iX; /** * The Y position (in screen coordinates) of the center of the box surrounding the text. */ screenint m_iY; /** * The size of the text. Useful for determining the boundaries of the text "box" */ int m_iSize; }; class Dasher::CStartEvent:public Dasher::CEvent { public: CStartEvent() { m_iEventType = EV_START; }; }; class Dasher::CStopEvent:public Dasher::CEvent { public: CStopEvent() { m_iEventType = EV_STOP; }; }; class Dasher::CControlEvent:public Dasher::CEvent { public: CControlEvent(int iID) { m_iEventType = EV_CONTROL; m_iID = iID; }; int m_iID; }; class Dasher::CLockEvent : public Dasher::CEvent { public: CLockEvent(const std::string &strMessage, bool bLock, int iPercent) { m_iEventType = EV_LOCK; m_strMessage = strMessage; m_bLock = bLock; m_iPercent = iPercent; }; std::string m_strMessage; bool m_bLock; int m_iPercent; }; class Dasher::CMessageEvent : public Dasher::CEvent { public: CMessageEvent(const std::string &strMessage, int iID, int iType) { m_iEventType = EV_MESSAGE; m_strMessage = strMessage; m_iID = iID; m_iType = iType; }; std::string m_strMessage; int m_iID; int m_iType; }; class Dasher::CCommandEvent : public Dasher::CEvent { public: CCommandEvent(const std::string &strCommand) { m_iEventType = EV_COMMAND; m_strCommand = strCommand; }; std::string m_strCommand; }; /// @} /// @} #endif
rgee/HFOSS-Dasher
428970066a96bf0d87e49bf408fb2fbcac96d3c3
Made some changes to GameModule - still getting 'undefined reference to vtable' error
diff --git a/Src/DasherCore/GameModule.cpp b/Src/DasherCore/GameModule.cpp index becf380..0d0da57 100644 --- a/Src/DasherCore/GameModule.cpp +++ b/Src/DasherCore/GameModule.cpp @@ -1,51 +1,55 @@ #include "GameModule.h" +using namespace Dasher; + void CGameModule::HandleEvent(Dasher::CEvent *pEvent) { - g_pLogger->Log("Inside event handler"); - - switch(pEvent->m_iEventType) + switch(pEvent->m_iEventType) { case EV_EDIT: g_pLogger->Log("Capturing an edit event"); - - switch(static_cast<CEditEvent*>(pEvent)->m_iEditType) + CEditEvent* evt = static_cast<CEditEvent*>(pEvent); + + switch(evt->m_iEditType) { // Added a new character (Stepped one node forward) case 0: - currentStringPos++; - pLastTypedNode = StringToNode(pEvent->m_sText); + m_stCurrentStringPos++; + pLastTypedNode = StringToNode(evt->m_sText); break; // Removed a character (Stepped one node back) case 1: break; default: break; } break; case EV_TEXTDRAW: CTextDrawEvent* evt = static_cast<CTextDrawEvent*>(pEvent); - if(!m_sTargetString[m_stCurrentStringPos + 1].compare(evt->m_sDisplayText)) { + if(!m_sTargetString[m_stCurrentStringPos + 1].compare("j")) { // TODO: Write this function on the view to draw an arrow to a given point. //m_pView->DrawArrowTo(evt->m_iX, evt->m_iY, evt->m_iSize); } default: break; } return; -} -CDasherNode CGameModule::StringToNode(std::string sText) { - + } + } +//CDasherNode CGameModule::StringToNode(std::string sText) { +// +//} + std::string CGameModule::GetTypedTarget() { return m_sTargetString.substr(0, m_stCurrentStringPos - 1); } std::string CGameModule::GetUntypedtarget() { return m_sTargetString.substr(m_stCurrentStringPos); } diff --git a/Src/DasherCore/GameModule.h b/Src/DasherCore/GameModule.h index 84cba81..089a67c 100644 --- a/Src/DasherCore/GameModule.h +++ b/Src/DasherCore/GameModule.h @@ -1,111 +1,106 @@ // GameModule.h #ifndef GAME_MODULE_H #define GAME_MODULE_H #include <string> + using namespace std; #include "DasherView.h" #include "DasherModel.h" #include "DasherModule.h" #include "DasherNode.h" #include "DasherView.h" #include "DasherTypes.h" -namespace Dasher { - class CDasherInterfaceBase; -} - namespace Dasher { /** * This Dasher Module encapsulates all game mode logic. In game mode, users will be given * a target string to type as well as visual feedback for their progress and a helpful * arrow to guide them in the right path through the dasher model. * * This class handles logic and drawing code with respect to the above. */ class CGameModule : public CDasherModule { public: // I don't actually know what the type is supposed to be for this...it's not an input method or an input filter. // Maybe we should define a new one. I've labeled it 0 for now. - rgee CGameModule(Dasher::CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CDasherInterfaceBase *pInterface, ModuleID_t iID, const char *szName) : CDasherModule(pEventHandler, pSettingsStore, iID, 0, szName) { g_pLogger->Log("Inside game module constructor"); m_pInterface = pInterface; } - ~CGameModule() {}; - - /** - * Handle events from the event processing system - * @param pEvent The event to be processed. - */ - virtual void HandleEvent(Dasher::CEvent *pEvent) { - g_pLogger->Log("In the header file!!!"); - } + virtual ~CGameModule() {}; /** * Gets the typed portion of the target string * @return The string that represents the current word(s) that have not been typed */ std::string GetTypedTarget(); /** * Gets the portion of the target string that has yet to be completed * @return The string that represents the current word(s) that have been typed */ std::string GetUntypedTarget(); bool DecorateView(CDasherView *pView) { //g_pLogger->Log("Decorating the view"); return false; } void SetDasherModel(CDasherModel *pModel) { m_pModel = pModel; } + /** + * Handle events from the event processing system + * @param pEvent The event to be processed. + */ + virtual void HandleEvent(Dasher::CEvent *pEvent); + private: /** * Searches for the dasher node under the current root that represents the desired string * @param text The string to search for * @return The node representing the string parameter */ - //Dasher::CDasherNode StringToNode(std::string sText); + //Dasher::CDasherNode StringToNode(std::string sText); /** * The last node the user typed. */ CDasherNode *pLastTypedNode; /** * The next node (character) the user must type. */ CDasherNode *pNextTargetNode; /** * The target string the user must type. */ std::string m_sTargetString; /** * The current position in the string. * Stored as a size_t to easily use substrings to determine what's been typed and what hasn't. */ size_t m_stCurrentStringPos; /** * The dasher model. */ CDasherModel *m_pModel; /** * The dasher interface. */ CDasherInterfaceBase *m_pInterface; }; } #endif
rgee/HFOSS-Dasher
8d237cb6bbaf364a0798c6b6858b889c1fa72cc8
Game module SHOULD now draw an arrow to the target character, if it exists
diff --git a/Src/DasherCore/GameModule.cpp b/Src/DasherCore/GameModule.cpp index e4e4395..3a6a88a 100644 --- a/Src/DasherCore/GameModule.cpp +++ b/Src/DasherCore/GameModule.cpp @@ -1,45 +1,48 @@ #include "GameModule.h" void CGameModule::HandleEvent(Dasher::CEvent *pEvent) { switch(pEvent->m_iEventType) { case EV_EDIT: switch(static_cast<CEditEvent*>(pEvent)->m_iEditType) { // Added a new character (Stepped one node forward) case 0: currentStringPos++; pLastTypedNode = StringToNode(pEvent->m_sText); break; // Removed a character (Stepped one node back) case 1: break; default: break; } break; case EV_TEXTDRAW: CTextDrawEvent* evt = static_cast<CTextDrawEvent*>(pEvent); if(!m_sTargetString[m_stCurrentStringPos + 1].compare(evt->m_sDisplayText)) { - // TODO: Write this function on the view to draw an arrow to a given point. - //m_pView->DrawArrowTo(evt->m_iX, evt->m_iY, evt->m_iSize); + myint X, Y; + + m_pView->DasherPolyarrow(Screen2Dasher(evt->m_iX, evt->m_iY, X, Y)); + DasherPolyarrow(X, Y, 20, GetLongParameter(LP_LINE_WIDTH)*4 135); } + break; default: break; } return; } CDasherNode CGameModule::StringToNode(std::string sText) { } std::string CGameModule::GetTypedTarget() { return m_sTargetString.substr(0, m_stCurrentStringPos - 1); } std::string CGameModule::GetUntypedtarget() { return m_sTargetString.substr(m_stCurrentStringPos); }
rgee/HFOSS-Dasher
63678f433494cf09bca514e28be743627d39dc83
Forward declared new event
diff --git a/Src/DasherCore/Event.h b/Src/DasherCore/Event.h index 7e56c54..2194ceb 100644 --- a/Src/DasherCore/Event.h +++ b/Src/DasherCore/Event.h @@ -1,169 +1,170 @@ #ifndef __event_h__ #define __event_h__ // Classes representing different event types. #include <string> #include "DasherTypes.h" namespace Dasher { class CEvent; + class CTextdrawEvent; class CParameterNotificationEvent; class CEditEvent; class CEditContextEvent; class CStartEvent; class CStopEvent; class CControlEvent; class CLockEvent; class CMessageEvent; class CCommandEvent; } enum { EV_PARAM_NOTIFY = 1, EV_EDIT, EV_EDIT_CONTEXT, EV_START, EV_STOP, EV_CONTROL, EV_LOCK, EV_MESSAGE, EV_COMMAND, EV_TEXTDRAW }; /// \ingroup Core /// @{ /// \defgroup Events Events generated by Dasher modules. /// @{ class Dasher::CEvent { public: int m_iEventType; }; class Dasher::CParameterNotificationEvent:public Dasher::CEvent { public: CParameterNotificationEvent(int iParameter) { m_iEventType = EV_PARAM_NOTIFY; m_iParameter = iParameter; }; int m_iParameter; }; class Dasher::CEditEvent:public Dasher::CEvent { public: CEditEvent(int iEditType, const std::string & sText, int iOffset) { m_iEventType = EV_EDIT; m_iEditType = iEditType; m_sText = sText; m_iOffset = iOffset; }; int m_iEditType; std::string m_sText; int m_iOffset; }; class Dasher::CEditContextEvent:public Dasher::CEvent { public: CEditContextEvent(int iOffset, int iLength) { m_iEventType = EV_EDIT_CONTEXT; m_iOffset = iOffset; m_iLength = iLength; }; int m_iOffset; int m_iLength; }; /** * An event that signals text has been drawn. Useful for determining its location * because that information is only available at draw time. */ class Dasher::CTextDrawEvent : public Dasher::CEvent { public: CTextDrawEvent(std::string sDisplayText, screenint iX, screenint iY, int iSize) :m_sDisplayText(sDisplayText), m_iX(iX), m_iY(iY), m_iSize(iSize) { }; /** * The text that has been drawn. */ std::string m_sDisplayText; /** * The X position (in screen coordinates) of the center of the box surrounding the text. */ screenint m_iX; /** * The Y position (in screen coordinates) of the center of the box surrounding the text. */ screenint m_iY; /** * The size of the text. Useful for determining the boundaries of the text "box" */ int m_iSize; }; class Dasher::CStartEvent:public Dasher::CEvent { public: CStartEvent() { m_iEventType = EV_START; }; }; class Dasher::CStopEvent:public Dasher::CEvent { public: CStopEvent() { m_iEventType = EV_STOP; }; }; class Dasher::CControlEvent:public Dasher::CEvent { public: CControlEvent(int iID) { m_iEventType = EV_CONTROL; m_iID = iID; }; int m_iID; }; class Dasher::CLockEvent : public Dasher::CEvent { public: CLockEvent(const std::string &strMessage, bool bLock, int iPercent) { m_iEventType = EV_LOCK; m_strMessage = strMessage; m_bLock = bLock; m_iPercent = iPercent; }; std::string m_strMessage; bool m_bLock; int m_iPercent; }; class Dasher::CMessageEvent : public Dasher::CEvent { public: CMessageEvent(const std::string &strMessage, int iID, int iType) { m_iEventType = EV_MESSAGE; m_strMessage = strMessage; m_iID = iID; m_iType = iType; }; std::string m_strMessage; int m_iID; int m_iType; }; class Dasher::CCommandEvent : public Dasher::CEvent { public: CCommandEvent(const std::string &strCommand) { m_iEventType = EV_COMMAND; m_strCommand = strCommand; }; std::string m_strCommand; }; /// @} /// @} #endif
rgee/HFOSS-Dasher
52f750678f34d49bfd1b7a4b01e6e00fa821e749
Successfully hooking CGameModule into the module manager, event, and rendering systems. Struggling with a weird inheritance problem in CGameModule::HandleEvent.
diff --git a/Src/DasherCore/DasherInterfaceBase.cpp b/Src/DasherCore/DasherInterfaceBase.cpp index db7cd91..f341066 100644 --- a/Src/DasherCore/DasherInterfaceBase.cpp +++ b/Src/DasherCore/DasherInterfaceBase.cpp @@ -92,1076 +92,1073 @@ CDasherInterfaceBase::CDasherInterfaceBase() { m_pDasherModel = NULL; m_DasherScreen = NULL; m_pDasherView = NULL; m_pInput = NULL; m_pInputFilter = NULL; m_AlphIO = NULL; m_ColourIO = NULL; m_pUserLog = NULL; m_pNCManager = NULL; m_defaultPolicy = NULL; m_pGameModule = NULL; // Various state variables m_bRedrawScheduled = false; m_iCurrentState = ST_START; // m_bGlobalLock = false; // TODO: Are these actually needed? strCurrentContext = ". "; strTrainfileBuffer = ""; // Create an event handler. m_pEventHandler = new CEventHandler(this); m_bLastChanged = true; #ifndef _WIN32_WCE // Global logging object we can use from anywhere g_pLogger = new CFileLogger("dasher.log", g_iLogLevel, g_iLogOptions); #endif } void CDasherInterfaceBase::Realize() { // TODO: What exactly needs to have happened by the time we call Realize()? CreateSettingsStore(); SetupUI(); SetupPaths(); std::vector<std::string> vAlphabetFiles; ScanAlphabetFiles(vAlphabetFiles); m_AlphIO = new CAlphIO(GetStringParameter(SP_SYSTEM_LOC), GetStringParameter(SP_USER_LOC), vAlphabetFiles); std::vector<std::string> vColourFiles; ScanColourFiles(vColourFiles); m_ColourIO = new CColourIO(GetStringParameter(SP_SYSTEM_LOC), GetStringParameter(SP_USER_LOC), vColourFiles); ChangeColours(); ChangeAlphabet(); // This creates the NodeCreationManager, the Alphabet // Create the user logging object if we are suppose to. We wait // until now so we have the real value of the parameter and not // just the default. // TODO: Sort out log type selection #ifndef _WIN32_WCE int iUserLogLevel = GetLongParameter(LP_USER_LOG_LEVEL_MASK); if(iUserLogLevel == 10) m_pUserLog = new CBasicLog(m_pEventHandler, m_pSettingsStore); else if (iUserLogLevel > 0) m_pUserLog = new CUserLog(m_pEventHandler, m_pSettingsStore, iUserLogLevel, m_Alphabet); #else m_pUserLog = NULL; #endif CreateModules(); CreateInput(); CreateInputFilter(); SetupActionButtons(); CParameterNotificationEvent oEvent(LP_NODE_BUDGET); InterfaceEventHandler(&oEvent); //if game mode is enabled , initialize the game module // if(GetBoolParameter(BP_GAME_MODE)) InitGameModule(); // Set up real orientation to match selection if(GetLongParameter(LP_ORIENTATION) == Dasher::Opts::AlphabetDefault) SetLongParameter(LP_REAL_ORIENTATION, m_Alphabet->GetOrientation()); else SetLongParameter(LP_REAL_ORIENTATION, GetLongParameter(LP_ORIENTATION)); // FIXME - need to rationalise this sort of thing. // InvalidateContext(true); ScheduleRedraw(); #ifndef _WIN32_WCE // All the setup is done by now, so let the user log object know // that future parameter changes should be logged. if (m_pUserLog != NULL) m_pUserLog->InitIsDone(); #endif // TODO: Make things work when model is created latet ChangeState(TR_MODEL_INIT); using GameMode::CDasherGameMode; // Create the teacher singleton object. CDasherGameMode::CreateTeacher(m_pEventHandler, m_pSettingsStore, this); CDasherGameMode::GetTeacher()->SetDasherView(m_pDasherView); CDasherGameMode::GetTeacher()->SetDasherModel(m_pDasherModel); } CDasherInterfaceBase::~CDasherInterfaceBase() { DASHER_ASSERT(m_iCurrentState == ST_SHUTDOWN); // It may seem odd that InterfaceBase does not "own" the teacher. // This is because game mode is a different layer, in a sense. GameMode::CDasherGameMode::DestroyTeacher(); delete m_pDasherModel; // The order of some of these deletions matters delete m_Alphabet; delete m_pDasherView; delete m_ColourIO; delete m_AlphIO; delete m_pNCManager; // Do NOT delete Edit box or Screen. This class did not create them. #ifndef _WIN32_WCE // When we destruct on shutdown, we'll output any detailed log file if (m_pUserLog != NULL) { m_pUserLog->OutputFile(); delete m_pUserLog; m_pUserLog = NULL; } if (g_pLogger != NULL) { delete g_pLogger; g_pLogger = NULL; } #endif for (std::vector<CActionButton *>::iterator it=m_vLeftButtons.begin(); it != m_vLeftButtons.end(); ++it) delete *it; for (std::vector<CActionButton *>::iterator it=m_vRightButtons.begin(); it != m_vRightButtons.end(); ++it) delete *it; // Must delete event handler after all CDasherComponent derived classes delete m_pEventHandler; } void CDasherInterfaceBase::PreSetNotify(int iParameter, const std::string &sNewValue) { // FIXME - make this a more general 'pre-set' event in the message // infrastructure switch(iParameter) { case SP_ALPHABET_ID: // Cycle the alphabet history if(GetStringParameter(SP_ALPHABET_ID) != sNewValue) { if(GetStringParameter(SP_ALPHABET_1) != sNewValue) { if(GetStringParameter(SP_ALPHABET_2) != sNewValue) { if(GetStringParameter(SP_ALPHABET_3) != sNewValue) SetStringParameter(SP_ALPHABET_4, GetStringParameter(SP_ALPHABET_3)); SetStringParameter(SP_ALPHABET_3, GetStringParameter(SP_ALPHABET_2)); } SetStringParameter(SP_ALPHABET_2, GetStringParameter(SP_ALPHABET_1)); } SetStringParameter(SP_ALPHABET_1, GetStringParameter(SP_ALPHABET_ID)); } break; } } void CDasherInterfaceBase::InterfaceEventHandler(Dasher::CEvent *pEvent) { if(pEvent->m_iEventType == EV_PARAM_NOTIFY) { Dasher::CParameterNotificationEvent * pEvt(static_cast < Dasher::CParameterNotificationEvent * >(pEvent)); switch (pEvt->m_iParameter) { case BP_OUTLINE_MODE: ScheduleRedraw(); break; case BP_DRAW_MOUSE: ScheduleRedraw(); break; case BP_CONTROL_MODE: ScheduleRedraw(); break; case BP_DRAW_MOUSE_LINE: ScheduleRedraw(); break; case LP_ORIENTATION: if(GetLongParameter(LP_ORIENTATION) == Dasher::Opts::AlphabetDefault) // TODO: See comment in DasherModel.cpp about prefered values SetLongParameter(LP_REAL_ORIENTATION, m_Alphabet->GetOrientation()); else SetLongParameter(LP_REAL_ORIENTATION, GetLongParameter(LP_ORIENTATION)); ScheduleRedraw(); break; case SP_ALPHABET_ID: ChangeAlphabet(); ScheduleRedraw(); break; case SP_COLOUR_ID: ChangeColours(); ScheduleRedraw(); break; case SP_DEFAULT_COLOUR_ID: // Delibarate fallthrough case BP_PALETTE_CHANGE: if(GetBoolParameter(BP_PALETTE_CHANGE)) SetStringParameter(SP_COLOUR_ID, GetStringParameter(SP_DEFAULT_COLOUR_ID)); break; case LP_LANGUAGE_MODEL_ID: CreateNCManager(); break; case LP_LINE_WIDTH: ScheduleRedraw(); break; case LP_DASHER_FONTSIZE: ScheduleRedraw(); break; case SP_INPUT_DEVICE: CreateInput(); break; case SP_INPUT_FILTER: CreateInputFilter(); ScheduleRedraw(); break; case BP_DASHER_PAUSED: ScheduleRedraw(); break; case LP_MARGIN_WIDTH: case BP_NONLINEAR_Y: case LP_NONLINEAR_X: ScheduleRedraw(); break; case LP_NODE_BUDGET: delete m_defaultPolicy; m_defaultPolicy = new AmortizedPolicy(GetLongParameter(LP_NODE_BUDGET)); default: break; } } else if(pEvent->m_iEventType == EV_EDIT && !GetBoolParameter(BP_GAME_MODE)) { CEditEvent *pEditEvent(static_cast < CEditEvent * >(pEvent)); if(pEditEvent->m_iEditType == 1) { strCurrentContext += pEditEvent->m_sText; if( strCurrentContext.size() > 20 ) strCurrentContext = strCurrentContext.substr( strCurrentContext.size() - 20 ); if(GetBoolParameter(BP_LM_ADAPTIVE)) strTrainfileBuffer += pEditEvent->m_sText; } else if(pEditEvent->m_iEditType == 2) { strCurrentContext = strCurrentContext.substr( 0, strCurrentContext.size() - pEditEvent->m_sText.size()); if(GetBoolParameter(BP_LM_ADAPTIVE)) strTrainfileBuffer = strTrainfileBuffer.substr( 0, strTrainfileBuffer.size() - pEditEvent->m_sText.size()); } } else if(pEvent->m_iEventType == EV_CONTROL) { CControlEvent *pControlEvent(static_cast <CControlEvent*>(pEvent)); switch(pControlEvent->m_iID) { case CControlManager::CTL_STOP: Pause(); break; case CControlManager::CTL_PAUSE: //Halt Dasher - without a stop event, so does not result in speech etc. SetBoolParameter(BP_DASHER_PAUSED, true); m_pDasherModel->TriggerSlowdown(); } } } void CDasherInterfaceBase::WriteTrainFileFull() { WriteTrainFile(strTrainfileBuffer); strTrainfileBuffer = ""; } void CDasherInterfaceBase::WriteTrainFilePartial() { // TODO: what if we're midway through a unicode character? WriteTrainFile(strTrainfileBuffer.substr(0,100)); strTrainfileBuffer = strTrainfileBuffer.substr(100); } void CDasherInterfaceBase::CreateModel(int iOffset) { // Creating a model without a node creation manager is a bad plan if(!m_pNCManager) return; if(m_pDasherModel) { delete m_pDasherModel; m_pDasherModel = 0; } m_pDasherModel = new CDasherModel(m_pEventHandler, m_pSettingsStore, m_pNCManager, this, m_pDasherView, iOffset); // Notify the teacher of the new model if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) pTeacher->SetDasherModel(m_pDasherModel); } void CDasherInterfaceBase::CreateNCManager() { // TODO: Try and make this work without necessarilty rebuilding the model if(!m_AlphIO) return; int lmID = GetLongParameter(LP_LANGUAGE_MODEL_ID); if( lmID == -1 ) return; int iOffset; if(m_pDasherModel) iOffset = m_pDasherModel->GetOffset(); else iOffset = 0; // TODO: Is this right? // Delete the old model and create a new one if(m_pDasherModel) { delete m_pDasherModel; m_pDasherModel = 0; } if(m_pNCManager) { delete m_pNCManager; m_pNCManager = 0; } m_pNCManager = new CNodeCreationManager(this, m_pEventHandler, m_pSettingsStore, m_AlphIO); m_Alphabet = m_pNCManager->GetAlphabet(); // TODO: Eventually we'll not have to pass the NC manager to the model... CreateModel(iOffset); } void CDasherInterfaceBase::Pause() { if (GetBoolParameter(BP_DASHER_PAUSED)) return; //already paused, no need to do anything. SetBoolParameter(BP_DASHER_PAUSED, true); // Request a full redraw at the next time step. SetBoolParameter(BP_REDRAW, true); Dasher::CStopEvent oEvent; m_pEventHandler->InsertEvent(&oEvent); #ifndef _WIN32_WCE if (m_pUserLog != NULL) m_pUserLog->StopWriting((float) GetNats()); #endif } void CDasherInterfaceBase::GameMessageIn(int message, void* messagedata) { GameMode::CDasherGameMode::GetTeacher()->Message(message, messagedata); } void CDasherInterfaceBase::Unpause(unsigned long Time) { if (!GetBoolParameter(BP_DASHER_PAUSED)) return; //already running, no need to do anything SetBoolParameter(BP_DASHER_PAUSED, false); if(m_pDasherModel != 0) m_pDasherModel->Reset_framerate(Time); Dasher::CStartEvent oEvent; m_pEventHandler->InsertEvent(&oEvent); // Commenting this out, can't see a good reason to ResetNats, // just because we are not paused anymore - pconlon // ResetNats(); #ifndef _WIN32_WCE if (m_pUserLog != NULL) m_pUserLog->StartWriting(); #endif } void CDasherInterfaceBase::CreateInput() { if(m_pInput) { m_pInput->Deactivate(); } m_pInput = (CDasherInput *)GetModuleByName(GetStringParameter(SP_INPUT_DEVICE)); if (m_pInput == NULL) m_pInput = (CDasherInput *)GetDefaultInputDevice(); if(m_pInput) { m_pInput->Activate(); } if(m_pDasherView != 0) m_pDasherView->SetInput(m_pInput); } void CDasherInterfaceBase::NewFrame(unsigned long iTime, bool bForceRedraw) { // Prevent NewFrame from being reentered. This can happen occasionally and // cause crashes. static bool bReentered=false; if (bReentered) { #ifdef DEBUG std::cout << "CDasherInterfaceBase::NewFrame was re-entered" << std::endl; #endif return; } bReentered=true; // Fail if Dasher is locked // if(m_iCurrentState != ST_NORMAL) // return; bool bChanged(false), bWasPaused(GetBoolParameter(BP_DASHER_PAUSED)); CExpansionPolicy *pol=m_defaultPolicy; if(m_pDasherView != 0) { if(!GetBoolParameter(BP_TRAINING)) { if (m_pUserLog != NULL) { //ACL note that as of 15/5/09, splitting UpdatePosition into two, //DasherModel no longer guarantees to empty these two if it didn't do anything. //So initialise appropriately... Dasher::VECTOR_SYMBOL_PROB vAdded; int iNumDeleted = 0; if(m_pInputFilter) { bChanged = m_pInputFilter->Timer(iTime, m_pDasherView, m_pDasherModel, &vAdded, &iNumDeleted, &pol); } #ifndef _WIN32_WCE if (iNumDeleted > 0) m_pUserLog->DeleteSymbols(iNumDeleted); if (vAdded.size() > 0) m_pUserLog->AddSymbols(&vAdded); #endif } else { if(m_pInputFilter) { bChanged = m_pInputFilter->Timer(iTime, m_pDasherView, m_pDasherModel, 0, 0, &pol); } } m_pDasherModel->CheckForNewRoot(m_pDasherView); } } //check: if we were paused before, and the input filter didn't unpause, // then nothing can have changed: DASHER_ASSERT(!bWasPaused || !GetBoolParameter(BP_DASHER_PAUSED) || !bChanged); // Flags at this stage: // // - bChanged = the display was updated, so needs to be rendered to the display // - m_bLastChanged = bChanged was true last time around // - m_bRedrawScheduled = Display invalidated internally // - bForceRedraw = Display invalidated externally // TODO: This is a bit hacky - we really need to sort out the redraw logic if((!bChanged && m_bLastChanged) || m_bRedrawScheduled || bForceRedraw) { m_pDasherView->Screen()->SetCaptureBackground(true); m_pDasherView->Screen()->SetLoadBackground(true); } bForceRedraw |= m_bLastChanged; m_bLastChanged = bChanged; //will also be set in Redraw if any nodes were expanded. Redraw(bChanged || m_bRedrawScheduled || bForceRedraw, *pol); m_bRedrawScheduled = false; // This just passes the time through to the framerate tracker, so we // know how often new frames are being drawn. if(m_pDasherModel != 0) m_pDasherModel->RecordFrame(iTime); bReentered=false; } void CDasherInterfaceBase::Redraw(bool bRedrawNodes, CExpansionPolicy &policy) { // No point continuing if there's nothing to draw on... if(!m_pDasherView) return; // Draw the nodes if(bRedrawNodes) { m_pDasherView->Screen()->SendMarker(0); if (m_pDasherModel) m_bLastChanged |= m_pDasherModel->RenderToView(m_pDasherView,policy); } // Draw the decorations m_pDasherView->Screen()->SendMarker(1); if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) pTeacher->DrawGameDecorations(m_pDasherView); bool bDecorationsChanged(false); if(m_pInputFilter) { bDecorationsChanged = m_pInputFilter->DecorateView(m_pDasherView); } if(m_pGameModule) { - g_pLogger->Log("The game module was initialized."); bDecorationsChanged = m_pGameModule->DecorateView(m_pDasherView) || bDecorationsChanged; } - else { - g_pLogger->Log("FUUUUUUCCCCCCKKKKKKKKKK"); - } bool bActionButtonsChanged(false); #ifdef EXPERIMENTAL_FEATURES bActionButtonsChanged = DrawActionButtons(); #endif // Only blit the image to the display if something has actually changed if(bRedrawNodes || bDecorationsChanged || bActionButtonsChanged) m_pDasherView->Display(); } void CDasherInterfaceBase::ChangeAlphabet() { if(GetStringParameter(SP_ALPHABET_ID) == "") { SetStringParameter(SP_ALPHABET_ID, m_AlphIO->GetDefault()); // This will result in ChangeAlphabet() being called again, so // exit from the first recursion return; } // Send a lock event WriteTrainFileFull(); // Lock Dasher to prevent changes from happening while we're training. SetBoolParameter( BP_TRAINING, true ); CreateNCManager(); #ifndef _WIN32_WCE // Let our user log object know about the new alphabet since // it needs to convert symbols into text for the log file. if (m_pUserLog != NULL) m_pUserLog->SetAlphabetPtr(m_Alphabet); #endif // Apply options from alphabet SetBoolParameter( BP_TRAINING, false ); //} } void CDasherInterfaceBase::ChangeColours() { if(!m_ColourIO || !m_DasherScreen) return; // TODO: Make fuction return a pointer directly m_DasherScreen->SetColourScheme(&(m_ColourIO->GetInfo(GetStringParameter(SP_COLOUR_ID)))); } void CDasherInterfaceBase::ChangeScreen(CDasherScreen *NewScreen) { // What does ChangeScreen do? m_DasherScreen = NewScreen; ChangeColours(); if(m_pDasherView != 0) { m_pDasherView->ChangeScreen(m_DasherScreen); } else if(GetLongParameter(LP_VIEW_ID) != -1) { ChangeView(); } PositionActionButtons(); BudgettingPolicy pol(GetLongParameter(LP_NODE_BUDGET)); //maintain budget, but allow arbitrary amount of work. Redraw(true, pol); // (we're assuming resolution changes are occasional, i.e. // we don't need to worry about maintaining the frame rate, so we can do // as much work as necessary. However, it'd probably be better still to // get a node queue from the input filter, as that might have a different // policy / budget. } void CDasherInterfaceBase::ChangeView() { // TODO: Actually respond to LP_VIEW_ID parameter (although there is only one view at the moment) // removed condition that m_pDasherModel != 0. Surely the view can exist without the model?-pconlon if(m_DasherScreen != 0 /*&& m_pDasherModel != 0*/) { delete m_pDasherView; m_pDasherView = new CDasherViewSquare(m_pEventHandler, m_pSettingsStore, m_DasherScreen); if (m_pInput) m_pDasherView->SetInput(m_pInput); // Tell the Teacher which view we are using if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) pTeacher->SetDasherView(m_pDasherView); } } const CAlphIO::AlphInfo & CDasherInterfaceBase::GetInfo(const std::string &AlphID) { return m_AlphIO->GetInfo(AlphID); } void CDasherInterfaceBase::SetInfo(const CAlphIO::AlphInfo &NewInfo) { m_AlphIO->SetInfo(NewInfo); } void CDasherInterfaceBase::DeleteAlphabet(const std::string &AlphID) { m_AlphIO->Delete(AlphID); } double CDasherInterfaceBase::GetCurCPM() { // return 0; } double CDasherInterfaceBase::GetCurFPS() { // return 0; } // int CDasherInterfaceBase::GetAutoOffset() { // if(m_pDasherView != 0) { // return m_pDasherView->GetAutoOffset(); // } // return -1; // } double CDasherInterfaceBase::GetNats() const { if(m_pDasherModel) return m_pDasherModel->GetNats(); else return 0.0; } void CDasherInterfaceBase::ResetNats() { if(m_pDasherModel) m_pDasherModel->ResetNats(); } // TODO: Check that none of this needs to be reimplemented // void CDasherInterfaceBase::InvalidateContext(bool bForceStart) { // m_pDasherModel->m_strContextBuffer = ""; // Dasher::CEditContextEvent oEvent(10); // m_pEventHandler->InsertEvent(&oEvent); // std::string strNewContext(m_pDasherModel->m_strContextBuffer); // // We keep track of an internal context and compare that to what // // we are given - don't restart Dasher if nothing has changed. // // This should really be integrated with DasherModel, which // // probably will be the case when we start to deal with being able // // to back off indefinitely. For now though we'll keep it in a // // separate string. // int iContextLength( 6 ); // The 'important' context length - should really get from language model // // FIXME - use unicode lengths // if(bForceStart || (strNewContext.substr( std::max(static_cast<int>(strNewContext.size()) - iContextLength, 0)) != strCurrentContext.substr( std::max(static_cast<int>(strCurrentContext.size()) - iContextLength, 0)))) { // if(m_pDasherModel != NULL) { // // TODO: Reimplement this // // if(m_pDasherModel->m_bContextSensitive || bForceStart) { // { // m_pDasherModel->SetContext(strNewContext); // PauseAt(0,0); // } // } // strCurrentContext = strNewContext; // WriteTrainFileFull(); // } // if(bForceStart) { // int iMinWidth; // if(m_pInputFilter && m_pInputFilter->GetMinWidth(iMinWidth)) { // m_pDasherModel->LimitRoot(iMinWidth); // } // } // if(m_pDasherView) // while( m_pDasherModel->CheckForNewRoot(m_pDasherView) ) { // // Do nothing // } // ScheduleRedraw(); // } // TODO: Fix this std::string CDasherInterfaceBase::GetContext(int iStart, int iLength) { m_strContext = ""; CEditContextEvent oEvent(iStart, iLength); m_pEventHandler->InsertEvent(&oEvent); return m_strContext; } void CDasherInterfaceBase::SetContext(std::string strNewContext) { m_strContext = strNewContext; } // Control mode stuff void CDasherInterfaceBase::RegisterNode( int iID, const std::string &strLabel, int iColour ) { m_pNCManager->RegisterNode(iID, strLabel, iColour); } void CDasherInterfaceBase::ConnectNode(int iChild, int iParent, int iAfter) { m_pNCManager->ConnectNode(iChild, iParent, iAfter); } void CDasherInterfaceBase::DisconnectNode(int iChild, int iParent) { m_pNCManager->DisconnectNode(iChild, iParent); } void CDasherInterfaceBase::SetBoolParameter(int iParameter, bool bValue) { m_pSettingsStore->SetBoolParameter(iParameter, bValue); }; void CDasherInterfaceBase::SetLongParameter(int iParameter, long lValue) { m_pSettingsStore->SetLongParameter(iParameter, lValue); }; void CDasherInterfaceBase::SetStringParameter(int iParameter, const std::string & sValue) { PreSetNotify(iParameter, sValue); m_pSettingsStore->SetStringParameter(iParameter, sValue); }; bool CDasherInterfaceBase::GetBoolParameter(int iParameter) { return m_pSettingsStore->GetBoolParameter(iParameter); } long CDasherInterfaceBase::GetLongParameter(int iParameter) { return m_pSettingsStore->GetLongParameter(iParameter); } std::string CDasherInterfaceBase::GetStringParameter(int iParameter) { return m_pSettingsStore->GetStringParameter(iParameter); } void CDasherInterfaceBase::ResetParameter(int iParameter) { m_pSettingsStore->ResetParameter(iParameter); } // We need to be able to get at the UserLog object from outside the interface CUserLogBase* CDasherInterfaceBase::GetUserLogPtr() { return m_pUserLog; } void CDasherInterfaceBase::KeyDown(int iTime, int iId, bool bPos, int iX, int iY) { if(m_iCurrentState != ST_NORMAL) return; if(m_pInputFilter && !GetBoolParameter(BP_TRAINING)) { m_pInputFilter->KeyDown(iTime, iId, m_pDasherView, m_pDasherModel, m_pUserLog, bPos, iX, iY); } if(m_pInput && !GetBoolParameter(BP_TRAINING)) { m_pInput->KeyDown(iTime, iId); } } void CDasherInterfaceBase::KeyUp(int iTime, int iId, bool bPos, int iX, int iY) { if(m_iCurrentState != ST_NORMAL) return; if(m_pInputFilter && !GetBoolParameter(BP_TRAINING)) { m_pInputFilter->KeyUp(iTime, iId, m_pDasherView, m_pDasherModel, bPos, iX, iY); } if(m_pInput && !GetBoolParameter(BP_TRAINING)) { m_pInput->KeyUp(iTime, iId); } } void CDasherInterfaceBase::InitGameModule() { - //TODO - don't use magic number here!!! if(m_pGameModule == NULL) { - g_pLogger->Log("InitGameModule"); - m_pGameModule = (CGameModule*) GetModule(21); + g_pLogger->Log("Initializing the game module."); + m_pGameModule = (CGameModule*) GetModuleByName("Game Mode"); } } void CDasherInterfaceBase::CreateInputFilter() { if(m_pInputFilter) { m_pInputFilter->Deactivate(); m_pInputFilter = NULL; } #ifndef _WIN32_WCE m_pInputFilter = (CInputFilter *)GetModuleByName(GetStringParameter(SP_INPUT_FILTER)); #endif if (m_pInputFilter == NULL) m_pInputFilter = (CInputFilter *)GetDefaultInputMethod(); m_pInputFilter->Activate(); } CDasherModule *CDasherInterfaceBase::RegisterModule(CDasherModule *pModule) { return m_oModuleManager.RegisterModule(pModule); } CDasherModule *CDasherInterfaceBase::GetModule(ModuleID_t iID) { return m_oModuleManager.GetModule(iID); } CDasherModule *CDasherInterfaceBase::GetModuleByName(const std::string &strName) { return m_oModuleManager.GetModuleByName(strName); } CDasherModule *CDasherInterfaceBase::GetDefaultInputDevice() { return m_oModuleManager.GetDefaultInputDevice(); } CDasherModule *CDasherInterfaceBase::GetDefaultInputMethod() { return m_oModuleManager.GetDefaultInputMethod(); } void CDasherInterfaceBase::SetDefaultInputDevice(CDasherModule *pModule) { m_oModuleManager.SetDefaultInputDevice(pModule); } void CDasherInterfaceBase::SetDefaultInputMethod(CDasherModule *pModule) { m_oModuleManager.SetDefaultInputMethod(pModule); } void CDasherInterfaceBase::CreateModules() { SetDefaultInputMethod( RegisterModule(new CDefaultFilter(m_pEventHandler, m_pSettingsStore, this, 3, _("Normal Control"))) ); RegisterModule(new COneDimensionalFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CEyetrackerFilter(m_pEventHandler, m_pSettingsStore, this)); #ifndef _WIN32_WCE RegisterModule(new CClickFilter(m_pEventHandler, m_pSettingsStore, this)); #else SetDefaultInputMethod( RegisterModule(new CClickFilter(m_pEventHandler, m_pSettingsStore, this)); ); #endif RegisterModule(new COneButtonFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new COneButtonDynamicFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CTwoButtonDynamicFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CTwoPushDynamicFilter(m_pEventHandler, m_pSettingsStore, this)); // TODO: specialist factory for button mode RegisterModule(new CButtonMode(m_pEventHandler, m_pSettingsStore, this, true, 8, _("Menu Mode"))); RegisterModule(new CButtonMode(m_pEventHandler, m_pSettingsStore, this, false,10, _("Direct Mode"))); // RegisterModule(new CDasherButtons(m_pEventHandler, m_pSettingsStore, this, 4, 0, false,11, "Buttons 3")); RegisterModule(new CAlternatingDirectMode(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CCompassMode(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CStylusFilter(m_pEventHandler, m_pSettingsStore, this, 15, _("Stylus Control"))); // Register game mode with the module manager // TODO should this be wrapped in an "if game mode enabled" // conditional? // TODO: I don't know what a sensible module ID should be // for this, so I chose an arbitrary value - RegisterModule(new CGameModule(m_pEventHandler, m_pSettingsStore, this, 21, _("GameMode"))); + // TODO: Put "Game Mode" in enumeration in Parameter.h + + RegisterModule(new CGameModule(m_pEventHandler, m_pSettingsStore, this, 21, _("Game Mode"))); } void CDasherInterfaceBase::GetPermittedValues(int iParameter, std::vector<std::string> &vList) { // TODO: Deprecate direct calls to these functions switch (iParameter) { case SP_ALPHABET_ID: if(m_AlphIO) m_AlphIO->GetAlphabets(&vList); break; case SP_COLOUR_ID: if(m_ColourIO) m_ColourIO->GetColours(&vList); break; case SP_INPUT_FILTER: m_oModuleManager.ListModules(1, vList); break; case SP_INPUT_DEVICE: m_oModuleManager.ListModules(0, vList); break; } } void CDasherInterfaceBase::StartShutdown() { ChangeState(TR_SHUTDOWN); } bool CDasherInterfaceBase::GetModuleSettings(const std::string &strName, SModuleSettings **pSettings, int *iCount) { return GetModuleByName(strName)->GetSettings(pSettings, iCount); } void CDasherInterfaceBase::SetupActionButtons() { m_vLeftButtons.push_back(new CActionButton(this, "Exit", true)); m_vLeftButtons.push_back(new CActionButton(this, "Preferences", false)); m_vLeftButtons.push_back(new CActionButton(this, "Help", false)); m_vLeftButtons.push_back(new CActionButton(this, "About", false)); } void CDasherInterfaceBase::DestroyActionButtons() { // TODO: implement and call this } void CDasherInterfaceBase::PositionActionButtons() { if(!m_DasherScreen) return; int iCurrentOffset(16); for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) { (*it)->SetPosition(16, iCurrentOffset, 32, 32); iCurrentOffset += 48; } iCurrentOffset = 16; for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) { (*it)->SetPosition(m_DasherScreen->GetWidth() - 144, iCurrentOffset, 128, 32); iCurrentOffset += 48; } } bool CDasherInterfaceBase::DrawActionButtons() { if(!m_DasherScreen) return false; bool bVisible(GetBoolParameter(BP_DASHER_PAUSED)); bool bRV(bVisible != m_bOldVisible); m_bOldVisible = bVisible; for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) (*it)->Draw(m_DasherScreen, bVisible); for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) (*it)->Draw(m_DasherScreen, bVisible); return bRV; } void CDasherInterfaceBase::HandleClickUp(int iTime, int iX, int iY) { #ifdef EXPERIMENTAL_FEATURES bool bVisible(GetBoolParameter(BP_DASHER_PAUSED)); for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) { if((*it)->HandleClickUp(iTime, iX, iY, bVisible)) return; } for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) { if((*it)->HandleClickUp(iTime, iX, iY, bVisible)) return; } #endif KeyUp(iTime, 100, true, iX, iY); } void CDasherInterfaceBase::HandleClickDown(int iTime, int iX, int iY) { #ifdef EXPERIMENTAL_FEATURES bool bVisible(GetBoolParameter(BP_DASHER_PAUSED)); for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) { if((*it)->HandleClickDown(iTime, iX, iY, bVisible)) return; } for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) { if((*it)->HandleClickDown(iTime, iX, iY, bVisible)) return; } #endif KeyDown(iTime, 100, true, iX, iY); } void CDasherInterfaceBase::ExecuteCommand(const std::string &strName) { // TODO: Pointless - just insert event directly CCommandEvent *pEvent = new CCommandEvent(strName); m_pEventHandler->InsertEvent(pEvent); delete pEvent; } double CDasherInterfaceBase::GetFramerate() { if(m_pDasherModel) return(m_pDasherModel->Framerate()); else return 0.0; } void CDasherInterfaceBase::AddActionButton(const std::string &strName) { m_vRightButtons.push_back(new CActionButton(this, strName, false)); } void CDasherInterfaceBase::OnUIRealised() { StartTimer(); ChangeState(TR_UI_INIT); } void CDasherInterfaceBase::ChangeState(ETransition iTransition) { static EState iTransitionTable[ST_NUM][TR_NUM] = { {ST_MODEL, ST_UI, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN},//ST_START {ST_FORBIDDEN, ST_NORMAL, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN},//ST_MODEL {ST_NORMAL, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN},//ST_UI {ST_FORBIDDEN, ST_FORBIDDEN, ST_LOCKED, ST_FORBIDDEN, ST_SHUTDOWN},//ST_NORMAL {ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_NORMAL, ST_FORBIDDEN},//ST_LOCKED {ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN}//ST_SHUTDOWN //TR_MODEL_INIT, TR_UI_INIT, TR_LOCK, TR_UNLOCK, TR_SHUTDOWN }; EState iNewState(iTransitionTable[m_iCurrentState][iTransition]); if(iNewState != ST_FORBIDDEN) { if (iNewState == ST_SHUTDOWN) { ShutdownTimer(); WriteTrainFileFull(); } m_iCurrentState = iNewState; } } void CDasherInterfaceBase::SetBuffer(int iOffset) { CreateModel(iOffset); } void CDasherInterfaceBase::UnsetBuffer() { // TODO: Write training file? if(m_pDasherModel) delete m_pDasherModel; m_pDasherModel = 0; } void CDasherInterfaceBase::SetOffset(int iOffset) { if(m_pDasherModel) m_pDasherModel->SetOffset(iOffset, m_pDasherView); } void CDasherInterfaceBase::SetControlOffset(int iOffset) { if(m_pDasherModel) m_pDasherModel->SetControlOffset(iOffset); } // Returns 0 on success, an error string on failure. const char* CDasherInterfaceBase::ClSet(const std::string &strKey, const std::string &strValue) { if(m_pSettingsStore) return m_pSettingsStore->ClSet(strKey, strValue); return 0; } void CDasherInterfaceBase::ImportTrainingText(const std::string &strPath) { if(m_pNCManager) m_pNCManager->ImportTrainingText(strPath); } diff --git a/Src/DasherCore/GameModule.cpp b/Src/DasherCore/GameModule.cpp index 9b73984..380e44c 100644 --- a/Src/DasherCore/GameModule.cpp +++ b/Src/DasherCore/GameModule.cpp @@ -1,38 +1,44 @@ #include "GameModule.h" void CGameModule::HandleEvent(Dasher::CEvent *pEvent) { + + g_pLogger->Log("Inside event handler"); + switch(pEvent->m_iEventType) { case EV_EDIT: + + g_pLogger->Log("Capturing an edit event"); + switch(static_cast<CEditEvent*>(pEvent)->m_iEditType) { // Added a new character (Stepped one node forward) case 0: currentStringPos++; pLastTypedNode = StringToNode(pEvent->m_sText); break; // Removed a character (Stepped one node back) case 1: break; default: break; } break; default: break; } return; } CDasherNode CGameModule::StringToNode(std::string sText) { } std::string CGameModule::GetTypedTarget() { return m_sTargetString.substr(0, m_stCurrentStringPos - 1); } std::string CGameModule::GetUntypedtarget() { return m_sTargetString.substr(m_stCurrentStringPos); } diff --git a/Src/DasherCore/GameModule.h b/Src/DasherCore/GameModule.h index 8e8c102..9a34577 100644 --- a/Src/DasherCore/GameModule.h +++ b/Src/DasherCore/GameModule.h @@ -1,107 +1,109 @@ // GameModule.h #ifndef GAME_MODULE_H #define GAME_MODULE_H #include <string> using namespace std; #include "DasherView.h" #include "DasherModel.h" #include "DasherModule.h" #include "DasherNode.h" namespace Dasher { class CDasherInterfaceBase; } namespace Dasher { /** * This Dasher Module encapsulates all game mode logic. In game mode, users will be given * a target string to type as well as visual feedback for their progress and a helpful * arrow to guide them in the right path through the dasher model. * * This class handles logic and drawing code with respect to the above. */ class CGameModule : public CDasherModule { public: // I don't actually know what the type is supposed to be for this...it's not an input method or an input filter. // Maybe we should define a new one. I've labeled it 0 for now. - rgee CGameModule(Dasher::CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CDasherInterfaceBase *pInterface, ModuleID_t iID, const char *szName) : CDasherModule(pEventHandler, pSettingsStore, iID, 0, szName) { g_pLogger->Log("Inside game module constructor"); m_pInterface = pInterface; } ~CGameModule() {}; /** * Handle events from the event processing system * @param pEvent The event to be processed. */ - void HandleEvent(Dasher::CEvent *pEvent) {}; + virtual void HandleEvent(Dasher::CEvent *pEvent) { + g_pLogger->Log("In the header file!!!"); + } /** * Gets the typed portion of the target string * @return The string that represents the current word(s) that have not been typed */ std::string GetTypedTarget(); /** * Gets the portion of the target string that has yet to be completed * @return The string that represents the current word(s) that have been typed */ std::string GetUntypedTarget(); bool DecorateView(CDasherView *pView) { - g_pLogger->Log("Decorating the view"); + //g_pLogger->Log("Decorating the view"); return false; } void SetDasherModel(CDasherModel *pModel) { m_pModel = pModel; } private: /** * Searches for the dasher node under the current root that represents the desired string * @param text The string to search for * @return The node representing the string parameter */ //Dasher::CDasherNode StringToNode(std::string sText); /** * The last node the user typed. */ CDasherNode *pLastTypedNode; /** * The next node (character) the user must type. */ CDasherNode *pNextTargetNode; /** * The target string the user must type. */ std::string m_sTargetString; /** * The current position in the string. * Stored as a size_t to easily use substrings to determine what's been typed and what hasn't. */ size_t m_stCurrentStringPos; /** * The dasher model. */ CDasherModel *m_pModel; /** * The dasher interface. */ CDasherInterfaceBase *m_pInterface; }; } #endif
rgee/HFOSS-Dasher
3da388a6fc6654217847beadd39f16d36e4ca144
Created a new event that represents text draw events to give us access to the location of text drawn the screen. GameModule now listens for this event.
diff --git a/Src/DasherCore/DasherViewSquare.cpp b/Src/DasherCore/DasherViewSquare.cpp index f0ec7ad..bb963e5 100644 --- a/Src/DasherCore/DasherViewSquare.cpp +++ b/Src/DasherCore/DasherViewSquare.cpp @@ -1,724 +1,729 @@ // DasherViewSquare.cpp // // Copyright (c) 2008 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" #ifdef _WIN32 #include "..\Win32\Common\WinCommon.h" #endif //#include "DasherGameMode.h" #include "DasherViewSquare.h" #include "DasherModel.h" #include "DasherView.h" #include "DasherTypes.h" #include "Event.h" #include "EventHandler.h" #include <algorithm> #include <iostream> #include <limits> #include <stdlib.h> using namespace Dasher; using namespace Opts; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG_MEMLEAKS #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif // FIXME - quite a lot of the code here probably should be moved to // the parent class (DasherView). I think we really should make the // parent class less general - we're probably not going to implement // anything which uses radically different co-ordinate transforms, and // we can always override if necessary. // FIXME - duplicated 'mode' code throught - needs to be fixed (actually, mode related stuff, Input2Dasher etc should probably be at least partially in some other class) CDasherViewSquare::CDasherViewSquare(CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CDasherScreen *DasherScreen) : CDasherView(pEventHandler, pSettingsStore, DasherScreen), m_Y1(4), m_Y2(0.95 * GetLongParameter(LP_MAX_Y)), m_Y3(0.05 * GetLongParameter((LP_MAX_Y))) { // TODO - AutoOffset should be part of the eyetracker input filter // Make sure that the auto calibration is set to zero berfore we start // m_yAutoOffset = 0; ChangeScreen(DasherScreen); //Note, nonlinearity parameters set in SetScaleFactor m_bVisibleRegionValid = false; } CDasherViewSquare::~CDasherViewSquare() {} void CDasherViewSquare::HandleEvent(Dasher::CEvent *pEvent) { // Let the parent class do its stuff CDasherView::HandleEvent(pEvent); // And then interpret events for ourself if(pEvent->m_iEventType == 1) { Dasher::CParameterNotificationEvent * pEvt(static_cast < Dasher::CParameterNotificationEvent * >(pEvent)); switch (pEvt->m_iParameter) { case LP_REAL_ORIENTATION: case LP_MARGIN_WIDTH: case BP_NONLINEAR_Y: case LP_NONLINEAR_X: m_bVisibleRegionValid = false; SetScaleFactor(); break; default: break; } } } /// Draw text specified in Dasher co-ordinates. The position is /// specified as two co-ordinates, intended to the be the corners of /// the leading edge of the containing box. void CDasherViewSquare::DasherDrawText(myint iAnchorX1, myint iAnchorY1, myint iAnchorX2, myint iAnchorY2, const std::string &sDisplayText, int &mostleft, bool bShove) { // Don't draw text which will overlap with text in an ancestor. if(iAnchorX1 > mostleft) iAnchorX1 = mostleft; if(iAnchorX2 > mostleft) iAnchorX2 = mostleft; myint iDasherMinX; myint iDasherMinY; myint iDasherMaxX; myint iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); iAnchorY1 = std::min( iDasherMaxY, std::max( iDasherMinY, iAnchorY1 ) ); iAnchorY2 = std::min( iDasherMaxY, std::max( iDasherMinY, iAnchorY2 ) ); screenint iScreenAnchorX1; screenint iScreenAnchorY1; screenint iScreenAnchorX2; screenint iScreenAnchorY2; // FIXME - Truncate here before converting - otherwise we risk integer overflow in screen coordinates Dasher2Screen(iAnchorX1, iAnchorY1, iScreenAnchorX1, iScreenAnchorY1); Dasher2Screen(iAnchorX2, iAnchorY2, iScreenAnchorX2, iScreenAnchorY2); // Truncate the ends of the anchor line to be on the screen - this // prevents us from loosing characters off the top and bottom of the // screen // TruncateToScreen(iScreenAnchorX1, iScreenAnchorY1); // TruncateToScreen(iScreenAnchorX2, iScreenAnchorY2); // Actual anchor point is the midpoint of the anchor line screenint iScreenAnchorX((iScreenAnchorX1 + iScreenAnchorX2) / 2); screenint iScreenAnchorY((iScreenAnchorY1 + iScreenAnchorY2) / 2); // Compute font size based on position int Size = GetLongParameter( LP_DASHER_FONTSIZE ); // FIXME - this could be much more elegant, and probably needs a // rethink anyway - behvaiour here is too dependent on screen size screenint iLeftTimesFontSize = ((myint)GetLongParameter(LP_MAX_Y) - (iAnchorX1 + iAnchorX2)/ 2 )*Size; if(iLeftTimesFontSize < (myint)GetLongParameter(LP_MAX_Y) * 19/ 20) Size *= 20; else if(iLeftTimesFontSize < (myint)GetLongParameter(LP_MAX_Y) * 159 / 160) Size *= 14; else Size *= 11; screenint TextWidth, TextHeight; Screen()->TextSize(sDisplayText, &TextWidth, &TextHeight, Size); // Poistion of text box relative to anchor depends on orientation screenint newleft2 = 0; screenint newtop2 = 0; screenint newright2 = 0; screenint newbottom2 = 0; switch (Dasher::Opts::ScreenOrientations(GetLongParameter(LP_REAL_ORIENTATION))) { case (Dasher::Opts::LeftToRight): newleft2 = iScreenAnchorX; newtop2 = iScreenAnchorY - TextHeight / 2; newright2 = iScreenAnchorX + TextWidth; newbottom2 = iScreenAnchorY + TextHeight / 2; break; case (Dasher::Opts::RightToLeft): newleft2 = iScreenAnchorX - TextWidth; newtop2 = iScreenAnchorY - TextHeight / 2; newright2 = iScreenAnchorX; newbottom2 = iScreenAnchorY + TextHeight / 2; break; case (Dasher::Opts::TopToBottom): newleft2 = iScreenAnchorX - TextWidth / 2; newtop2 = iScreenAnchorY; newright2 = iScreenAnchorX + TextWidth / 2; newbottom2 = iScreenAnchorY + TextHeight; break; case (Dasher::Opts::BottomToTop): newleft2 = iScreenAnchorX - TextWidth / 2; newtop2 = iScreenAnchorY - TextHeight; newright2 = iScreenAnchorX + TextWidth / 2; newbottom2 = iScreenAnchorY; break; default: break; } // Update the value of mostleft to take into account the new text if(bShove) { myint iDasherNewLeft; myint iDasherNewTop; myint iDasherNewRight; myint iDasherNewBottom; Screen2Dasher(newleft2, newtop2, iDasherNewLeft, iDasherNewTop); Screen2Dasher(newright2, newbottom2, iDasherNewRight, iDasherNewBottom); mostleft = std::min(iDasherNewRight, iDasherNewLeft); } - + + + // Tell other listeners that text has been drawn and provide some information + // about the draw call. + m_pEventHandler->InsertEvent(new CTextDrawEvent(sDisplaytext, newleft2, newtop2, Size)); + // Actually draw the text. We use DelayDrawText as the text should // be overlayed once all of the boxes have been drawn. m_DelayDraw.DelayDrawText(sDisplayText, newleft2, newtop2, Size); } void CDasherViewSquare::RenderNodes(CDasherNode *pRoot, myint iRootMin, myint iRootMax, CExpansionPolicy &policy) { DASHER_ASSERT(pRoot != 0); myint iDasherMinX; myint iDasherMinY; myint iDasherMaxX; myint iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); // screenint iScreenLeft; screenint iScreenTop; screenint iScreenRight; screenint iScreenBottom; Dasher2Screen(iRootMax-iRootMin, iRootMin, iScreenLeft, iScreenTop); Dasher2Screen(0, iRootMax, iScreenRight, iScreenBottom); //ifiScreenTop < 0) // iScreenTop = 0; //if(iScreenLeft < 0) // iScreenLeft=0; //// TODO: Should these be right on the boundary? //if(iScreenBottom > Screen()->GetHeight()) // iScreenBottom=Screen()->GetHeight(); //if(iScreenRight > Screen()->GetWidth()) // iScreenRight=Screen()->GetWidth(); // Blank the region around the root node: if(iRootMin > iDasherMinY) DasherDrawRectangle(iDasherMaxX, iDasherMinY, iDasherMinX, iRootMin, 0, -1, Nodes1, 0); //if(iScreenTop > 0) // Screen()->DrawRectangle(0, 0, Screen()->GetWidth(), iScreenTop, 0, -1, Nodes1, false, true, 1); if(iRootMax < iDasherMaxY) DasherDrawRectangle(iDasherMaxX, iRootMax, iDasherMinX, iDasherMaxY, 0, -1, Nodes1, 0); //if(iScreenBottom <= Screen()->GetHeight()) // Screen()->DrawRectangle(0, iScreenBottom, Screen()->GetWidth(), Screen()->GetHeight(), 0, -1, Nodes1, false, true, 1); DasherDrawRectangle(0, iDasherMinY, iDasherMinX, iDasherMaxY, 0, -1, Nodes1, 0); // Screen()->DrawRectangle(iScreenRight, std::max(0, (int)iScreenTop), // Screen()->GetWidth(), std::min(Screen()->GetHeight(), (int)iScreenBottom), // 0, -1, Nodes1, false, true, 1); // Render the root node (and children) RecursiveRender(pRoot, iRootMin, iRootMax, iDasherMaxX, policy, std::numeric_limits<double>::infinity(), iDasherMaxX,0,0); // Labels are drawn in a second parse to get the overlapping right m_DelayDraw.Draw(Screen()); // Finally decorate the view Crosshair((myint)GetLongParameter(LP_OX)); } //min size in *Dasher co-ordinates* to consider rendering a node #define QUICK_REJECT 50 //min size in *screen* (pixel) co-ordinates to render a node #define MIN_SIZE 2 bool CDasherViewSquare::CheckRender(CDasherNode *pRender, myint y1, myint y2, int mostleft, CExpansionPolicy &policy, double dMaxCost, myint parent_width, int parent_color, int iDepth) { if (y2-y1 >= QUICK_REJECT) { myint iDasherMinX; myint iDasherMinY; myint iDasherMaxX; myint iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); if (y1 <= iDasherMaxY && y2 >= iDasherMinY) { screenint iScreenX1; screenint iScreenY1; screenint iScreenX2; screenint iScreenY2; Dasher2Screen(0, std::max(y1, iDasherMinY), iScreenX1, iScreenY1); Dasher2Screen(0, std::min(y2, iDasherMaxY), iScreenX2, iScreenY2); Cint32 iHeight = std::max(myint(iScreenY2 - iScreenY1),myint( 0)); if (iHeight >= MIN_SIZE) { //node should be rendered! RecursiveRender(pRender, y1, y2, mostleft, policy, dMaxCost, parent_width, parent_color, iDepth); return true; } } } // We get here if the node is too small to render or is off-screen. // So, collapse it immediately. // // In game mode, we get here if the child is too small to draw, but we need the // coordinates - if this is the case then we shouldn't delete any children. // // TODO: Should probably render the parent segment here anyway (or // in the above) if(!pRender->GetFlag(NF_GAME)) pRender->Delete_children(); return false; } void CDasherViewSquare::RecursiveRender(CDasherNode *pRender, myint y1, myint y2, int mostleft, CExpansionPolicy &policy, double dMaxCost, myint parent_width,int parent_color, int iDepth) { DASHER_ASSERT_VALIDPTR_RW(pRender); // if(iDepth == 2) // std::cout << pRender->GetDisplayInfo()->strDisplayText << std::endl; // TODO: We need an overhall of the node creation/deletion logic - // make sure that we only maintain the minimum number of nodes which // are actually needed. This is especially true at the moment in // Game mode, which feels very sluggish. Node creation also feels // slower in Windows than Linux, especially if many nodes are // created at once (eg untrained Hiragana) ++m_iRenderCount; // myint trange = y2 - y1; // Attempt to draw the region to the left of this node inside its parent. // if(iDepth == 2) { // std::cout << "y1: " << y1 << " y2: " << y2 << std::endl; // Set the NF_SUPER flag if this node entirely frames the visual // area. // TODO: too slow? // TODO: use flags more rather than delete/reparent lists myint iDasherMinX; myint iDasherMinY; myint iDasherMaxX; myint iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); DasherDrawRectangle(std::min(parent_width,iDasherMaxX), std::max(y1,iDasherMinY), std::min(y2-y1,iDasherMaxX), std::min(y2,iDasherMaxY), parent_color, -1, Nodes1, 0); const std::string &sDisplayText(pRender->getDisplayText()); if( sDisplayText.size() > 0 ) { DasherDrawText(y2-y1, y1, y2-y1, y2, sDisplayText, mostleft, pRender->bShove()); } pRender->SetFlag(NF_SUPER, !IsSpaceAroundNode(y1,y2)); // If there are no children then we still need to render the parent if(pRender->ChildCount() == 0) { DasherDrawRectangle(std::min(y2-y1,iDasherMaxX), std::min(y2,iDasherMaxY),0, std::max(y1,iDasherMinY), pRender->getColour(), -1, Nodes1, 0); //also allow it to be expanded, it's big enough. policy.pushNode(pRender, y1, y2, true, dMaxCost); return; } //Node has children. It can therefore be collapsed...however, // we don't allow a node covering the crosshair to be collapsed // (at best this'll mean there's nowhere useful to go forwards; // at worst, all kinds of crashes trying to do text output!) if (!pRender->GetFlag(NF_GAME) && !pRender->GetFlag(NF_SEEN)) dMaxCost = policy.pushNode(pRender, y1, y2, false, dMaxCost); // Render children int norm = (myint)GetLongParameter(LP_NORMALIZATION); myint lasty=y1; int id=-1; // int lower=-1,upper=-1; myint temp_parentwidth=y2-y1; int temp_parentcolor = pRender->getColour(); const myint Range(y2 - y1); if (CDasherNode *pChild = pRender->onlyChildRendered) { //if child still covers screen, render _just_ it and return myint newy1 = y1 + (Range * (myint)pChild->Lbnd()) / (myint)norm; myint newy2 = y1 + (Range * (myint)pChild->Hbnd()) / (myint)norm; if (newy1 < iDasherMinY && newy2 > iDasherMaxY) { //still covers entire screen. Parent should too... DASHER_ASSERT(dMaxCost == std::numeric_limits<double>::infinity()); //don't inc iDepth, meaningless when covers the screen RecursiveRender(pChild, newy1, newy2, mostleft, policy, dMaxCost, temp_parentwidth, temp_parentcolor, iDepth); //leave pRender->onlyChildRendered set, so remaining children are skipped } else pRender->onlyChildRendered = NULL; } if (!pRender->onlyChildRendered) { //render all children... for(CDasherNode::ChildMap::const_iterator i = pRender->GetChildren().begin(); i != pRender->GetChildren().end(); i++) { id++; CDasherNode *pChild = *i; myint newy1 = y1 + (Range * (myint)pChild->Lbnd()) / (myint)norm;/// norm and lbnd are simple ints myint newy2 = y1 + (Range * (myint)pChild->Hbnd()) / (myint)norm; if (newy1 < iDasherMinY && newy2 > iDasherMaxY) { DASHER_ASSERT(dMaxCost == std::numeric_limits<double>::infinity()); pRender->onlyChildRendered = pChild; RecursiveRender(pChild, newy1, newy2, mostleft, policy, dMaxCost, temp_parentwidth, temp_parentcolor, iDepth); //ensure we don't blank over this child in "finishing off" the parent (!) lasty=newy2; break; //no need to render any more children! } if (CheckRender(pChild, newy1, newy2, mostleft, policy, dMaxCost, temp_parentwidth, temp_parentcolor, iDepth+1)) { if (lasty<newy1) { //if child has been drawn then the interval between him and the //last drawn child should be drawn too. //std::cout << "Fill in: " << lasty << " " << newy1 << std::endl; RenderNodePartFast(temp_parentcolor, lasty, newy1, mostleft, pRender->getDisplayText(), pRender->bShove(), temp_parentwidth); } lasty = newy2; } } // Finish off the drawing process // if(iDepth == 1) { // Theres a chance that we haven't yet filled the entire parent, so finish things off if necessary. if(lasty<y2) { RenderNodePartFast(temp_parentcolor, lasty, y2, mostleft, pRender->getDisplayText(), pRender->bShove(), temp_parentwidth); } } // Draw the outline if(pRender->getColour() != -1) {//-1 = invisible RenderNodeOutlineFast(pRender->getColour(), y1, y2, mostleft, pRender->getDisplayText(), pRender->bShove()); } // } } bool CDasherViewSquare::IsSpaceAroundNode(myint y1, myint y2) { myint iDasherMinX; myint iDasherMinY; myint iDasherMaxX; myint iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); return ((y2 - y1) < iDasherMaxX) || (y1 > iDasherMinY) || (y2 < iDasherMaxY); } // Draw the outline of a node int CDasherViewSquare::RenderNodeOutlineFast(const int Color, myint y1, myint y2, int &mostleft, const std::string &sDisplayText, bool bShove) { // Commenting because click mode occasionally fails this assert. // I don't know why. -- cjb. if (!(y2 >= y1)) { return 1; } // TODO - Get sensible limits here (to allow for non-linearities) myint iDasherMinX; myint iDasherMinY; myint iDasherMaxX; myint iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); screenint iScreenX1; screenint iScreenY1; screenint iScreenX2; screenint iScreenY2; Dasher2Screen(0, std::max(y1, iDasherMinY), iScreenX1, iScreenY1); Dasher2Screen(0, std::min(y2, iDasherMaxY), iScreenX2, iScreenY2); Cint32 iHeight = std::max(myint(iScreenY2 - iScreenY1),myint( 0)); Cint32 iWidth = std::max(myint(iScreenX2 - iScreenX1),myint( 0)); if((iHeight <= 1) && (iWidth <= 1)) return 0; // We're too small to render if((y1 > iDasherMaxY) || (y2 < iDasherMinY)){ return 0; // We're entirely off screen, so don't render. } // TODO: This should be earlier? if(!GetBoolParameter(BP_OUTLINE_MODE)) return 1; myint iDasherSize(y2 - y1); // std::cout << std::min(iDasherSize,iDasherMaxX) << " " << std::min(y2,iDasherMaxY) << " 0 " << std::max(y1,iDasherMinY) << std::endl; DasherDrawRectangle(0, std::min(y1,iDasherMaxY),std::min(iDasherSize,iDasherMaxX), std::max(y2,iDasherMinY), -1, Color, Nodes1, 1); // // FIXME - get rid of pointless assignment below // int iTruncation(GetLongParameter(LP_TRUNCATION)); // Trucation farction times 100; // if(iTruncation == 0) { // Regular squares // } // else { // // TODO: Put something back here? // } return 1; } // Draw a filled block of a node right down to the baseline (intended // for the case when you have no visible child) int CDasherViewSquare::RenderNodePartFast(const int Color, myint y1, myint y2, int &mostleft, const std::string &sDisplayText, bool bShove,myint iParentWidth ) { // Commenting because click mode occasionally fails this assert. // I don't know why. -- cjb. if (!(y2 >= y1)) { return 1; } // TODO - Get sensible limits here (to allow for non-linearities) myint iDasherMinX; myint iDasherMinY; myint iDasherMaxX; myint iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); screenint iScreenX1; screenint iScreenY1; screenint iScreenX2; screenint iScreenY2; Dasher2Screen(0, std::max(y1, iDasherMinY), iScreenX1, iScreenY1); Dasher2Screen(0, std::min(y2, iDasherMaxY), iScreenX2, iScreenY2); // std::cout << "Fill in components: " << iScreenY1 << " " << iScreenY2 << std::endl; Cint32 iHeight = std::max(myint(iScreenY2 - iScreenY1),myint( 0)); Cint32 iWidth = std::max(myint(iScreenX2 - iScreenX1),myint( 0)); if((iHeight < 1) && (iWidth < 1)) { // std::cout << "b" << std::endl; return 0; // We're too small to render } if((y1 > iDasherMaxY) || (y2 < iDasherMinY)){ //std::cout << "a" << std::endl; return 0; // We're entirely off screen, so don't render. } DasherDrawRectangle(std::min(iParentWidth,iDasherMaxX), std::min(y2,iDasherMaxY),0, std::max(y1,iDasherMinY), Color, -1, Nodes1, 0); return 1; } /// Convert screen co-ordinates to dasher co-ordinates. This doesn't /// include the nonlinear mapping for eyetracking mode etc - it is /// just the inverse of the mapping used to calculate the screen /// positions of boxes etc. void CDasherViewSquare::Screen2Dasher(screenint iInputX, screenint iInputY, myint &iDasherX, myint &iDasherY) { // Things we're likely to need: //myint iDasherWidth = (myint)GetLongParameter(LP_MAX_Y); myint iDasherHeight = (myint)GetLongParameter(LP_MAX_Y); screenint iScreenWidth = Screen()->GetWidth(); screenint iScreenHeight = Screen()->GetHeight(); int eOrientation(GetLongParameter(LP_REAL_ORIENTATION)); switch(eOrientation) { case Dasher::Opts::LeftToRight: iDasherX = iCenterX - ( iInputX - iScreenWidth / 2 ) * m_iScalingFactor / iScaleFactorX; iDasherY = iDasherHeight / 2 + ( iInputY - iScreenHeight / 2 ) * m_iScalingFactor / iScaleFactorY; break; case Dasher::Opts::RightToLeft: iDasherX = myint(iCenterX + ( iInputX - iScreenWidth / 2 ) * m_iScalingFactor/ iScaleFactorX); iDasherY = myint(iDasherHeight / 2 + ( iInputY - iScreenHeight / 2 ) * m_iScalingFactor/ iScaleFactorY); break; case Dasher::Opts::TopToBottom: iDasherX = myint(iCenterX - ( iInputY - iScreenHeight / 2 ) * m_iScalingFactor/ iScaleFactorY); iDasherY = myint(iDasherHeight / 2 + ( iInputX - iScreenWidth / 2 ) * m_iScalingFactor/ iScaleFactorX); break; case Dasher::Opts::BottomToTop: iDasherX = myint(iCenterX + ( iInputY - iScreenHeight / 2 ) * m_iScalingFactor/ iScaleFactorY); iDasherY = myint(iDasherHeight / 2 + ( iInputX - iScreenWidth / 2 ) * m_iScalingFactor/ iScaleFactorX); break; } iDasherX = ixmap(iDasherX); iDasherY = iymap(iDasherY); } void CDasherViewSquare::SetScaleFactor( void ) { //Parameters for X non-linearity. // Set some defaults here, in case we change(d) them later... m_dXmpb = 0.5; //threshold: DasherX's less than (m_dXmpb * MAX_Y) are linear... m_dXmpc = 0.9; //...but multiplied by m_dXmpc; DasherX's above that, are logarithmic... //set log scaling coefficient (unused if LP_NONLINEAR_X==0) // note previous value of m_dXmpa = 0.2, i.e. a value of LP_NONLINEAR_X =~= 4.8 m_dXmpa = exp(GetLongParameter(LP_NONLINEAR_X)/-3.0); myint iDasherWidth = (myint)GetLongParameter(LP_MAX_Y); myint iDasherHeight = iDasherWidth; screenint iScreenWidth = Screen()->GetWidth(); screenint iScreenHeight = Screen()->GetHeight(); // Try doing this a different way: myint iDasherMargin( GetLongParameter(LP_MARGIN_WIDTH) ); // Make this a parameter myint iMinX( 0-iDasherMargin ); myint iMaxX( iDasherWidth ); iCenterX = (iMinX + iMaxX)/2; myint iMinY( 0 ); myint iMaxY( iDasherHeight ); Dasher::Opts::ScreenOrientations eOrientation(Dasher::Opts::ScreenOrientations(GetLongParameter(LP_REAL_ORIENTATION))); double dScaleFactorX, dScaleFactorY; if (eOrientation == Dasher::Opts::LeftToRight || eOrientation == Dasher::Opts::RightToLeft) { dScaleFactorX = iScreenWidth / static_cast<double>( iMaxX - iMinX ); dScaleFactorY = iScreenHeight / static_cast<double>( iMaxY - iMinY ); } else { dScaleFactorX = iScreenHeight / static_cast<double>( iMaxX - iMinX ); dScaleFactorY = iScreenWidth / static_cast<double>( iMaxY - iMinY ); } if (dScaleFactorX < dScaleFactorY) { //fewer (pixels per dasher coord) in X direction - i.e., X is more compressed. //So, use X scale for Y too...except first, we'll _try_ to reduce the difference // by changing the relative scaling of X and Y (by at most 20%): double dMul = max(0.8, dScaleFactorX / dScaleFactorY); m_dXmpc *= dMul; dScaleFactorX /= dMul; iScaleFactorX = myint(dScaleFactorX * m_iScalingFactor); iScaleFactorY = myint(std::max(dScaleFactorX, dScaleFactorY / 4.0) * m_iScalingFactor); } else { //X has more room; use Y scale for both -> will get lots history iScaleFactorX = myint(std::max(dScaleFactorY, dScaleFactorX / 4.0) * m_iScalingFactor); iScaleFactorY = myint(dScaleFactorY * m_iScalingFactor); // however, "compensate" by relaxing the default "relative scaling" of X // (normally only 90% of Y) towards 1... m_dXmpc = std::min(1.0,0.9 * dScaleFactorX / dScaleFactorY); } iCenterX *= m_dXmpc; } inline myint CDasherViewSquare::CustomIDiv(myint iNumerator, myint iDenominator) { // Integer division rounding away from zero long long int num, denom, quot, rem; myint res; num = iNumerator; denom = iDenominator; DASHER_ASSERT(denom != 0); #ifdef HAVE_LLDIV lldiv_t ans = ::lldiv(num, denom); quot = ans.quot; rem = ans.rem; #else quot = num / denom; rem = num % denom; #endif if (rem < 0) res = quot - 1; else if (rem > 0) res = quot + 1; else res = quot; diff --git a/Src/DasherCore/Event.h b/Src/DasherCore/Event.h index 542972a..7e56c54 100644 --- a/Src/DasherCore/Event.h +++ b/Src/DasherCore/Event.h @@ -1,136 +1,169 @@ #ifndef __event_h__ #define __event_h__ // Classes representing different event types. #include <string> #include "DasherTypes.h" namespace Dasher { class CEvent; class CParameterNotificationEvent; class CEditEvent; class CEditContextEvent; class CStartEvent; class CStopEvent; class CControlEvent; class CLockEvent; class CMessageEvent; class CCommandEvent; } enum { - EV_PARAM_NOTIFY = 1, EV_EDIT, EV_EDIT_CONTEXT, EV_START, EV_STOP, EV_CONTROL, EV_LOCK, EV_MESSAGE, EV_COMMAND + EV_PARAM_NOTIFY = 1, EV_EDIT, EV_EDIT_CONTEXT, EV_START, EV_STOP, EV_CONTROL, EV_LOCK, EV_MESSAGE, EV_COMMAND, EV_TEXTDRAW }; /// \ingroup Core /// @{ /// \defgroup Events Events generated by Dasher modules. /// @{ class Dasher::CEvent { public: int m_iEventType; }; class Dasher::CParameterNotificationEvent:public Dasher::CEvent { public: CParameterNotificationEvent(int iParameter) { m_iEventType = EV_PARAM_NOTIFY; m_iParameter = iParameter; }; int m_iParameter; }; class Dasher::CEditEvent:public Dasher::CEvent { public: CEditEvent(int iEditType, const std::string & sText, int iOffset) { m_iEventType = EV_EDIT; m_iEditType = iEditType; m_sText = sText; m_iOffset = iOffset; }; int m_iEditType; std::string m_sText; int m_iOffset; }; class Dasher::CEditContextEvent:public Dasher::CEvent { public: CEditContextEvent(int iOffset, int iLength) { m_iEventType = EV_EDIT_CONTEXT; m_iOffset = iOffset; m_iLength = iLength; }; int m_iOffset; int m_iLength; }; +/** + * An event that signals text has been drawn. Useful for determining its location + * because that information is only available at draw time. + */ +class Dasher::CTextDrawEvent : public Dasher::CEvent { +public: + CTextDrawEvent(std::string sDisplayText, screenint iX, screenint iY, int iSize) + :m_sDisplayText(sDisplayText), + m_iX(iX), + m_iY(iY), + m_iSize(iSize) + { }; + /** + * The text that has been drawn. + */ + std::string m_sDisplayText; + + /** + * The X position (in screen coordinates) of the center of the box surrounding the text. + */ + screenint m_iX; + + /** + * The Y position (in screen coordinates) of the center of the box surrounding the text. + */ + screenint m_iY; + + /** + * The size of the text. Useful for determining the boundaries of the text "box" + */ + int m_iSize; +}; + class Dasher::CStartEvent:public Dasher::CEvent { public: CStartEvent() { m_iEventType = EV_START; }; }; class Dasher::CStopEvent:public Dasher::CEvent { public: CStopEvent() { m_iEventType = EV_STOP; }; }; class Dasher::CControlEvent:public Dasher::CEvent { public: CControlEvent(int iID) { m_iEventType = EV_CONTROL; m_iID = iID; }; int m_iID; }; class Dasher::CLockEvent : public Dasher::CEvent { public: CLockEvent(const std::string &strMessage, bool bLock, int iPercent) { m_iEventType = EV_LOCK; m_strMessage = strMessage; m_bLock = bLock; m_iPercent = iPercent; }; std::string m_strMessage; bool m_bLock; int m_iPercent; }; class Dasher::CMessageEvent : public Dasher::CEvent { public: CMessageEvent(const std::string &strMessage, int iID, int iType) { m_iEventType = EV_MESSAGE; m_strMessage = strMessage; m_iID = iID; m_iType = iType; }; std::string m_strMessage; int m_iID; int m_iType; }; class Dasher::CCommandEvent : public Dasher::CEvent { public: CCommandEvent(const std::string &strCommand) { m_iEventType = EV_COMMAND; m_strCommand = strCommand; }; std::string m_strCommand; }; /// @} /// @} #endif diff --git a/Src/DasherCore/FileWordGenerator.cpp b/Src/DasherCore/FileWordGenerator.cpp index 8dde340..833685e 100644 --- a/Src/DasherCore/FileWordGenerator.cpp +++ b/Src/DasherCore/FileWordGenerator.cpp @@ -1,35 +1,31 @@ #include "FileWordGenerator.h" bool CFileWordGenerator::Generate() { if(!m_bWordsReady) { ifstream file_in; file_in.open(path.c_str()); char buffer; while(file_in.good()) { buffer = file_in.get(); m_sGeneratedString.append(buffer); } m_uiPos = 0; } } std::string CFileWordGenerator::GetPath() { return m_sPath; } std::string CFileWordGenerator::GetFilename() { return m_sPath.substr(m_sPath.rfind("/")); } void CFileWordGenerator::SetSource(std::string newPath) { m_sPath = newPath; m_bWordsReady = false; Generate(); } virtual std::string CFileWordGenerator::GetNextWord() { return m_sGeneratedString.substr(m_uiPos, m_sGeneratedString.find(" ")); } - -virtual std::string CFileWordGerneator::GetPreWord() { - return "Not yet implemented. Sorry!"; -} diff --git a/Src/DasherCore/GameModule.cpp b/Src/DasherCore/GameModule.cpp index 9b73984..e4e4395 100644 --- a/Src/DasherCore/GameModule.cpp +++ b/Src/DasherCore/GameModule.cpp @@ -1,38 +1,45 @@ #include "GameModule.h" void CGameModule::HandleEvent(Dasher::CEvent *pEvent) { switch(pEvent->m_iEventType) { case EV_EDIT: switch(static_cast<CEditEvent*>(pEvent)->m_iEditType) { // Added a new character (Stepped one node forward) case 0: currentStringPos++; pLastTypedNode = StringToNode(pEvent->m_sText); break; // Removed a character (Stepped one node back) case 1: break; default: break; } break; + case EV_TEXTDRAW: + CTextDrawEvent* evt = static_cast<CTextDrawEvent*>(pEvent); + if(!m_sTargetString[m_stCurrentStringPos + 1].compare(evt->m_sDisplayText)) { + // TODO: Write this function on the view to draw an arrow to a given point. + //m_pView->DrawArrowTo(evt->m_iX, evt->m_iY, evt->m_iSize); + } default: - break; + break; } return; } CDasherNode CGameModule::StringToNode(std::string sText) { } std::string CGameModule::GetTypedTarget() { return m_sTargetString.substr(0, m_stCurrentStringPos - 1); } std::string CGameModule::GetUntypedtarget() { return m_sTargetString.substr(m_stCurrentStringPos); } + diff --git a/Src/DasherCore/GameModule.h b/Src/DasherCore/GameModule.h index 2c15a23..f7d5637 100644 --- a/Src/DasherCore/GameModule.h +++ b/Src/DasherCore/GameModule.h @@ -1,92 +1,93 @@ // GameModule.h #ifndef GAME_MODULE_H #define GAME_MODULE_H #include <string> using namespace std; #include "DasherModule.h" #include "DasherModel.h" #include "DasherNode.h" #include "DasherView.h" +#include "DasherTypes.h" namespace Dasher { class CDasherInterfaceBase; } namespace Dasher { /** * This Dasher Module encapsulates all game mode logic. In game mode, users will be given * a target string to type as well as visual feedback for their progress and a helpful * arrow to guide them in the right path through the dasher model. * * This class handles logic and drawing code with respect to the above. */ class CGameModule : public CDasherModule { public: // I don't actually know what the type is supposed to be for this...it's not an input method or an input filter. // Maybe we should define a new one. I've labeled it 0 for now. - rgee CGameModule(Dasher::CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CDasherInterfaceBase *pInterface, ModuleID_t iID, const char *szName) : CDasherModule(pEventHandler, pSettingsStore, iID, 0, szName) { m_pInterface = pInterface; } /** * Handle events from the event processing system * @param pEvent The event to be processed. */ void HandleEvent(Dasher::CEvent *pEvent); /** * Gets the typed portion of the target string * @return The string that represents the current word(s) that have not been typed */ inline std::string GetTypedTarget(); /** * Gets the portion of the target string that has yet to be completed * @return The string that represents the current word(s) that have been typed */ inline std::string GetUntypedTarget(); inline void SetDasherModel(CDasherModel *pModel) { m_pModel = pModel; } private: /** * Searches for the dasher node under the current root that represents the desired string * @param text The string to search for * @return The node representing the string parameter */ CDasherNode StringToNode(std::string sText) /** * The last node the user typed. */ CDasherNode *pLastTypedNode; /** * The next node (character) the user must type. */ CDasherNode *pNextTargetNode; /** * The target string the user must type. */ std::string m_sTargetString; /** * The current position in the string. * Stored as a size_t to easily use substrings to determine what's been typed and what hasn't. */ size_t m_stCurrentStringPos; /** * The dasher model. */ CDasherModel *m_pModel; }; } #endif
rgee/HFOSS-Dasher
f3123f614e50cd4d378b529d9aa1fb6f911617c9
Continued work integrating the game module into dasher - still have some work to do. Have some cout statements lying around
diff --git a/Src/DasherCore/DasherInterfaceBase.cpp b/Src/DasherCore/DasherInterfaceBase.cpp index 0a1fc60..db7cd91 100644 --- a/Src/DasherCore/DasherInterfaceBase.cpp +++ b/Src/DasherCore/DasherInterfaceBase.cpp @@ -1,1156 +1,1167 @@ // DasherInterfaceBase.cpp // // Copyright (c) 2008 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" #include "DasherInterfaceBase.h" //#include "ActionButton.h" #include "DasherViewSquare.h" #include "ControlManager.h" #include "DasherScreen.h" #include "DasherView.h" #include "DasherInput.h" #include "DasherModel.h" #include "EventHandler.h" #include "Event.h" #include "NodeCreationManager.h" #ifndef _WIN32_WCE #include "UserLog.h" #include "BasicLog.h" #endif #include "DasherGameMode.h" // Input filters #include "AlternatingDirectMode.h" #include "ButtonMode.h" #include "ClickFilter.h" #include "CompassMode.h" #include "DefaultFilter.h" #include "EyetrackerFilter.h" #include "OneButtonFilter.h" #include "OneButtonDynamicFilter.h" #include "OneDimensionalFilter.h" #include "StylusFilter.h" #include "TwoButtonDynamicFilter.h" #include "TwoPushDynamicFilter.h" // STL headers #include <cstdio> #include <iostream> #include <memory> // Declare our global file logging object #include "../DasherCore/FileLogger.h" #ifdef _DEBUG const eLogLevel g_iLogLevel = logDEBUG; const int g_iLogOptions = logTimeStamp | logDateStamp | logDeleteOldFile; #else const eLogLevel g_iLogLevel = logNORMAL; const int g_iLogOptions = logTimeStamp | logDateStamp; #endif #ifndef _WIN32_WCE CFileLogger* g_pLogger = NULL; #endif using namespace Dasher; using namespace std; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG_MEMLEAKS #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif CDasherInterfaceBase::CDasherInterfaceBase() { // Ensure that pointers to 'owned' objects are set to NULL. m_Alphabet = NULL; m_pDasherModel = NULL; m_DasherScreen = NULL; m_pDasherView = NULL; m_pInput = NULL; m_pInputFilter = NULL; m_AlphIO = NULL; m_ColourIO = NULL; m_pUserLog = NULL; m_pNCManager = NULL; m_defaultPolicy = NULL; m_pGameModule = NULL; // Various state variables m_bRedrawScheduled = false; m_iCurrentState = ST_START; // m_bGlobalLock = false; // TODO: Are these actually needed? strCurrentContext = ". "; strTrainfileBuffer = ""; // Create an event handler. m_pEventHandler = new CEventHandler(this); m_bLastChanged = true; #ifndef _WIN32_WCE // Global logging object we can use from anywhere g_pLogger = new CFileLogger("dasher.log", g_iLogLevel, g_iLogOptions); #endif } void CDasherInterfaceBase::Realize() { // TODO: What exactly needs to have happened by the time we call Realize()? CreateSettingsStore(); SetupUI(); SetupPaths(); std::vector<std::string> vAlphabetFiles; ScanAlphabetFiles(vAlphabetFiles); m_AlphIO = new CAlphIO(GetStringParameter(SP_SYSTEM_LOC), GetStringParameter(SP_USER_LOC), vAlphabetFiles); std::vector<std::string> vColourFiles; ScanColourFiles(vColourFiles); m_ColourIO = new CColourIO(GetStringParameter(SP_SYSTEM_LOC), GetStringParameter(SP_USER_LOC), vColourFiles); ChangeColours(); ChangeAlphabet(); // This creates the NodeCreationManager, the Alphabet // Create the user logging object if we are suppose to. We wait // until now so we have the real value of the parameter and not // just the default. // TODO: Sort out log type selection #ifndef _WIN32_WCE int iUserLogLevel = GetLongParameter(LP_USER_LOG_LEVEL_MASK); if(iUserLogLevel == 10) m_pUserLog = new CBasicLog(m_pEventHandler, m_pSettingsStore); else if (iUserLogLevel > 0) m_pUserLog = new CUserLog(m_pEventHandler, m_pSettingsStore, iUserLogLevel, m_Alphabet); #else m_pUserLog = NULL; #endif CreateModules(); CreateInput(); CreateInputFilter(); SetupActionButtons(); CParameterNotificationEvent oEvent(LP_NODE_BUDGET); InterfaceEventHandler(&oEvent); //if game mode is enabled , initialize the game module - if(GetBoolParameter(BP_GAME_MODE)) + // if(GetBoolParameter(BP_GAME_MODE)) InitGameModule(); // Set up real orientation to match selection if(GetLongParameter(LP_ORIENTATION) == Dasher::Opts::AlphabetDefault) SetLongParameter(LP_REAL_ORIENTATION, m_Alphabet->GetOrientation()); else SetLongParameter(LP_REAL_ORIENTATION, GetLongParameter(LP_ORIENTATION)); // FIXME - need to rationalise this sort of thing. // InvalidateContext(true); ScheduleRedraw(); #ifndef _WIN32_WCE // All the setup is done by now, so let the user log object know // that future parameter changes should be logged. if (m_pUserLog != NULL) m_pUserLog->InitIsDone(); #endif // TODO: Make things work when model is created latet ChangeState(TR_MODEL_INIT); using GameMode::CDasherGameMode; // Create the teacher singleton object. CDasherGameMode::CreateTeacher(m_pEventHandler, m_pSettingsStore, this); CDasherGameMode::GetTeacher()->SetDasherView(m_pDasherView); CDasherGameMode::GetTeacher()->SetDasherModel(m_pDasherModel); } CDasherInterfaceBase::~CDasherInterfaceBase() { DASHER_ASSERT(m_iCurrentState == ST_SHUTDOWN); // It may seem odd that InterfaceBase does not "own" the teacher. // This is because game mode is a different layer, in a sense. GameMode::CDasherGameMode::DestroyTeacher(); delete m_pDasherModel; // The order of some of these deletions matters delete m_Alphabet; delete m_pDasherView; delete m_ColourIO; delete m_AlphIO; delete m_pNCManager; // Do NOT delete Edit box or Screen. This class did not create them. #ifndef _WIN32_WCE // When we destruct on shutdown, we'll output any detailed log file if (m_pUserLog != NULL) { m_pUserLog->OutputFile(); delete m_pUserLog; m_pUserLog = NULL; } if (g_pLogger != NULL) { delete g_pLogger; g_pLogger = NULL; } #endif for (std::vector<CActionButton *>::iterator it=m_vLeftButtons.begin(); it != m_vLeftButtons.end(); ++it) delete *it; for (std::vector<CActionButton *>::iterator it=m_vRightButtons.begin(); it != m_vRightButtons.end(); ++it) delete *it; // Must delete event handler after all CDasherComponent derived classes delete m_pEventHandler; } void CDasherInterfaceBase::PreSetNotify(int iParameter, const std::string &sNewValue) { // FIXME - make this a more general 'pre-set' event in the message // infrastructure switch(iParameter) { case SP_ALPHABET_ID: // Cycle the alphabet history if(GetStringParameter(SP_ALPHABET_ID) != sNewValue) { if(GetStringParameter(SP_ALPHABET_1) != sNewValue) { if(GetStringParameter(SP_ALPHABET_2) != sNewValue) { if(GetStringParameter(SP_ALPHABET_3) != sNewValue) SetStringParameter(SP_ALPHABET_4, GetStringParameter(SP_ALPHABET_3)); SetStringParameter(SP_ALPHABET_3, GetStringParameter(SP_ALPHABET_2)); } SetStringParameter(SP_ALPHABET_2, GetStringParameter(SP_ALPHABET_1)); } SetStringParameter(SP_ALPHABET_1, GetStringParameter(SP_ALPHABET_ID)); } break; } } void CDasherInterfaceBase::InterfaceEventHandler(Dasher::CEvent *pEvent) { if(pEvent->m_iEventType == EV_PARAM_NOTIFY) { Dasher::CParameterNotificationEvent * pEvt(static_cast < Dasher::CParameterNotificationEvent * >(pEvent)); switch (pEvt->m_iParameter) { case BP_OUTLINE_MODE: ScheduleRedraw(); break; case BP_DRAW_MOUSE: ScheduleRedraw(); break; case BP_CONTROL_MODE: ScheduleRedraw(); break; case BP_DRAW_MOUSE_LINE: ScheduleRedraw(); break; case LP_ORIENTATION: if(GetLongParameter(LP_ORIENTATION) == Dasher::Opts::AlphabetDefault) // TODO: See comment in DasherModel.cpp about prefered values SetLongParameter(LP_REAL_ORIENTATION, m_Alphabet->GetOrientation()); else SetLongParameter(LP_REAL_ORIENTATION, GetLongParameter(LP_ORIENTATION)); ScheduleRedraw(); break; case SP_ALPHABET_ID: ChangeAlphabet(); ScheduleRedraw(); break; case SP_COLOUR_ID: ChangeColours(); ScheduleRedraw(); break; case SP_DEFAULT_COLOUR_ID: // Delibarate fallthrough case BP_PALETTE_CHANGE: if(GetBoolParameter(BP_PALETTE_CHANGE)) SetStringParameter(SP_COLOUR_ID, GetStringParameter(SP_DEFAULT_COLOUR_ID)); break; case LP_LANGUAGE_MODEL_ID: CreateNCManager(); break; case LP_LINE_WIDTH: ScheduleRedraw(); break; case LP_DASHER_FONTSIZE: ScheduleRedraw(); break; case SP_INPUT_DEVICE: CreateInput(); break; case SP_INPUT_FILTER: CreateInputFilter(); ScheduleRedraw(); break; case BP_DASHER_PAUSED: ScheduleRedraw(); break; case LP_MARGIN_WIDTH: case BP_NONLINEAR_Y: case LP_NONLINEAR_X: ScheduleRedraw(); break; case LP_NODE_BUDGET: delete m_defaultPolicy; m_defaultPolicy = new AmortizedPolicy(GetLongParameter(LP_NODE_BUDGET)); default: break; } } else if(pEvent->m_iEventType == EV_EDIT && !GetBoolParameter(BP_GAME_MODE)) { CEditEvent *pEditEvent(static_cast < CEditEvent * >(pEvent)); if(pEditEvent->m_iEditType == 1) { strCurrentContext += pEditEvent->m_sText; if( strCurrentContext.size() > 20 ) strCurrentContext = strCurrentContext.substr( strCurrentContext.size() - 20 ); if(GetBoolParameter(BP_LM_ADAPTIVE)) strTrainfileBuffer += pEditEvent->m_sText; } else if(pEditEvent->m_iEditType == 2) { strCurrentContext = strCurrentContext.substr( 0, strCurrentContext.size() - pEditEvent->m_sText.size()); if(GetBoolParameter(BP_LM_ADAPTIVE)) strTrainfileBuffer = strTrainfileBuffer.substr( 0, strTrainfileBuffer.size() - pEditEvent->m_sText.size()); } } else if(pEvent->m_iEventType == EV_CONTROL) { CControlEvent *pControlEvent(static_cast <CControlEvent*>(pEvent)); switch(pControlEvent->m_iID) { case CControlManager::CTL_STOP: Pause(); break; case CControlManager::CTL_PAUSE: //Halt Dasher - without a stop event, so does not result in speech etc. SetBoolParameter(BP_DASHER_PAUSED, true); m_pDasherModel->TriggerSlowdown(); } } } void CDasherInterfaceBase::WriteTrainFileFull() { WriteTrainFile(strTrainfileBuffer); strTrainfileBuffer = ""; } void CDasherInterfaceBase::WriteTrainFilePartial() { // TODO: what if we're midway through a unicode character? WriteTrainFile(strTrainfileBuffer.substr(0,100)); strTrainfileBuffer = strTrainfileBuffer.substr(100); } void CDasherInterfaceBase::CreateModel(int iOffset) { // Creating a model without a node creation manager is a bad plan if(!m_pNCManager) return; if(m_pDasherModel) { delete m_pDasherModel; m_pDasherModel = 0; } m_pDasherModel = new CDasherModel(m_pEventHandler, m_pSettingsStore, m_pNCManager, this, m_pDasherView, iOffset); // Notify the teacher of the new model if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) pTeacher->SetDasherModel(m_pDasherModel); } void CDasherInterfaceBase::CreateNCManager() { // TODO: Try and make this work without necessarilty rebuilding the model if(!m_AlphIO) return; int lmID = GetLongParameter(LP_LANGUAGE_MODEL_ID); if( lmID == -1 ) return; int iOffset; if(m_pDasherModel) iOffset = m_pDasherModel->GetOffset(); else iOffset = 0; // TODO: Is this right? // Delete the old model and create a new one if(m_pDasherModel) { delete m_pDasherModel; m_pDasherModel = 0; } if(m_pNCManager) { delete m_pNCManager; m_pNCManager = 0; } m_pNCManager = new CNodeCreationManager(this, m_pEventHandler, m_pSettingsStore, m_AlphIO); m_Alphabet = m_pNCManager->GetAlphabet(); // TODO: Eventually we'll not have to pass the NC manager to the model... CreateModel(iOffset); } void CDasherInterfaceBase::Pause() { if (GetBoolParameter(BP_DASHER_PAUSED)) return; //already paused, no need to do anything. SetBoolParameter(BP_DASHER_PAUSED, true); // Request a full redraw at the next time step. SetBoolParameter(BP_REDRAW, true); Dasher::CStopEvent oEvent; m_pEventHandler->InsertEvent(&oEvent); #ifndef _WIN32_WCE if (m_pUserLog != NULL) m_pUserLog->StopWriting((float) GetNats()); #endif } void CDasherInterfaceBase::GameMessageIn(int message, void* messagedata) { GameMode::CDasherGameMode::GetTeacher()->Message(message, messagedata); } void CDasherInterfaceBase::Unpause(unsigned long Time) { if (!GetBoolParameter(BP_DASHER_PAUSED)) return; //already running, no need to do anything SetBoolParameter(BP_DASHER_PAUSED, false); if(m_pDasherModel != 0) m_pDasherModel->Reset_framerate(Time); Dasher::CStartEvent oEvent; m_pEventHandler->InsertEvent(&oEvent); // Commenting this out, can't see a good reason to ResetNats, // just because we are not paused anymore - pconlon // ResetNats(); #ifndef _WIN32_WCE if (m_pUserLog != NULL) m_pUserLog->StartWriting(); #endif } void CDasherInterfaceBase::CreateInput() { if(m_pInput) { m_pInput->Deactivate(); } m_pInput = (CDasherInput *)GetModuleByName(GetStringParameter(SP_INPUT_DEVICE)); if (m_pInput == NULL) m_pInput = (CDasherInput *)GetDefaultInputDevice(); if(m_pInput) { m_pInput->Activate(); } if(m_pDasherView != 0) m_pDasherView->SetInput(m_pInput); } void CDasherInterfaceBase::NewFrame(unsigned long iTime, bool bForceRedraw) { // Prevent NewFrame from being reentered. This can happen occasionally and // cause crashes. static bool bReentered=false; if (bReentered) { #ifdef DEBUG std::cout << "CDasherInterfaceBase::NewFrame was re-entered" << std::endl; #endif return; } bReentered=true; // Fail if Dasher is locked // if(m_iCurrentState != ST_NORMAL) // return; bool bChanged(false), bWasPaused(GetBoolParameter(BP_DASHER_PAUSED)); CExpansionPolicy *pol=m_defaultPolicy; if(m_pDasherView != 0) { if(!GetBoolParameter(BP_TRAINING)) { if (m_pUserLog != NULL) { //ACL note that as of 15/5/09, splitting UpdatePosition into two, //DasherModel no longer guarantees to empty these two if it didn't do anything. //So initialise appropriately... Dasher::VECTOR_SYMBOL_PROB vAdded; int iNumDeleted = 0; if(m_pInputFilter) { bChanged = m_pInputFilter->Timer(iTime, m_pDasherView, m_pDasherModel, &vAdded, &iNumDeleted, &pol); } #ifndef _WIN32_WCE if (iNumDeleted > 0) m_pUserLog->DeleteSymbols(iNumDeleted); if (vAdded.size() > 0) m_pUserLog->AddSymbols(&vAdded); #endif } else { if(m_pInputFilter) { bChanged = m_pInputFilter->Timer(iTime, m_pDasherView, m_pDasherModel, 0, 0, &pol); } } m_pDasherModel->CheckForNewRoot(m_pDasherView); } } //check: if we were paused before, and the input filter didn't unpause, // then nothing can have changed: DASHER_ASSERT(!bWasPaused || !GetBoolParameter(BP_DASHER_PAUSED) || !bChanged); // Flags at this stage: // // - bChanged = the display was updated, so needs to be rendered to the display // - m_bLastChanged = bChanged was true last time around // - m_bRedrawScheduled = Display invalidated internally // - bForceRedraw = Display invalidated externally // TODO: This is a bit hacky - we really need to sort out the redraw logic if((!bChanged && m_bLastChanged) || m_bRedrawScheduled || bForceRedraw) { m_pDasherView->Screen()->SetCaptureBackground(true); m_pDasherView->Screen()->SetLoadBackground(true); } bForceRedraw |= m_bLastChanged; m_bLastChanged = bChanged; //will also be set in Redraw if any nodes were expanded. Redraw(bChanged || m_bRedrawScheduled || bForceRedraw, *pol); m_bRedrawScheduled = false; // This just passes the time through to the framerate tracker, so we // know how often new frames are being drawn. if(m_pDasherModel != 0) m_pDasherModel->RecordFrame(iTime); bReentered=false; } void CDasherInterfaceBase::Redraw(bool bRedrawNodes, CExpansionPolicy &policy) { // No point continuing if there's nothing to draw on... if(!m_pDasherView) return; // Draw the nodes if(bRedrawNodes) { m_pDasherView->Screen()->SendMarker(0); if (m_pDasherModel) m_bLastChanged |= m_pDasherModel->RenderToView(m_pDasherView,policy); } // Draw the decorations m_pDasherView->Screen()->SendMarker(1); if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) pTeacher->DrawGameDecorations(m_pDasherView); bool bDecorationsChanged(false); if(m_pInputFilter) { bDecorationsChanged = m_pInputFilter->DecorateView(m_pDasherView); } + if(m_pGameModule) { + g_pLogger->Log("The game module was initialized."); + bDecorationsChanged = m_pGameModule->DecorateView(m_pDasherView) || bDecorationsChanged; + } + else { + g_pLogger->Log("FUUUUUUCCCCCCKKKKKKKKKK"); + } + bool bActionButtonsChanged(false); #ifdef EXPERIMENTAL_FEATURES bActionButtonsChanged = DrawActionButtons(); #endif // Only blit the image to the display if something has actually changed if(bRedrawNodes || bDecorationsChanged || bActionButtonsChanged) m_pDasherView->Display(); } void CDasherInterfaceBase::ChangeAlphabet() { if(GetStringParameter(SP_ALPHABET_ID) == "") { SetStringParameter(SP_ALPHABET_ID, m_AlphIO->GetDefault()); // This will result in ChangeAlphabet() being called again, so // exit from the first recursion return; } // Send a lock event WriteTrainFileFull(); // Lock Dasher to prevent changes from happening while we're training. SetBoolParameter( BP_TRAINING, true ); CreateNCManager(); #ifndef _WIN32_WCE // Let our user log object know about the new alphabet since // it needs to convert symbols into text for the log file. if (m_pUserLog != NULL) m_pUserLog->SetAlphabetPtr(m_Alphabet); #endif // Apply options from alphabet SetBoolParameter( BP_TRAINING, false ); //} } void CDasherInterfaceBase::ChangeColours() { if(!m_ColourIO || !m_DasherScreen) return; // TODO: Make fuction return a pointer directly m_DasherScreen->SetColourScheme(&(m_ColourIO->GetInfo(GetStringParameter(SP_COLOUR_ID)))); } void CDasherInterfaceBase::ChangeScreen(CDasherScreen *NewScreen) { // What does ChangeScreen do? m_DasherScreen = NewScreen; ChangeColours(); if(m_pDasherView != 0) { m_pDasherView->ChangeScreen(m_DasherScreen); } else if(GetLongParameter(LP_VIEW_ID) != -1) { ChangeView(); } PositionActionButtons(); BudgettingPolicy pol(GetLongParameter(LP_NODE_BUDGET)); //maintain budget, but allow arbitrary amount of work. Redraw(true, pol); // (we're assuming resolution changes are occasional, i.e. // we don't need to worry about maintaining the frame rate, so we can do // as much work as necessary. However, it'd probably be better still to // get a node queue from the input filter, as that might have a different // policy / budget. } void CDasherInterfaceBase::ChangeView() { // TODO: Actually respond to LP_VIEW_ID parameter (although there is only one view at the moment) // removed condition that m_pDasherModel != 0. Surely the view can exist without the model?-pconlon if(m_DasherScreen != 0 /*&& m_pDasherModel != 0*/) { delete m_pDasherView; m_pDasherView = new CDasherViewSquare(m_pEventHandler, m_pSettingsStore, m_DasherScreen); if (m_pInput) m_pDasherView->SetInput(m_pInput); // Tell the Teacher which view we are using if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) pTeacher->SetDasherView(m_pDasherView); } } const CAlphIO::AlphInfo & CDasherInterfaceBase::GetInfo(const std::string &AlphID) { return m_AlphIO->GetInfo(AlphID); } void CDasherInterfaceBase::SetInfo(const CAlphIO::AlphInfo &NewInfo) { m_AlphIO->SetInfo(NewInfo); } void CDasherInterfaceBase::DeleteAlphabet(const std::string &AlphID) { m_AlphIO->Delete(AlphID); } double CDasherInterfaceBase::GetCurCPM() { // return 0; } double CDasherInterfaceBase::GetCurFPS() { // return 0; } // int CDasherInterfaceBase::GetAutoOffset() { // if(m_pDasherView != 0) { // return m_pDasherView->GetAutoOffset(); // } // return -1; // } double CDasherInterfaceBase::GetNats() const { if(m_pDasherModel) return m_pDasherModel->GetNats(); else return 0.0; } void CDasherInterfaceBase::ResetNats() { if(m_pDasherModel) m_pDasherModel->ResetNats(); } // TODO: Check that none of this needs to be reimplemented // void CDasherInterfaceBase::InvalidateContext(bool bForceStart) { // m_pDasherModel->m_strContextBuffer = ""; // Dasher::CEditContextEvent oEvent(10); // m_pEventHandler->InsertEvent(&oEvent); // std::string strNewContext(m_pDasherModel->m_strContextBuffer); // // We keep track of an internal context and compare that to what // // we are given - don't restart Dasher if nothing has changed. // // This should really be integrated with DasherModel, which // // probably will be the case when we start to deal with being able // // to back off indefinitely. For now though we'll keep it in a // // separate string. // int iContextLength( 6 ); // The 'important' context length - should really get from language model // // FIXME - use unicode lengths // if(bForceStart || (strNewContext.substr( std::max(static_cast<int>(strNewContext.size()) - iContextLength, 0)) != strCurrentContext.substr( std::max(static_cast<int>(strCurrentContext.size()) - iContextLength, 0)))) { // if(m_pDasherModel != NULL) { // // TODO: Reimplement this // // if(m_pDasherModel->m_bContextSensitive || bForceStart) { // { // m_pDasherModel->SetContext(strNewContext); // PauseAt(0,0); // } // } // strCurrentContext = strNewContext; // WriteTrainFileFull(); // } // if(bForceStart) { // int iMinWidth; // if(m_pInputFilter && m_pInputFilter->GetMinWidth(iMinWidth)) { // m_pDasherModel->LimitRoot(iMinWidth); // } // } // if(m_pDasherView) // while( m_pDasherModel->CheckForNewRoot(m_pDasherView) ) { // // Do nothing // } // ScheduleRedraw(); // } // TODO: Fix this std::string CDasherInterfaceBase::GetContext(int iStart, int iLength) { m_strContext = ""; CEditContextEvent oEvent(iStart, iLength); m_pEventHandler->InsertEvent(&oEvent); return m_strContext; } void CDasherInterfaceBase::SetContext(std::string strNewContext) { m_strContext = strNewContext; } // Control mode stuff void CDasherInterfaceBase::RegisterNode( int iID, const std::string &strLabel, int iColour ) { m_pNCManager->RegisterNode(iID, strLabel, iColour); } void CDasherInterfaceBase::ConnectNode(int iChild, int iParent, int iAfter) { m_pNCManager->ConnectNode(iChild, iParent, iAfter); } void CDasherInterfaceBase::DisconnectNode(int iChild, int iParent) { m_pNCManager->DisconnectNode(iChild, iParent); } void CDasherInterfaceBase::SetBoolParameter(int iParameter, bool bValue) { m_pSettingsStore->SetBoolParameter(iParameter, bValue); }; void CDasherInterfaceBase::SetLongParameter(int iParameter, long lValue) { m_pSettingsStore->SetLongParameter(iParameter, lValue); }; void CDasherInterfaceBase::SetStringParameter(int iParameter, const std::string & sValue) { PreSetNotify(iParameter, sValue); m_pSettingsStore->SetStringParameter(iParameter, sValue); }; bool CDasherInterfaceBase::GetBoolParameter(int iParameter) { return m_pSettingsStore->GetBoolParameter(iParameter); } long CDasherInterfaceBase::GetLongParameter(int iParameter) { return m_pSettingsStore->GetLongParameter(iParameter); } std::string CDasherInterfaceBase::GetStringParameter(int iParameter) { return m_pSettingsStore->GetStringParameter(iParameter); } void CDasherInterfaceBase::ResetParameter(int iParameter) { m_pSettingsStore->ResetParameter(iParameter); } // We need to be able to get at the UserLog object from outside the interface CUserLogBase* CDasherInterfaceBase::GetUserLogPtr() { return m_pUserLog; } void CDasherInterfaceBase::KeyDown(int iTime, int iId, bool bPos, int iX, int iY) { if(m_iCurrentState != ST_NORMAL) return; if(m_pInputFilter && !GetBoolParameter(BP_TRAINING)) { m_pInputFilter->KeyDown(iTime, iId, m_pDasherView, m_pDasherModel, m_pUserLog, bPos, iX, iY); } if(m_pInput && !GetBoolParameter(BP_TRAINING)) { m_pInput->KeyDown(iTime, iId); } } void CDasherInterfaceBase::KeyUp(int iTime, int iId, bool bPos, int iX, int iY) { if(m_iCurrentState != ST_NORMAL) return; if(m_pInputFilter && !GetBoolParameter(BP_TRAINING)) { m_pInputFilter->KeyUp(iTime, iId, m_pDasherView, m_pDasherModel, bPos, iX, iY); } if(m_pInput && !GetBoolParameter(BP_TRAINING)) { m_pInput->KeyUp(iTime, iId); } } -void CDasherInterFaceBase::InitGameModule() { +void CDasherInterfaceBase::InitGameModule() { - if(m_pGameModule == NULL) - m_pGameModule = (CGameModule*) GetModuleByName(GetStringParameter(BP_GAME_MODULE)); + //TODO - don't use magic number here!!! + if(m_pGameModule == NULL) { + g_pLogger->Log("InitGameModule"); + m_pGameModule = (CGameModule*) GetModule(21); + } } void CDasherInterfaceBase::CreateInputFilter() { if(m_pInputFilter) { m_pInputFilter->Deactivate(); m_pInputFilter = NULL; } #ifndef _WIN32_WCE m_pInputFilter = (CInputFilter *)GetModuleByName(GetStringParameter(SP_INPUT_FILTER)); #endif if (m_pInputFilter == NULL) m_pInputFilter = (CInputFilter *)GetDefaultInputMethod(); m_pInputFilter->Activate(); } CDasherModule *CDasherInterfaceBase::RegisterModule(CDasherModule *pModule) { return m_oModuleManager.RegisterModule(pModule); } CDasherModule *CDasherInterfaceBase::GetModule(ModuleID_t iID) { return m_oModuleManager.GetModule(iID); } CDasherModule *CDasherInterfaceBase::GetModuleByName(const std::string &strName) { return m_oModuleManager.GetModuleByName(strName); } CDasherModule *CDasherInterfaceBase::GetDefaultInputDevice() { return m_oModuleManager.GetDefaultInputDevice(); } CDasherModule *CDasherInterfaceBase::GetDefaultInputMethod() { return m_oModuleManager.GetDefaultInputMethod(); } void CDasherInterfaceBase::SetDefaultInputDevice(CDasherModule *pModule) { m_oModuleManager.SetDefaultInputDevice(pModule); } void CDasherInterfaceBase::SetDefaultInputMethod(CDasherModule *pModule) { m_oModuleManager.SetDefaultInputMethod(pModule); } void CDasherInterfaceBase::CreateModules() { SetDefaultInputMethod( RegisterModule(new CDefaultFilter(m_pEventHandler, m_pSettingsStore, this, 3, _("Normal Control"))) ); RegisterModule(new COneDimensionalFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CEyetrackerFilter(m_pEventHandler, m_pSettingsStore, this)); #ifndef _WIN32_WCE RegisterModule(new CClickFilter(m_pEventHandler, m_pSettingsStore, this)); #else SetDefaultInputMethod( RegisterModule(new CClickFilter(m_pEventHandler, m_pSettingsStore, this)); ); #endif RegisterModule(new COneButtonFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new COneButtonDynamicFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CTwoButtonDynamicFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CTwoPushDynamicFilter(m_pEventHandler, m_pSettingsStore, this)); // TODO: specialist factory for button mode RegisterModule(new CButtonMode(m_pEventHandler, m_pSettingsStore, this, true, 8, _("Menu Mode"))); RegisterModule(new CButtonMode(m_pEventHandler, m_pSettingsStore, this, false,10, _("Direct Mode"))); // RegisterModule(new CDasherButtons(m_pEventHandler, m_pSettingsStore, this, 4, 0, false,11, "Buttons 3")); RegisterModule(new CAlternatingDirectMode(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CCompassMode(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CStylusFilter(m_pEventHandler, m_pSettingsStore, this, 15, _("Stylus Control"))); // Register game mode with the module manager // TODO should this be wrapped in an "if game mode enabled" // conditional? // TODO: I don't know what a sensible module ID should be // for this, so I chose an arbitrary value RegisterModule(new CGameModule(m_pEventHandler, m_pSettingsStore, this, 21, _("GameMode"))); } void CDasherInterfaceBase::GetPermittedValues(int iParameter, std::vector<std::string> &vList) { // TODO: Deprecate direct calls to these functions switch (iParameter) { case SP_ALPHABET_ID: if(m_AlphIO) m_AlphIO->GetAlphabets(&vList); break; case SP_COLOUR_ID: if(m_ColourIO) m_ColourIO->GetColours(&vList); break; case SP_INPUT_FILTER: m_oModuleManager.ListModules(1, vList); break; case SP_INPUT_DEVICE: m_oModuleManager.ListModules(0, vList); break; } } void CDasherInterfaceBase::StartShutdown() { ChangeState(TR_SHUTDOWN); } bool CDasherInterfaceBase::GetModuleSettings(const std::string &strName, SModuleSettings **pSettings, int *iCount) { return GetModuleByName(strName)->GetSettings(pSettings, iCount); } void CDasherInterfaceBase::SetupActionButtons() { m_vLeftButtons.push_back(new CActionButton(this, "Exit", true)); m_vLeftButtons.push_back(new CActionButton(this, "Preferences", false)); m_vLeftButtons.push_back(new CActionButton(this, "Help", false)); m_vLeftButtons.push_back(new CActionButton(this, "About", false)); } void CDasherInterfaceBase::DestroyActionButtons() { // TODO: implement and call this } void CDasherInterfaceBase::PositionActionButtons() { if(!m_DasherScreen) return; int iCurrentOffset(16); for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) { (*it)->SetPosition(16, iCurrentOffset, 32, 32); iCurrentOffset += 48; } iCurrentOffset = 16; for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) { (*it)->SetPosition(m_DasherScreen->GetWidth() - 144, iCurrentOffset, 128, 32); iCurrentOffset += 48; } } bool CDasherInterfaceBase::DrawActionButtons() { if(!m_DasherScreen) return false; bool bVisible(GetBoolParameter(BP_DASHER_PAUSED)); bool bRV(bVisible != m_bOldVisible); m_bOldVisible = bVisible; for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) (*it)->Draw(m_DasherScreen, bVisible); for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) (*it)->Draw(m_DasherScreen, bVisible); return bRV; } void CDasherInterfaceBase::HandleClickUp(int iTime, int iX, int iY) { #ifdef EXPERIMENTAL_FEATURES bool bVisible(GetBoolParameter(BP_DASHER_PAUSED)); for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) { if((*it)->HandleClickUp(iTime, iX, iY, bVisible)) return; } for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) { if((*it)->HandleClickUp(iTime, iX, iY, bVisible)) return; } #endif KeyUp(iTime, 100, true, iX, iY); } void CDasherInterfaceBase::HandleClickDown(int iTime, int iX, int iY) { #ifdef EXPERIMENTAL_FEATURES bool bVisible(GetBoolParameter(BP_DASHER_PAUSED)); for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) { if((*it)->HandleClickDown(iTime, iX, iY, bVisible)) return; } for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) { if((*it)->HandleClickDown(iTime, iX, iY, bVisible)) return; } #endif KeyDown(iTime, 100, true, iX, iY); } void CDasherInterfaceBase::ExecuteCommand(const std::string &strName) { // TODO: Pointless - just insert event directly CCommandEvent *pEvent = new CCommandEvent(strName); m_pEventHandler->InsertEvent(pEvent); delete pEvent; } double CDasherInterfaceBase::GetFramerate() { if(m_pDasherModel) return(m_pDasherModel->Framerate()); else return 0.0; } void CDasherInterfaceBase::AddActionButton(const std::string &strName) { m_vRightButtons.push_back(new CActionButton(this, strName, false)); } void CDasherInterfaceBase::OnUIRealised() { StartTimer(); ChangeState(TR_UI_INIT); } void CDasherInterfaceBase::ChangeState(ETransition iTransition) { static EState iTransitionTable[ST_NUM][TR_NUM] = { {ST_MODEL, ST_UI, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN},//ST_START {ST_FORBIDDEN, ST_NORMAL, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN},//ST_MODEL {ST_NORMAL, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN},//ST_UI {ST_FORBIDDEN, ST_FORBIDDEN, ST_LOCKED, ST_FORBIDDEN, ST_SHUTDOWN},//ST_NORMAL {ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_NORMAL, ST_FORBIDDEN},//ST_LOCKED {ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN}//ST_SHUTDOWN //TR_MODEL_INIT, TR_UI_INIT, TR_LOCK, TR_UNLOCK, TR_SHUTDOWN }; EState iNewState(iTransitionTable[m_iCurrentState][iTransition]); if(iNewState != ST_FORBIDDEN) { if (iNewState == ST_SHUTDOWN) { ShutdownTimer(); WriteTrainFileFull(); } m_iCurrentState = iNewState; } } void CDasherInterfaceBase::SetBuffer(int iOffset) { CreateModel(iOffset); } void CDasherInterfaceBase::UnsetBuffer() { // TODO: Write training file? if(m_pDasherModel) delete m_pDasherModel; m_pDasherModel = 0; } void CDasherInterfaceBase::SetOffset(int iOffset) { if(m_pDasherModel) m_pDasherModel->SetOffset(iOffset, m_pDasherView); } void CDasherInterfaceBase::SetControlOffset(int iOffset) { if(m_pDasherModel) m_pDasherModel->SetControlOffset(iOffset); } // Returns 0 on success, an error string on failure. const char* CDasherInterfaceBase::ClSet(const std::string &strKey, const std::string &strValue) { if(m_pSettingsStore) return m_pSettingsStore->ClSet(strKey, strValue); return 0; } void CDasherInterfaceBase::ImportTrainingText(const std::string &strPath) { if(m_pNCManager) m_pNCManager->ImportTrainingText(strPath); } diff --git a/Src/DasherCore/DasherInterfaceBase.h b/Src/DasherCore/DasherInterfaceBase.h index 6ca025d..7ea4099 100644 --- a/Src/DasherCore/DasherInterfaceBase.h +++ b/Src/DasherCore/DasherInterfaceBase.h @@ -1,554 +1,555 @@ // DasherInterfaceBase.h // // Copyright (c) 2008 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #ifndef __DasherInterfaceBase_h__ #define __DasherInterfaceBase_h__ /// /// \mainpage /// /// This is the Dasher source code documentation. Please try to keep /// it up to date! /// // TODO - there is a list of things to be configurable in my notes // Check that everything that is not self-contained within the GUI is covered. #include "../Common/NoClones.h" #include "../Common/ModuleSettings.h" #include "ActionButton.h" #include "Alphabet/Alphabet.h" #include "Alphabet/AlphIO.h" #include "AutoSpeedControl.h" #include "ColourIO.h" #include "InputFilter.h" #include "ModuleManager.h" +#include "GameModule.h" #include <map> #include <algorithm> namespace Dasher { class CDasherScreen; class CDasherView; class CDasherInput; class CDasherModel; class CEventHandler; class CEvent; class CDasherInterfaceBase; } class CSettingsStore; class CUserLogBase; class CNodeCreationManager; /// \defgroup Core Core Dasher classes /// @{ struct Dasher::SLockData { std::string strDisplay; int iPercent; }; /// The central class in the core of Dasher. Ties together the rest of /// the platform independent stuff and provides a single interface for /// the UI to use. class Dasher::CDasherInterfaceBase:private NoClones { public: CDasherInterfaceBase(); virtual ~CDasherInterfaceBase(); /// @name Access to internal member classes /// Access various classes contained within the interface. These /// should be considered dangerous and use minimised. Eventually to /// be replaced by properly encapsulated equivalents. /// @{ /// /// Return a pointer to the current EventHandler (the one /// which the CSettingsStore is using to notify parameter /// changes) /// virtual CEventHandler *GetEventHandler() { return m_pEventHandler; }; /// /// \deprecated In situ alphabet editing is no longer supported /// \todo Document this /// const CAlphIO::AlphInfo & GetInfo(const std::string & AlphID); /// \todo Document this void SetInfo(const CAlphIO::AlphInfo & NewInfo); /// \todo Document this void DeleteAlphabet(const std::string & AlphID); /// Get a pointer to the current alphabet object CAlphabet *GetAlphabet() { return m_Alphabet; } /// Gets a pointer to the object doing user logging CUserLogBase* GetUserLogPtr(); // @} /// /// @name Parameter manipulation /// Members for manipulating the parameters of the core Dasher object. /// //@{ /// /// Set a boolean parameter. /// \param iParameter The parameter to set. /// \param bValue The new value. /// void SetBoolParameter(int iParameter, bool bValue); /// /// Set a long integer parameter. /// \param iParameter The parameter to set. /// \param lValue The new value. /// void SetLongParameter(int iParameter, long lValue); /// /// Set a string parameter. /// \param iParameter The parameter to set. /// \param sValue The new value. /// void SetStringParameter(int iParameter, const std::string & sValue); /// Get a boolean parameter /// \param iParameter The parameter to get. /// \retval The current value. bool GetBoolParameter(int iParameter); /// Get a long integer parameter /// \param iParameter The parameter to get. /// \retval The current value. long GetLongParameter(int iParameter); /// Get a string parameter /// \param iParameter The parameter to get. /// \retval The current value. std::string GetStringParameter(int iParameter); /// /// Reset a parameter to the default value /// void ResetParameter(int iParmater); /// /// Obtain the permitted values for a string parameter - used to /// geneate preferences dialogues etc. /// void GetPermittedValues(int iParameter, std::vector<std::string> &vList); /// /// Get a list of settings which apply to a particular module /// bool GetModuleSettings(const std::string &strName, SModuleSettings **pSettings, int *iCount); //@} /// Forward events to listeners in the SettingsUI and Editbox. /// \param pEvent The event to forward. /// \todo Should be protected. virtual void ExternalEventHandler(Dasher::CEvent * pEvent) {}; /// Interface level event handler. For example, responsible for /// restarting the Dasher model whenever parameter changes make it /// invalid. /// \param pEvent The event. /// \todo Should be protected. void InterfaceEventHandler(Dasher::CEvent * pEvent); void PreSetNotify(int iParameter, const std::string &sValue); /// @name Starting and stopping /// Methods used to instruct dynamic motion of Dasher to start or stop /// @{ /// Resets the Dasher model. Doesn't actually unpause Dasher. /// \deprecated Use InvalidateContext() instead // void Start(); /// Pause Dasher. Sets BP_DASHER_PAUSED and broadcasts a StopEvent. /// (But does nothing if BP_DASHER_PAUSED is not set) void Pause(); // are required to make /// Unpause Dasher. Clears BP_DASHER_PAUSED, broadcasts a StartEvent. /// (But does nothing if BP_DASHER_PAUSED is currently set). /// \param Time Time in ms, used to keep a constant frame rate void Unpause(unsigned long Time); // Dasher run at the /// @} // App Interface // ----------------------------------------------------- // std::map<int, std::string>& GetAlphabets(); // map<key, value> int is a UID string can change. Store UID in preferences. Display string to user. // std::vector<std::string>& GetAlphabets(); // std::vector<std::string>& GetLangModels(); // std::vector<std::string>& GetViews(); /// Supply a new CDasherScreen object to do the rendering. /// \param NewScreen Pointer to the new CDasherScreen. void ChangeScreen(CDasherScreen * NewScreen); // We may change the widgets Dasher uses /// Train Dasher from a file /// All traing data must be in UTF-8 /// \param Filename File to load. /// \param iTotalBytes documentme /// \param iOffset Document me // int TrainFile(std::string Filename, int iTotalBytes, int iOffset); /// Set the context in which Dasher makes predictions /// \param strNewContext The new context (UTF-8) void SetContext(std::string strNewContext); /// New control mechanisms: void SetBuffer(int iOffset); void UnsetBuffer(); void SetOffset(int iOffset); /// @name Status reporting /// Get information about the runtime status of Dasher which might /// be of interest for debugging purposes etc. /// @{ /// Get the current rate of text entry. /// \retval The rate in characters per minute. /// TODO: Check that this is still used double GetCurCPM(); /// Get current refresh rate. /// \retval The rate in frames per second /// TODO: Check that this is still used double GetCurFPS(); /// Get the total number of nats (base-e bits) entered. /// \retval The current total /// \todo Obsolete since new logging code? double GetNats() const; /// Reset the count of nats entered. /// \todo Obsolete since new logging code? void ResetNats(); double GetFramerate(); /// @} /// @name Control hierarchy and action buttons /// Manipulate the hierarchy of commands presented in control mode etc /// @{ void RegisterNode( int iID, const std::string &strLabel, int iColour ); void ConnectNode(int iChild, int iParent, int iAfter); void DisconnectNode(int iChild, int iParent); void ExecuteCommand(const std::string &strName); void AddActionButton(const std::string &strName); /// @} /// @name User input /// Deals with forwarding user input to the core /// @{ void KeyDown(int iTime, int iId, bool bPos = false, int iX = 0, int iY = 0); void KeyUp(int iTime, int iId, bool bPos = false, int iX = 0, int iY = 0); void HandleClickUp(int iTime, int iX, int iY); void HandleClickDown(int iTime, int iX, int iY); /// @} // Module management functions CDasherModule *RegisterModule(CDasherModule *pModule); CDasherModule *GetModule(ModuleID_t iID); CDasherModule *GetModuleByName(const std::string &strName); CDasherModule *GetDefaultInputDevice(); CDasherModule *GetDefaultInputMethod(); void SetDefaultInputDevice(CDasherModule *); void SetDefaultInputMethod(CDasherModule *); void StartShutdown(); void AddGameModeString(const std::string &strText) { m_deGameModeStrings.push_back(strText); Pause(); // CreateDasherModel(); CreateNCManager(); // Start(); }; void GameMessageIn(int message, void* messagedata); virtual void GameMessageOut(int message, const void* messagedata) {} void ScheduleRedraw() { m_bRedrawScheduled = true; }; std::string GetContext(int iStart, int iLength); void SetControlOffset(int iOffset); /// Set a key value pair by name - designed to allow operation from /// the command line. Returns 0 on success, an error string on failure. /// const char* ClSet(const std::string &strKey, const std::string &strValue); void ImportTrainingText(const std::string &strPath); protected: /// @name Startup /// Interaction with the derived class during core startup /// @{ /// /// Allocate resources, create alphabets etc. This is a separate /// routine to the constructor to give us a chance to set up /// parameters before things are created. /// void Realize(); /// /// Notify the core that the UI has been realised. At this point drawing etc. is expected to work /// void OnUIRealised(); /// /// Creates a default set of modules. Override in subclasses to create any /// extra/different modules specific to the platform (eg input device drivers) /// virtual void CreateModules(); /// @} /// Draw a new Dasher frame, regardless of whether we're paused etc. /// \param iTime Current time in ms. /// \param bForceRedraw /// \todo See comments in cpp file for some functionality which needs to be re-implemented void NewFrame(unsigned long iTime, bool bForceRedraw); enum ETransition { TR_MODEL_INIT = 0, TR_UI_INIT, TR_LOCK, TR_UNLOCK, TR_SHUTDOWN, TR_NUM }; enum EState { ST_START = 0, ST_MODEL, ST_UI, ST_NORMAL, ST_LOCKED, ST_SHUTDOWN, ST_NUM, ST_FORBIDDEN, ST_DELAY }; /// @name State machine functions /// ... /// @{ void ChangeState(ETransition iTransition); /// @} CEventHandler *m_pEventHandler; CSettingsStore *m_pSettingsStore; private: //The default expansion policy to use - an amortized policy depending on the LP_NODE_BUDGET parameter. CExpansionPolicy *m_defaultPolicy; /// @name Platform dependent utility functions /// These functions provide various platform dependent functions /// required by the core. A derived class is created for each /// supported platform which implements these. // @{ /// /// Initialise the SP_SYSTEM_LOC and SP_USER_LOC paths - the exact /// method of doing this will be OS dependent /// virtual void SetupPaths() = 0; /// /// Produce a list of filenames for alphabet files /// virtual void ScanAlphabetFiles(std::vector<std::string> &vFileList) = 0; /// /// Produce a list of filenames for colour files /// virtual void ScanColourFiles(std::vector<std::string> &vFileList) = 0; /// /// Set up the platform dependent UI for the widget (not the wider /// app). Note that the constructor of the derived class will /// probably want to return details of what was created - this will /// have to happen separately, but we'll need to be careful with the /// semantics. /// virtual void SetupUI() = 0; /// /// Create settings store object, which will be platform dependent /// TODO: Can this not be done just by selecting which settings /// store implementation to instantiate? /// virtual void CreateSettingsStore() = 0; /// /// Obtain the size in bytes of a file - the way to do this is /// dependent on the OS (TODO: Check this - any posix on Windows?) /// virtual int GetFileSize(const std::string &strFileName) = 0; /// /// Start the callback timer /// virtual void StartTimer() = 0; /// /// Shutdown the callback timer (permenantly - this is called once /// Dasher is committed to closing). /// virtual void ShutdownTimer() = 0; /// /// Append text to the training file - used to store state between /// sessions /// @todo Pass file path to the function rather than having implementations work it out themselves /// virtual void WriteTrainFile(const std::string &strNewText) { }; /// @} /// Provide a new CDasherInput input device object. void CreateInput(); /* Initialize m_pGameModule by fetching the * constructed module from the module manager. */ void InitGameModule(); void CreateInputFilter(); void CreateModel(int iOffset); void CreateNCManager(); void ChangeAlphabet(); void ChangeColours(); void ChangeView(); void Redraw(bool bRedrawNodes, CExpansionPolicy &policy); void SetupActionButtons(); void DestroyActionButtons(); void PositionActionButtons(); bool DrawActionButtons(); void WriteTrainFileFull(); void WriteTrainFilePartial(); std::deque<std::string> m_deGameModeStrings; std::vector<CActionButton *> m_vLeftButtons; std::vector<CActionButton *> m_vRightButtons; /// @name Child components /// Various objects which are 'owned' by the core. /// @{ CAlphabet *m_Alphabet; CDasherModel *m_pDasherModel; diff --git a/Src/DasherCore/GameModule.h b/Src/DasherCore/GameModule.h index 2c15a23..8e8c102 100644 --- a/Src/DasherCore/GameModule.h +++ b/Src/DasherCore/GameModule.h @@ -1,92 +1,107 @@ // GameModule.h #ifndef GAME_MODULE_H #define GAME_MODULE_H #include <string> using namespace std; -#include "DasherModule.h" +#include "DasherView.h" #include "DasherModel.h" +#include "DasherModule.h" #include "DasherNode.h" -#include "DasherView.h" namespace Dasher { class CDasherInterfaceBase; } namespace Dasher { /** * This Dasher Module encapsulates all game mode logic. In game mode, users will be given * a target string to type as well as visual feedback for their progress and a helpful * arrow to guide them in the right path through the dasher model. * * This class handles logic and drawing code with respect to the above. */ class CGameModule : public CDasherModule { public: // I don't actually know what the type is supposed to be for this...it's not an input method or an input filter. // Maybe we should define a new one. I've labeled it 0 for now. - rgee CGameModule(Dasher::CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CDasherInterfaceBase *pInterface, ModuleID_t iID, const char *szName) : CDasherModule(pEventHandler, pSettingsStore, iID, 0, szName) - { m_pInterface = pInterface; } + { + g_pLogger->Log("Inside game module constructor"); + m_pInterface = pInterface; + } + + ~CGameModule() {}; /** * Handle events from the event processing system * @param pEvent The event to be processed. */ - void HandleEvent(Dasher::CEvent *pEvent); + void HandleEvent(Dasher::CEvent *pEvent) {}; /** * Gets the typed portion of the target string * @return The string that represents the current word(s) that have not been typed */ - inline std::string GetTypedTarget(); + std::string GetTypedTarget(); /** * Gets the portion of the target string that has yet to be completed * @return The string that represents the current word(s) that have been typed */ - inline std::string GetUntypedTarget(); + std::string GetUntypedTarget(); - inline void SetDasherModel(CDasherModel *pModel) { m_pModel = pModel; } + bool DecorateView(CDasherView *pView) { + g_pLogger->Log("Decorating the view"); + return false; + } + + void SetDasherModel(CDasherModel *pModel) { m_pModel = pModel; } private: /** * Searches for the dasher node under the current root that represents the desired string * @param text The string to search for * @return The node representing the string parameter */ - CDasherNode StringToNode(std::string sText) + //Dasher::CDasherNode StringToNode(std::string sText); /** * The last node the user typed. */ CDasherNode *pLastTypedNode; /** * The next node (character) the user must type. */ CDasherNode *pNextTargetNode; /** * The target string the user must type. */ std::string m_sTargetString; /** * The current position in the string. * Stored as a size_t to easily use substrings to determine what's been typed and what hasn't. */ size_t m_stCurrentStringPos; /** * The dasher model. */ CDasherModel *m_pModel; + + /** + * The dasher interface. + */ + CDasherInterfaceBase *m_pInterface; }; } #endif
rgee/HFOSS-Dasher
d378ef49f4749c9c79a9fefe7d41ba7eaf2292b7
Modified makefile to compile generators
diff --git a/Src/DasherCore/Makefile.am b/Src/DasherCore/Makefile.am index b322d78..4bd4363 100644 --- a/Src/DasherCore/Makefile.am +++ b/Src/DasherCore/Makefile.am @@ -1,166 +1,169 @@ SUBDIRS = LanguageModelling noinst_LIBRARIES = libdashercore.a libdasherprefs.a libdasherprefs_a_SOURCES = \ Parameters.h \ SettingsStore.cpp \ SettingsStore.h libdashercore_a_SOURCES = \ Alphabet/AlphIO.cpp \ Alphabet/AlphIO.h \ Alphabet/Alphabet.cpp \ Alphabet/Alphabet.h \ Alphabet/AlphabetMap.cpp \ Alphabet/AlphabetMap.h \ Alphabet/GroupInfo.h \ AlternatingDirectMode.cpp \ AlternatingDirectMode.h \ ActionButton.cpp \ ActionButton.h \ AlphabetManager.cpp \ AlphabetManager.h \ AutoSpeedControl.cpp \ AutoSpeedControl.h \ BasicLog.cpp \ BasicLog.h \ ButtonMode.cpp \ ButtonMode.h \ ButtonMultiPress.h \ ButtonMultiPress.cpp \ CircleStartHandler.cpp \ CircleStartHandler.h \ ClickFilter.cpp \ ClickFilter.h \ ColourIO.cpp \ ColourIO.h \ CompassMode.cpp \ CompassMode.h \ ControlManager.cpp \ ControlManager.h \ ConversionHelper.cpp \ ConversionHelper.h \ ConversionManager.cpp \ ConversionManager.h \ DasherButtons.cpp \ DasherButtons.h \ DasherComponent.cpp \ DasherComponent.h \ DasherGameMode.cpp \ DasherGameMode.h \ DasherInput.h \ DasherInterfaceBase.cpp \ DasherInterfaceBase.h \ DasherModel.cpp \ DasherModel.h \ DasherModule.cpp \ DasherModule.h \ DasherNode.cpp \ DasherNode.h \ DasherScreen.h \ DasherTypes.h \ DasherView.cpp \ DasherView.h \ DasherViewSquare.cpp \ DasherViewSquare.h \ DasherViewSquare.inl \ DefaultFilter.cpp \ DefaultFilter.h \ DelayedDraw.cpp \ DelayedDraw.h \ DynamicFilter.h \ DynamicFilter.cpp \ Event.h \ EventHandler.cpp \ EventHandler.h \ EyetrackerFilter.cpp \ EyetrackerFilter.h \ FileLogger.cpp \ FileLogger.h \ + FileWordGenerator.h \ + FileWordGenerator.cpp \ FrameRate.h \ FrameRate.cpp \ GameLevel.cpp \ GameLevel.h \ GameMessages.h \ + GameModule.h \ + GameModule.cpp \ GameScorer.cpp \ GameScorer.h \ GameStatistics.h \ - GameModule.h \ - GameModule.cpp \ GnomeSettingsStore.cpp \ GnomeSettingsStore.h \ InputFilter.h \ MandarinAlphMgr.cpp \ MandarinAlphMgr.h \ MemoryLeak.cpp \ MemoryLeak.h \ ModuleManager.cpp \ ModuleManager.h \ NodeCreationManager.cpp \ NodeCreationManager.h \ ExpansionPolicy.cpp \ ExpansionPolicy.h \ OneButtonDynamicFilter.cpp \ OneButtonDynamicFilter.h \ OneButtonFilter.cpp \ OneButtonFilter.h \ OneDimensionalFilter.cpp \ OneDimensionalFilter.h \ PinyinParser.cpp \ PinyinParser.h \ SCENode.cpp \ SCENode.h \ SimpleTimer.cpp \ SimpleTimer.h \ SocketInput.cpp \ SocketInput.h \ SocketInputBase.cpp \ SocketInputBase.h \ StartHandler.h \ StylusFilter.cpp \ StylusFilter.h \ TimeSpan.cpp \ TimeSpan.h \ Trainer.cpp \ Trainer.h \ TrainingHelper.cpp \ TrainingHelper.h \ TwoBoxStartHandler.cpp \ TwoBoxStartHandler.h \ TwoButtonDynamicFilter.cpp \ TwoButtonDynamicFilter.h \ TwoPushDynamicFilter.cpp \ TwoPushDynamicFilter.h \ UserButton.cpp \ UserButton.h \ UserLocation.cpp \ UserLocation.h \ UserLog.cpp \ UserLog.h \ UserLogBase.h \ UserLogParam.cpp \ UserLogParam.h \ UserLogTrial.cpp \ UserLogTrial.h \ + WordGeneratorBase.h \ XMLUtil.cpp \ XMLUtil.h libdashercore_a_LIBADD = @JAPANESE_SOURCES@ libdashercore_a_DEPENDENCIES = @JAPANESE_SOURCES@ EXTRA_libdashercore_a_SOURCES = \ CannaConversionHelper.cpp \ CannaConversionHelper.h AM_CXXFLAGS = -I$(srcdir)/../DasherCore -DPROGDATA=\"$(pkgdatadir)\" -I../../intl -I$(top_srcdir)/intl $(GTK2_CFLAGS) $(SETTINGS_CFLAGS) $(gnome_speech_CFLAGS) $(gnome_a11y_CFLAGS) $(gnome_CFLAGS) EXTRA_DIST = \ LanguageModelling/BigramLanguageModel.cpp \ LanguageModelling/BigramLanguageModel.h \ LanguageModelling/KanjiConversionIME.cpp \ LanguageModelling/KanjiConversionIME.h \ DasherCore.vcproj \ DasherCore_vc80.vcproj \ IMEConversionHelper.cpp \ IMEConversionHelper.h
rgee/HFOSS-Dasher
a39cec2f357290917e62d282eaba70b8b48ea268
Wrote a word generator that abstracts away the logic for generating words for any purpose. Will be used in game mode to generate target strings from a file.
diff --git a/Src/DasherCore/FileWordGenerator.cpp b/Src/DasherCore/FileWordGenerator.cpp new file mode 100644 index 0000000..8dde340 --- /dev/null +++ b/Src/DasherCore/FileWordGenerator.cpp @@ -0,0 +1,35 @@ +#include "FileWordGenerator.h" + +bool CFileWordGenerator::Generate() { + if(!m_bWordsReady) { + ifstream file_in; + file_in.open(path.c_str()); + char buffer; + while(file_in.good()) { + buffer = file_in.get(); + m_sGeneratedString.append(buffer); + } + m_uiPos = 0; + } +} + +std::string CFileWordGenerator::GetPath() { + return m_sPath; +} +std::string CFileWordGenerator::GetFilename() { + return m_sPath.substr(m_sPath.rfind("/")); +} + +void CFileWordGenerator::SetSource(std::string newPath) { + m_sPath = newPath; + m_bWordsReady = false; + Generate(); +} + +virtual std::string CFileWordGenerator::GetNextWord() { + return m_sGeneratedString.substr(m_uiPos, m_sGeneratedString.find(" ")); +} + +virtual std::string CFileWordGerneator::GetPreWord() { + return "Not yet implemented. Sorry!"; +} diff --git a/Src/DasherCore/FileWordGenerator.h b/Src/DasherCore/FileWordGenerator.h new file mode 100644 index 0000000..d17e959 --- /dev/null +++ b/Src/DasherCore/FileWordGenerator.h @@ -0,0 +1,59 @@ +#include <string> +#include <iostream.h> +#include <fstream.h> +using namespace std; + +#include "WordGeneratorBase.h" + +namespace Dasher { +class CFileWordGenerator : public CWordGeneratorBase { +public: + CFileWordGenerator(std::string path, int regen) : CWordGeneratorBase(regen) { + } + /** + * The generator function. In this implementation, it reads from a file to produce strings. + * @see CWordGeneratorBase::Generate + */ + virtual bool Generate(); + + /** + * Returns the next word that was read + */ + virtual std::string GetNextWord(); + + + /** + * File path getter + * @return The path to the file this generator reads from. + */ + std::string GetPath(); + + /** + * File name getter + * @return The actual name of the file being read from + */ + std::string GetFilename(); + + /** + * Sets the source file this generator reads from. + * @warning This method regenerates the model and gets rid of the old data. + * @param newPath The path to the file to load from. + */ + void SetSource(std::string newPath); +prviate: + /** + * The string that has been generated. + */ + std::string m_sGeneratedString + + /** + * The path to the file this generator reads from. + */ + std::string m_sPath; + + /** + * The position we're currently reading from in the string. + */ + size_t m_uiPos; +}; +} diff --git a/Src/DasherCore/WordGeneratorBase.h b/Src/DasherCore/WordGeneratorBase.h new file mode 100644 index 0000000..1c2318b --- /dev/null +++ b/Src/DasherCore/WordGeneratorBase.h @@ -0,0 +1,52 @@ +#include <string> +using namespace std; + +namespace Dasher { +/** + * The base class for all word generators. Word generators encapsulate + * logic for simply generating words based on implementation-specific + * conditions. Currently, this is being used to wrap GameMode's simple + * text-file reading mechanism, but another generator can easily be + * written that selects words based on a function of the current value + * of the Sri Lankan rupee and the amount of twitter feeds regarding + * the winter olympics, for example. + */ +class CWordGeneratorBase { +public: + CWordGeneratorBase(int regen) : m_iRegenTime(regen), m_bWordsReady(false) {} + + virtual ~CWordGeneratorBase() { } + + + /** + * Gets a single word based on the generation rules. + * @pre { Generate must have been called at least once. } + * @return The next string from this generator + */ + virtual std::string GetNextWord() = 0; + + /** + * Gets the previous word in the generated string based on generation rules. + * @pre { Generate must have been called at least once. } + * @return The previous string from this generator + */ + //virtual std::string GetPrevWord() = 0; + + /** + * Generate the words based on the generation rules + * @return True if the generation succeeded, false if not. + * @warning The return value of this function should always be checked in case it's using files. + */ + virtual bool Generate() = 0; +protected: + /** + * The time in seconds after which a generator should regenerate. + */ + int m_iRegenTime; + + /** + * A boolean representing whether the words have been generated yet. + */ + bool m_bWordsReady; +}; +}
rgee/HFOSS-Dasher
7d3b62344812308ba582951f40c5c1c3e0f6073e
Added Game Module to makefile
diff --git a/Src/DasherCore/Makefile.am b/Src/DasherCore/Makefile.am index ae4b1b1..b322d78 100644 --- a/Src/DasherCore/Makefile.am +++ b/Src/DasherCore/Makefile.am @@ -1,164 +1,166 @@ SUBDIRS = LanguageModelling noinst_LIBRARIES = libdashercore.a libdasherprefs.a libdasherprefs_a_SOURCES = \ Parameters.h \ SettingsStore.cpp \ SettingsStore.h libdashercore_a_SOURCES = \ Alphabet/AlphIO.cpp \ Alphabet/AlphIO.h \ Alphabet/Alphabet.cpp \ Alphabet/Alphabet.h \ Alphabet/AlphabetMap.cpp \ Alphabet/AlphabetMap.h \ Alphabet/GroupInfo.h \ AlternatingDirectMode.cpp \ AlternatingDirectMode.h \ ActionButton.cpp \ ActionButton.h \ AlphabetManager.cpp \ AlphabetManager.h \ AutoSpeedControl.cpp \ AutoSpeedControl.h \ BasicLog.cpp \ BasicLog.h \ ButtonMode.cpp \ ButtonMode.h \ ButtonMultiPress.h \ ButtonMultiPress.cpp \ CircleStartHandler.cpp \ CircleStartHandler.h \ ClickFilter.cpp \ ClickFilter.h \ ColourIO.cpp \ ColourIO.h \ CompassMode.cpp \ CompassMode.h \ ControlManager.cpp \ ControlManager.h \ ConversionHelper.cpp \ ConversionHelper.h \ ConversionManager.cpp \ ConversionManager.h \ DasherButtons.cpp \ DasherButtons.h \ DasherComponent.cpp \ DasherComponent.h \ DasherGameMode.cpp \ DasherGameMode.h \ DasherInput.h \ DasherInterfaceBase.cpp \ DasherInterfaceBase.h \ DasherModel.cpp \ DasherModel.h \ DasherModule.cpp \ DasherModule.h \ DasherNode.cpp \ DasherNode.h \ DasherScreen.h \ DasherTypes.h \ DasherView.cpp \ DasherView.h \ DasherViewSquare.cpp \ DasherViewSquare.h \ DasherViewSquare.inl \ DefaultFilter.cpp \ DefaultFilter.h \ DelayedDraw.cpp \ DelayedDraw.h \ DynamicFilter.h \ DynamicFilter.cpp \ Event.h \ EventHandler.cpp \ EventHandler.h \ EyetrackerFilter.cpp \ EyetrackerFilter.h \ FileLogger.cpp \ FileLogger.h \ FrameRate.h \ FrameRate.cpp \ GameLevel.cpp \ GameLevel.h \ GameMessages.h \ GameScorer.cpp \ GameScorer.h \ GameStatistics.h \ + GameModule.h \ + GameModule.cpp \ GnomeSettingsStore.cpp \ GnomeSettingsStore.h \ InputFilter.h \ MandarinAlphMgr.cpp \ MandarinAlphMgr.h \ MemoryLeak.cpp \ MemoryLeak.h \ ModuleManager.cpp \ ModuleManager.h \ NodeCreationManager.cpp \ NodeCreationManager.h \ ExpansionPolicy.cpp \ ExpansionPolicy.h \ OneButtonDynamicFilter.cpp \ OneButtonDynamicFilter.h \ OneButtonFilter.cpp \ OneButtonFilter.h \ OneDimensionalFilter.cpp \ OneDimensionalFilter.h \ PinyinParser.cpp \ PinyinParser.h \ SCENode.cpp \ SCENode.h \ SimpleTimer.cpp \ SimpleTimer.h \ SocketInput.cpp \ SocketInput.h \ SocketInputBase.cpp \ SocketInputBase.h \ StartHandler.h \ StylusFilter.cpp \ StylusFilter.h \ TimeSpan.cpp \ TimeSpan.h \ Trainer.cpp \ Trainer.h \ TrainingHelper.cpp \ TrainingHelper.h \ TwoBoxStartHandler.cpp \ TwoBoxStartHandler.h \ TwoButtonDynamicFilter.cpp \ TwoButtonDynamicFilter.h \ TwoPushDynamicFilter.cpp \ TwoPushDynamicFilter.h \ UserButton.cpp \ UserButton.h \ UserLocation.cpp \ UserLocation.h \ UserLog.cpp \ UserLog.h \ UserLogBase.h \ UserLogParam.cpp \ UserLogParam.h \ UserLogTrial.cpp \ UserLogTrial.h \ XMLUtil.cpp \ XMLUtil.h libdashercore_a_LIBADD = @JAPANESE_SOURCES@ libdashercore_a_DEPENDENCIES = @JAPANESE_SOURCES@ EXTRA_libdashercore_a_SOURCES = \ CannaConversionHelper.cpp \ CannaConversionHelper.h AM_CXXFLAGS = -I$(srcdir)/../DasherCore -DPROGDATA=\"$(pkgdatadir)\" -I../../intl -I$(top_srcdir)/intl $(GTK2_CFLAGS) $(SETTINGS_CFLAGS) $(gnome_speech_CFLAGS) $(gnome_a11y_CFLAGS) $(gnome_CFLAGS) EXTRA_DIST = \ LanguageModelling/BigramLanguageModel.cpp \ LanguageModelling/BigramLanguageModel.h \ LanguageModelling/KanjiConversionIME.cpp \ LanguageModelling/KanjiConversionIME.h \ DasherCore.vcproj \ DasherCore_vc80.vcproj \ IMEConversionHelper.cpp \ IMEConversionHelper.h
rgee/HFOSS-Dasher
bbc07b623f43404e294d78508b4a222e7c607b17
Modified DasherInterfaceBase to integrate the game module in. Not sure whether it compiles or not - still having trouble in that arena.
diff --git a/Src/DasherCore/DasherInterfaceBase.cpp b/Src/DasherCore/DasherInterfaceBase.cpp index 09ea7bc..0a1fc60 100644 --- a/Src/DasherCore/DasherInterfaceBase.cpp +++ b/Src/DasherCore/DasherInterfaceBase.cpp @@ -1,1138 +1,1156 @@ // DasherInterfaceBase.cpp // // Copyright (c) 2008 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" #include "DasherInterfaceBase.h" //#include "ActionButton.h" #include "DasherViewSquare.h" #include "ControlManager.h" #include "DasherScreen.h" #include "DasherView.h" #include "DasherInput.h" #include "DasherModel.h" #include "EventHandler.h" #include "Event.h" #include "NodeCreationManager.h" #ifndef _WIN32_WCE #include "UserLog.h" #include "BasicLog.h" #endif #include "DasherGameMode.h" // Input filters #include "AlternatingDirectMode.h" #include "ButtonMode.h" #include "ClickFilter.h" #include "CompassMode.h" #include "DefaultFilter.h" #include "EyetrackerFilter.h" #include "OneButtonFilter.h" #include "OneButtonDynamicFilter.h" #include "OneDimensionalFilter.h" #include "StylusFilter.h" #include "TwoButtonDynamicFilter.h" #include "TwoPushDynamicFilter.h" // STL headers #include <cstdio> #include <iostream> #include <memory> // Declare our global file logging object #include "../DasherCore/FileLogger.h" #ifdef _DEBUG const eLogLevel g_iLogLevel = logDEBUG; const int g_iLogOptions = logTimeStamp | logDateStamp | logDeleteOldFile; #else const eLogLevel g_iLogLevel = logNORMAL; const int g_iLogOptions = logTimeStamp | logDateStamp; #endif #ifndef _WIN32_WCE CFileLogger* g_pLogger = NULL; #endif using namespace Dasher; using namespace std; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG_MEMLEAKS #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif CDasherInterfaceBase::CDasherInterfaceBase() { // Ensure that pointers to 'owned' objects are set to NULL. m_Alphabet = NULL; m_pDasherModel = NULL; m_DasherScreen = NULL; m_pDasherView = NULL; m_pInput = NULL; m_pInputFilter = NULL; m_AlphIO = NULL; m_ColourIO = NULL; m_pUserLog = NULL; m_pNCManager = NULL; m_defaultPolicy = NULL; + m_pGameModule = NULL; // Various state variables m_bRedrawScheduled = false; m_iCurrentState = ST_START; // m_bGlobalLock = false; // TODO: Are these actually needed? strCurrentContext = ". "; strTrainfileBuffer = ""; // Create an event handler. m_pEventHandler = new CEventHandler(this); m_bLastChanged = true; #ifndef _WIN32_WCE // Global logging object we can use from anywhere g_pLogger = new CFileLogger("dasher.log", g_iLogLevel, g_iLogOptions); #endif } void CDasherInterfaceBase::Realize() { // TODO: What exactly needs to have happened by the time we call Realize()? CreateSettingsStore(); SetupUI(); SetupPaths(); std::vector<std::string> vAlphabetFiles; ScanAlphabetFiles(vAlphabetFiles); m_AlphIO = new CAlphIO(GetStringParameter(SP_SYSTEM_LOC), GetStringParameter(SP_USER_LOC), vAlphabetFiles); std::vector<std::string> vColourFiles; ScanColourFiles(vColourFiles); m_ColourIO = new CColourIO(GetStringParameter(SP_SYSTEM_LOC), GetStringParameter(SP_USER_LOC), vColourFiles); ChangeColours(); ChangeAlphabet(); // This creates the NodeCreationManager, the Alphabet // Create the user logging object if we are suppose to. We wait // until now so we have the real value of the parameter and not // just the default. // TODO: Sort out log type selection #ifndef _WIN32_WCE int iUserLogLevel = GetLongParameter(LP_USER_LOG_LEVEL_MASK); if(iUserLogLevel == 10) m_pUserLog = new CBasicLog(m_pEventHandler, m_pSettingsStore); else if (iUserLogLevel > 0) m_pUserLog = new CUserLog(m_pEventHandler, m_pSettingsStore, iUserLogLevel, m_Alphabet); #else m_pUserLog = NULL; #endif CreateModules(); CreateInput(); CreateInputFilter(); SetupActionButtons(); CParameterNotificationEvent oEvent(LP_NODE_BUDGET); InterfaceEventHandler(&oEvent); + //if game mode is enabled , initialize the game module + if(GetBoolParameter(BP_GAME_MODE)) + InitGameModule(); + // Set up real orientation to match selection if(GetLongParameter(LP_ORIENTATION) == Dasher::Opts::AlphabetDefault) SetLongParameter(LP_REAL_ORIENTATION, m_Alphabet->GetOrientation()); else SetLongParameter(LP_REAL_ORIENTATION, GetLongParameter(LP_ORIENTATION)); // FIXME - need to rationalise this sort of thing. // InvalidateContext(true); ScheduleRedraw(); #ifndef _WIN32_WCE // All the setup is done by now, so let the user log object know // that future parameter changes should be logged. if (m_pUserLog != NULL) m_pUserLog->InitIsDone(); #endif // TODO: Make things work when model is created latet ChangeState(TR_MODEL_INIT); using GameMode::CDasherGameMode; // Create the teacher singleton object. CDasherGameMode::CreateTeacher(m_pEventHandler, m_pSettingsStore, this); CDasherGameMode::GetTeacher()->SetDasherView(m_pDasherView); CDasherGameMode::GetTeacher()->SetDasherModel(m_pDasherModel); } CDasherInterfaceBase::~CDasherInterfaceBase() { DASHER_ASSERT(m_iCurrentState == ST_SHUTDOWN); // It may seem odd that InterfaceBase does not "own" the teacher. // This is because game mode is a different layer, in a sense. GameMode::CDasherGameMode::DestroyTeacher(); delete m_pDasherModel; // The order of some of these deletions matters delete m_Alphabet; delete m_pDasherView; delete m_ColourIO; delete m_AlphIO; delete m_pNCManager; // Do NOT delete Edit box or Screen. This class did not create them. #ifndef _WIN32_WCE // When we destruct on shutdown, we'll output any detailed log file if (m_pUserLog != NULL) { m_pUserLog->OutputFile(); delete m_pUserLog; m_pUserLog = NULL; } if (g_pLogger != NULL) { delete g_pLogger; g_pLogger = NULL; } #endif for (std::vector<CActionButton *>::iterator it=m_vLeftButtons.begin(); it != m_vLeftButtons.end(); ++it) delete *it; for (std::vector<CActionButton *>::iterator it=m_vRightButtons.begin(); it != m_vRightButtons.end(); ++it) delete *it; // Must delete event handler after all CDasherComponent derived classes delete m_pEventHandler; } void CDasherInterfaceBase::PreSetNotify(int iParameter, const std::string &sNewValue) { // FIXME - make this a more general 'pre-set' event in the message // infrastructure switch(iParameter) { case SP_ALPHABET_ID: // Cycle the alphabet history if(GetStringParameter(SP_ALPHABET_ID) != sNewValue) { if(GetStringParameter(SP_ALPHABET_1) != sNewValue) { if(GetStringParameter(SP_ALPHABET_2) != sNewValue) { if(GetStringParameter(SP_ALPHABET_3) != sNewValue) SetStringParameter(SP_ALPHABET_4, GetStringParameter(SP_ALPHABET_3)); SetStringParameter(SP_ALPHABET_3, GetStringParameter(SP_ALPHABET_2)); } SetStringParameter(SP_ALPHABET_2, GetStringParameter(SP_ALPHABET_1)); } SetStringParameter(SP_ALPHABET_1, GetStringParameter(SP_ALPHABET_ID)); } break; } } void CDasherInterfaceBase::InterfaceEventHandler(Dasher::CEvent *pEvent) { if(pEvent->m_iEventType == EV_PARAM_NOTIFY) { Dasher::CParameterNotificationEvent * pEvt(static_cast < Dasher::CParameterNotificationEvent * >(pEvent)); switch (pEvt->m_iParameter) { case BP_OUTLINE_MODE: ScheduleRedraw(); break; case BP_DRAW_MOUSE: ScheduleRedraw(); break; case BP_CONTROL_MODE: ScheduleRedraw(); break; case BP_DRAW_MOUSE_LINE: ScheduleRedraw(); break; case LP_ORIENTATION: if(GetLongParameter(LP_ORIENTATION) == Dasher::Opts::AlphabetDefault) // TODO: See comment in DasherModel.cpp about prefered values SetLongParameter(LP_REAL_ORIENTATION, m_Alphabet->GetOrientation()); else SetLongParameter(LP_REAL_ORIENTATION, GetLongParameter(LP_ORIENTATION)); ScheduleRedraw(); break; case SP_ALPHABET_ID: ChangeAlphabet(); ScheduleRedraw(); break; case SP_COLOUR_ID: ChangeColours(); ScheduleRedraw(); break; case SP_DEFAULT_COLOUR_ID: // Delibarate fallthrough case BP_PALETTE_CHANGE: if(GetBoolParameter(BP_PALETTE_CHANGE)) SetStringParameter(SP_COLOUR_ID, GetStringParameter(SP_DEFAULT_COLOUR_ID)); break; case LP_LANGUAGE_MODEL_ID: CreateNCManager(); break; case LP_LINE_WIDTH: ScheduleRedraw(); break; case LP_DASHER_FONTSIZE: ScheduleRedraw(); break; case SP_INPUT_DEVICE: CreateInput(); break; case SP_INPUT_FILTER: CreateInputFilter(); ScheduleRedraw(); break; case BP_DASHER_PAUSED: ScheduleRedraw(); break; case LP_MARGIN_WIDTH: case BP_NONLINEAR_Y: case LP_NONLINEAR_X: ScheduleRedraw(); break; case LP_NODE_BUDGET: delete m_defaultPolicy; m_defaultPolicy = new AmortizedPolicy(GetLongParameter(LP_NODE_BUDGET)); default: break; } } else if(pEvent->m_iEventType == EV_EDIT && !GetBoolParameter(BP_GAME_MODE)) { CEditEvent *pEditEvent(static_cast < CEditEvent * >(pEvent)); if(pEditEvent->m_iEditType == 1) { strCurrentContext += pEditEvent->m_sText; if( strCurrentContext.size() > 20 ) strCurrentContext = strCurrentContext.substr( strCurrentContext.size() - 20 ); if(GetBoolParameter(BP_LM_ADAPTIVE)) strTrainfileBuffer += pEditEvent->m_sText; } else if(pEditEvent->m_iEditType == 2) { strCurrentContext = strCurrentContext.substr( 0, strCurrentContext.size() - pEditEvent->m_sText.size()); if(GetBoolParameter(BP_LM_ADAPTIVE)) strTrainfileBuffer = strTrainfileBuffer.substr( 0, strTrainfileBuffer.size() - pEditEvent->m_sText.size()); } } else if(pEvent->m_iEventType == EV_CONTROL) { CControlEvent *pControlEvent(static_cast <CControlEvent*>(pEvent)); switch(pControlEvent->m_iID) { case CControlManager::CTL_STOP: Pause(); break; case CControlManager::CTL_PAUSE: //Halt Dasher - without a stop event, so does not result in speech etc. SetBoolParameter(BP_DASHER_PAUSED, true); m_pDasherModel->TriggerSlowdown(); } } } void CDasherInterfaceBase::WriteTrainFileFull() { WriteTrainFile(strTrainfileBuffer); strTrainfileBuffer = ""; } void CDasherInterfaceBase::WriteTrainFilePartial() { // TODO: what if we're midway through a unicode character? WriteTrainFile(strTrainfileBuffer.substr(0,100)); strTrainfileBuffer = strTrainfileBuffer.substr(100); } void CDasherInterfaceBase::CreateModel(int iOffset) { // Creating a model without a node creation manager is a bad plan if(!m_pNCManager) return; if(m_pDasherModel) { delete m_pDasherModel; m_pDasherModel = 0; } m_pDasherModel = new CDasherModel(m_pEventHandler, m_pSettingsStore, m_pNCManager, this, m_pDasherView, iOffset); // Notify the teacher of the new model if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) pTeacher->SetDasherModel(m_pDasherModel); } void CDasherInterfaceBase::CreateNCManager() { // TODO: Try and make this work without necessarilty rebuilding the model if(!m_AlphIO) return; int lmID = GetLongParameter(LP_LANGUAGE_MODEL_ID); if( lmID == -1 ) return; int iOffset; if(m_pDasherModel) iOffset = m_pDasherModel->GetOffset(); else iOffset = 0; // TODO: Is this right? // Delete the old model and create a new one if(m_pDasherModel) { delete m_pDasherModel; m_pDasherModel = 0; } if(m_pNCManager) { delete m_pNCManager; m_pNCManager = 0; } m_pNCManager = new CNodeCreationManager(this, m_pEventHandler, m_pSettingsStore, m_AlphIO); m_Alphabet = m_pNCManager->GetAlphabet(); // TODO: Eventually we'll not have to pass the NC manager to the model... CreateModel(iOffset); } void CDasherInterfaceBase::Pause() { if (GetBoolParameter(BP_DASHER_PAUSED)) return; //already paused, no need to do anything. SetBoolParameter(BP_DASHER_PAUSED, true); // Request a full redraw at the next time step. SetBoolParameter(BP_REDRAW, true); Dasher::CStopEvent oEvent; m_pEventHandler->InsertEvent(&oEvent); #ifndef _WIN32_WCE if (m_pUserLog != NULL) m_pUserLog->StopWriting((float) GetNats()); #endif } void CDasherInterfaceBase::GameMessageIn(int message, void* messagedata) { GameMode::CDasherGameMode::GetTeacher()->Message(message, messagedata); } void CDasherInterfaceBase::Unpause(unsigned long Time) { if (!GetBoolParameter(BP_DASHER_PAUSED)) return; //already running, no need to do anything SetBoolParameter(BP_DASHER_PAUSED, false); if(m_pDasherModel != 0) m_pDasherModel->Reset_framerate(Time); Dasher::CStartEvent oEvent; m_pEventHandler->InsertEvent(&oEvent); // Commenting this out, can't see a good reason to ResetNats, // just because we are not paused anymore - pconlon // ResetNats(); #ifndef _WIN32_WCE if (m_pUserLog != NULL) m_pUserLog->StartWriting(); #endif } void CDasherInterfaceBase::CreateInput() { if(m_pInput) { m_pInput->Deactivate(); } m_pInput = (CDasherInput *)GetModuleByName(GetStringParameter(SP_INPUT_DEVICE)); if (m_pInput == NULL) m_pInput = (CDasherInput *)GetDefaultInputDevice(); if(m_pInput) { m_pInput->Activate(); } if(m_pDasherView != 0) m_pDasherView->SetInput(m_pInput); } void CDasherInterfaceBase::NewFrame(unsigned long iTime, bool bForceRedraw) { // Prevent NewFrame from being reentered. This can happen occasionally and // cause crashes. static bool bReentered=false; if (bReentered) { #ifdef DEBUG std::cout << "CDasherInterfaceBase::NewFrame was re-entered" << std::endl; #endif return; } bReentered=true; // Fail if Dasher is locked // if(m_iCurrentState != ST_NORMAL) // return; bool bChanged(false), bWasPaused(GetBoolParameter(BP_DASHER_PAUSED)); CExpansionPolicy *pol=m_defaultPolicy; if(m_pDasherView != 0) { if(!GetBoolParameter(BP_TRAINING)) { if (m_pUserLog != NULL) { //ACL note that as of 15/5/09, splitting UpdatePosition into two, //DasherModel no longer guarantees to empty these two if it didn't do anything. //So initialise appropriately... Dasher::VECTOR_SYMBOL_PROB vAdded; int iNumDeleted = 0; if(m_pInputFilter) { bChanged = m_pInputFilter->Timer(iTime, m_pDasherView, m_pDasherModel, &vAdded, &iNumDeleted, &pol); } #ifndef _WIN32_WCE if (iNumDeleted > 0) m_pUserLog->DeleteSymbols(iNumDeleted); if (vAdded.size() > 0) m_pUserLog->AddSymbols(&vAdded); #endif } else { if(m_pInputFilter) { bChanged = m_pInputFilter->Timer(iTime, m_pDasherView, m_pDasherModel, 0, 0, &pol); } } m_pDasherModel->CheckForNewRoot(m_pDasherView); } } //check: if we were paused before, and the input filter didn't unpause, // then nothing can have changed: DASHER_ASSERT(!bWasPaused || !GetBoolParameter(BP_DASHER_PAUSED) || !bChanged); // Flags at this stage: // // - bChanged = the display was updated, so needs to be rendered to the display // - m_bLastChanged = bChanged was true last time around // - m_bRedrawScheduled = Display invalidated internally // - bForceRedraw = Display invalidated externally // TODO: This is a bit hacky - we really need to sort out the redraw logic if((!bChanged && m_bLastChanged) || m_bRedrawScheduled || bForceRedraw) { m_pDasherView->Screen()->SetCaptureBackground(true); m_pDasherView->Screen()->SetLoadBackground(true); } bForceRedraw |= m_bLastChanged; m_bLastChanged = bChanged; //will also be set in Redraw if any nodes were expanded. Redraw(bChanged || m_bRedrawScheduled || bForceRedraw, *pol); m_bRedrawScheduled = false; // This just passes the time through to the framerate tracker, so we // know how often new frames are being drawn. if(m_pDasherModel != 0) m_pDasherModel->RecordFrame(iTime); bReentered=false; } void CDasherInterfaceBase::Redraw(bool bRedrawNodes, CExpansionPolicy &policy) { // No point continuing if there's nothing to draw on... if(!m_pDasherView) return; // Draw the nodes if(bRedrawNodes) { m_pDasherView->Screen()->SendMarker(0); if (m_pDasherModel) m_bLastChanged |= m_pDasherModel->RenderToView(m_pDasherView,policy); } // Draw the decorations m_pDasherView->Screen()->SendMarker(1); if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) pTeacher->DrawGameDecorations(m_pDasherView); bool bDecorationsChanged(false); if(m_pInputFilter) { bDecorationsChanged = m_pInputFilter->DecorateView(m_pDasherView); } bool bActionButtonsChanged(false); #ifdef EXPERIMENTAL_FEATURES bActionButtonsChanged = DrawActionButtons(); #endif // Only blit the image to the display if something has actually changed if(bRedrawNodes || bDecorationsChanged || bActionButtonsChanged) m_pDasherView->Display(); } void CDasherInterfaceBase::ChangeAlphabet() { if(GetStringParameter(SP_ALPHABET_ID) == "") { SetStringParameter(SP_ALPHABET_ID, m_AlphIO->GetDefault()); // This will result in ChangeAlphabet() being called again, so // exit from the first recursion return; } // Send a lock event WriteTrainFileFull(); // Lock Dasher to prevent changes from happening while we're training. SetBoolParameter( BP_TRAINING, true ); CreateNCManager(); #ifndef _WIN32_WCE // Let our user log object know about the new alphabet since // it needs to convert symbols into text for the log file. if (m_pUserLog != NULL) m_pUserLog->SetAlphabetPtr(m_Alphabet); #endif // Apply options from alphabet SetBoolParameter( BP_TRAINING, false ); //} } void CDasherInterfaceBase::ChangeColours() { if(!m_ColourIO || !m_DasherScreen) return; // TODO: Make fuction return a pointer directly m_DasherScreen->SetColourScheme(&(m_ColourIO->GetInfo(GetStringParameter(SP_COLOUR_ID)))); } void CDasherInterfaceBase::ChangeScreen(CDasherScreen *NewScreen) { // What does ChangeScreen do? m_DasherScreen = NewScreen; ChangeColours(); if(m_pDasherView != 0) { m_pDasherView->ChangeScreen(m_DasherScreen); } else if(GetLongParameter(LP_VIEW_ID) != -1) { ChangeView(); } PositionActionButtons(); BudgettingPolicy pol(GetLongParameter(LP_NODE_BUDGET)); //maintain budget, but allow arbitrary amount of work. Redraw(true, pol); // (we're assuming resolution changes are occasional, i.e. // we don't need to worry about maintaining the frame rate, so we can do // as much work as necessary. However, it'd probably be better still to // get a node queue from the input filter, as that might have a different // policy / budget. } void CDasherInterfaceBase::ChangeView() { // TODO: Actually respond to LP_VIEW_ID parameter (although there is only one view at the moment) // removed condition that m_pDasherModel != 0. Surely the view can exist without the model?-pconlon if(m_DasherScreen != 0 /*&& m_pDasherModel != 0*/) { delete m_pDasherView; m_pDasherView = new CDasherViewSquare(m_pEventHandler, m_pSettingsStore, m_DasherScreen); if (m_pInput) m_pDasherView->SetInput(m_pInput); // Tell the Teacher which view we are using if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) pTeacher->SetDasherView(m_pDasherView); } } const CAlphIO::AlphInfo & CDasherInterfaceBase::GetInfo(const std::string &AlphID) { return m_AlphIO->GetInfo(AlphID); } void CDasherInterfaceBase::SetInfo(const CAlphIO::AlphInfo &NewInfo) { m_AlphIO->SetInfo(NewInfo); } void CDasherInterfaceBase::DeleteAlphabet(const std::string &AlphID) { m_AlphIO->Delete(AlphID); } double CDasherInterfaceBase::GetCurCPM() { // return 0; } double CDasherInterfaceBase::GetCurFPS() { // return 0; } // int CDasherInterfaceBase::GetAutoOffset() { // if(m_pDasherView != 0) { // return m_pDasherView->GetAutoOffset(); // } // return -1; // } double CDasherInterfaceBase::GetNats() const { if(m_pDasherModel) return m_pDasherModel->GetNats(); else return 0.0; } void CDasherInterfaceBase::ResetNats() { if(m_pDasherModel) m_pDasherModel->ResetNats(); } // TODO: Check that none of this needs to be reimplemented // void CDasherInterfaceBase::InvalidateContext(bool bForceStart) { // m_pDasherModel->m_strContextBuffer = ""; // Dasher::CEditContextEvent oEvent(10); // m_pEventHandler->InsertEvent(&oEvent); // std::string strNewContext(m_pDasherModel->m_strContextBuffer); // // We keep track of an internal context and compare that to what // // we are given - don't restart Dasher if nothing has changed. // // This should really be integrated with DasherModel, which // // probably will be the case when we start to deal with being able // // to back off indefinitely. For now though we'll keep it in a // // separate string. // int iContextLength( 6 ); // The 'important' context length - should really get from language model // // FIXME - use unicode lengths // if(bForceStart || (strNewContext.substr( std::max(static_cast<int>(strNewContext.size()) - iContextLength, 0)) != strCurrentContext.substr( std::max(static_cast<int>(strCurrentContext.size()) - iContextLength, 0)))) { // if(m_pDasherModel != NULL) { // // TODO: Reimplement this // // if(m_pDasherModel->m_bContextSensitive || bForceStart) { // { // m_pDasherModel->SetContext(strNewContext); // PauseAt(0,0); // } // } // strCurrentContext = strNewContext; // WriteTrainFileFull(); // } // if(bForceStart) { // int iMinWidth; // if(m_pInputFilter && m_pInputFilter->GetMinWidth(iMinWidth)) { // m_pDasherModel->LimitRoot(iMinWidth); // } // } // if(m_pDasherView) // while( m_pDasherModel->CheckForNewRoot(m_pDasherView) ) { // // Do nothing // } // ScheduleRedraw(); // } // TODO: Fix this std::string CDasherInterfaceBase::GetContext(int iStart, int iLength) { m_strContext = ""; CEditContextEvent oEvent(iStart, iLength); m_pEventHandler->InsertEvent(&oEvent); return m_strContext; } void CDasherInterfaceBase::SetContext(std::string strNewContext) { m_strContext = strNewContext; } // Control mode stuff void CDasherInterfaceBase::RegisterNode( int iID, const std::string &strLabel, int iColour ) { m_pNCManager->RegisterNode(iID, strLabel, iColour); } void CDasherInterfaceBase::ConnectNode(int iChild, int iParent, int iAfter) { m_pNCManager->ConnectNode(iChild, iParent, iAfter); } void CDasherInterfaceBase::DisconnectNode(int iChild, int iParent) { m_pNCManager->DisconnectNode(iChild, iParent); } void CDasherInterfaceBase::SetBoolParameter(int iParameter, bool bValue) { m_pSettingsStore->SetBoolParameter(iParameter, bValue); }; void CDasherInterfaceBase::SetLongParameter(int iParameter, long lValue) { m_pSettingsStore->SetLongParameter(iParameter, lValue); }; void CDasherInterfaceBase::SetStringParameter(int iParameter, const std::string & sValue) { PreSetNotify(iParameter, sValue); m_pSettingsStore->SetStringParameter(iParameter, sValue); }; bool CDasherInterfaceBase::GetBoolParameter(int iParameter) { return m_pSettingsStore->GetBoolParameter(iParameter); } long CDasherInterfaceBase::GetLongParameter(int iParameter) { return m_pSettingsStore->GetLongParameter(iParameter); } std::string CDasherInterfaceBase::GetStringParameter(int iParameter) { return m_pSettingsStore->GetStringParameter(iParameter); } void CDasherInterfaceBase::ResetParameter(int iParameter) { m_pSettingsStore->ResetParameter(iParameter); } // We need to be able to get at the UserLog object from outside the interface CUserLogBase* CDasherInterfaceBase::GetUserLogPtr() { return m_pUserLog; } void CDasherInterfaceBase::KeyDown(int iTime, int iId, bool bPos, int iX, int iY) { if(m_iCurrentState != ST_NORMAL) return; if(m_pInputFilter && !GetBoolParameter(BP_TRAINING)) { m_pInputFilter->KeyDown(iTime, iId, m_pDasherView, m_pDasherModel, m_pUserLog, bPos, iX, iY); } if(m_pInput && !GetBoolParameter(BP_TRAINING)) { m_pInput->KeyDown(iTime, iId); } } void CDasherInterfaceBase::KeyUp(int iTime, int iId, bool bPos, int iX, int iY) { if(m_iCurrentState != ST_NORMAL) return; if(m_pInputFilter && !GetBoolParameter(BP_TRAINING)) { m_pInputFilter->KeyUp(iTime, iId, m_pDasherView, m_pDasherModel, bPos, iX, iY); } if(m_pInput && !GetBoolParameter(BP_TRAINING)) { m_pInput->KeyUp(iTime, iId); } } +void CDasherInterFaceBase::InitGameModule() { + + if(m_pGameModule == NULL) + m_pGameModule = (CGameModule*) GetModuleByName(GetStringParameter(BP_GAME_MODULE)); +} + void CDasherInterfaceBase::CreateInputFilter() { if(m_pInputFilter) { m_pInputFilter->Deactivate(); m_pInputFilter = NULL; } #ifndef _WIN32_WCE m_pInputFilter = (CInputFilter *)GetModuleByName(GetStringParameter(SP_INPUT_FILTER)); #endif if (m_pInputFilter == NULL) m_pInputFilter = (CInputFilter *)GetDefaultInputMethod(); m_pInputFilter->Activate(); } CDasherModule *CDasherInterfaceBase::RegisterModule(CDasherModule *pModule) { return m_oModuleManager.RegisterModule(pModule); } CDasherModule *CDasherInterfaceBase::GetModule(ModuleID_t iID) { return m_oModuleManager.GetModule(iID); } CDasherModule *CDasherInterfaceBase::GetModuleByName(const std::string &strName) { return m_oModuleManager.GetModuleByName(strName); } CDasherModule *CDasherInterfaceBase::GetDefaultInputDevice() { return m_oModuleManager.GetDefaultInputDevice(); } CDasherModule *CDasherInterfaceBase::GetDefaultInputMethod() { return m_oModuleManager.GetDefaultInputMethod(); } void CDasherInterfaceBase::SetDefaultInputDevice(CDasherModule *pModule) { m_oModuleManager.SetDefaultInputDevice(pModule); } void CDasherInterfaceBase::SetDefaultInputMethod(CDasherModule *pModule) { m_oModuleManager.SetDefaultInputMethod(pModule); } void CDasherInterfaceBase::CreateModules() { SetDefaultInputMethod( RegisterModule(new CDefaultFilter(m_pEventHandler, m_pSettingsStore, this, 3, _("Normal Control"))) ); RegisterModule(new COneDimensionalFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CEyetrackerFilter(m_pEventHandler, m_pSettingsStore, this)); #ifndef _WIN32_WCE RegisterModule(new CClickFilter(m_pEventHandler, m_pSettingsStore, this)); #else SetDefaultInputMethod( RegisterModule(new CClickFilter(m_pEventHandler, m_pSettingsStore, this)); ); #endif RegisterModule(new COneButtonFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new COneButtonDynamicFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CTwoButtonDynamicFilter(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CTwoPushDynamicFilter(m_pEventHandler, m_pSettingsStore, this)); // TODO: specialist factory for button mode RegisterModule(new CButtonMode(m_pEventHandler, m_pSettingsStore, this, true, 8, _("Menu Mode"))); RegisterModule(new CButtonMode(m_pEventHandler, m_pSettingsStore, this, false,10, _("Direct Mode"))); // RegisterModule(new CDasherButtons(m_pEventHandler, m_pSettingsStore, this, 4, 0, false,11, "Buttons 3")); RegisterModule(new CAlternatingDirectMode(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CCompassMode(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CStylusFilter(m_pEventHandler, m_pSettingsStore, this, 15, _("Stylus Control"))); + + // Register game mode with the module manager + // TODO should this be wrapped in an "if game mode enabled" + // conditional? + // TODO: I don't know what a sensible module ID should be + // for this, so I chose an arbitrary value + RegisterModule(new CGameModule(m_pEventHandler, m_pSettingsStore, this, 21, _("GameMode"))); } void CDasherInterfaceBase::GetPermittedValues(int iParameter, std::vector<std::string> &vList) { // TODO: Deprecate direct calls to these functions switch (iParameter) { case SP_ALPHABET_ID: if(m_AlphIO) m_AlphIO->GetAlphabets(&vList); break; case SP_COLOUR_ID: if(m_ColourIO) m_ColourIO->GetColours(&vList); break; case SP_INPUT_FILTER: m_oModuleManager.ListModules(1, vList); break; case SP_INPUT_DEVICE: m_oModuleManager.ListModules(0, vList); break; } } void CDasherInterfaceBase::StartShutdown() { ChangeState(TR_SHUTDOWN); } bool CDasherInterfaceBase::GetModuleSettings(const std::string &strName, SModuleSettings **pSettings, int *iCount) { return GetModuleByName(strName)->GetSettings(pSettings, iCount); } void CDasherInterfaceBase::SetupActionButtons() { m_vLeftButtons.push_back(new CActionButton(this, "Exit", true)); m_vLeftButtons.push_back(new CActionButton(this, "Preferences", false)); m_vLeftButtons.push_back(new CActionButton(this, "Help", false)); m_vLeftButtons.push_back(new CActionButton(this, "About", false)); } void CDasherInterfaceBase::DestroyActionButtons() { // TODO: implement and call this } void CDasherInterfaceBase::PositionActionButtons() { if(!m_DasherScreen) return; int iCurrentOffset(16); for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) { (*it)->SetPosition(16, iCurrentOffset, 32, 32); iCurrentOffset += 48; } iCurrentOffset = 16; for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) { (*it)->SetPosition(m_DasherScreen->GetWidth() - 144, iCurrentOffset, 128, 32); iCurrentOffset += 48; } } bool CDasherInterfaceBase::DrawActionButtons() { if(!m_DasherScreen) return false; bool bVisible(GetBoolParameter(BP_DASHER_PAUSED)); bool bRV(bVisible != m_bOldVisible); m_bOldVisible = bVisible; for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) (*it)->Draw(m_DasherScreen, bVisible); for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) (*it)->Draw(m_DasherScreen, bVisible); return bRV; } void CDasherInterfaceBase::HandleClickUp(int iTime, int iX, int iY) { #ifdef EXPERIMENTAL_FEATURES bool bVisible(GetBoolParameter(BP_DASHER_PAUSED)); for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) { if((*it)->HandleClickUp(iTime, iX, iY, bVisible)) return; } for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) { if((*it)->HandleClickUp(iTime, iX, iY, bVisible)) return; } #endif KeyUp(iTime, 100, true, iX, iY); } void CDasherInterfaceBase::HandleClickDown(int iTime, int iX, int iY) { #ifdef EXPERIMENTAL_FEATURES bool bVisible(GetBoolParameter(BP_DASHER_PAUSED)); for(std::vector<CActionButton *>::iterator it(m_vLeftButtons.begin()); it != m_vLeftButtons.end(); ++it) { if((*it)->HandleClickDown(iTime, iX, iY, bVisible)) return; } for(std::vector<CActionButton *>::iterator it(m_vRightButtons.begin()); it != m_vRightButtons.end(); ++it) { if((*it)->HandleClickDown(iTime, iX, iY, bVisible)) return; } #endif KeyDown(iTime, 100, true, iX, iY); } void CDasherInterfaceBase::ExecuteCommand(const std::string &strName) { // TODO: Pointless - just insert event directly CCommandEvent *pEvent = new CCommandEvent(strName); m_pEventHandler->InsertEvent(pEvent); delete pEvent; } double CDasherInterfaceBase::GetFramerate() { if(m_pDasherModel) return(m_pDasherModel->Framerate()); else return 0.0; } void CDasherInterfaceBase::AddActionButton(const std::string &strName) { m_vRightButtons.push_back(new CActionButton(this, strName, false)); } void CDasherInterfaceBase::OnUIRealised() { StartTimer(); ChangeState(TR_UI_INIT); } void CDasherInterfaceBase::ChangeState(ETransition iTransition) { static EState iTransitionTable[ST_NUM][TR_NUM] = { {ST_MODEL, ST_UI, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN},//ST_START {ST_FORBIDDEN, ST_NORMAL, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN},//ST_MODEL {ST_NORMAL, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN},//ST_UI {ST_FORBIDDEN, ST_FORBIDDEN, ST_LOCKED, ST_FORBIDDEN, ST_SHUTDOWN},//ST_NORMAL {ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_NORMAL, ST_FORBIDDEN},//ST_LOCKED {ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN, ST_FORBIDDEN}//ST_SHUTDOWN //TR_MODEL_INIT, TR_UI_INIT, TR_LOCK, TR_UNLOCK, TR_SHUTDOWN }; EState iNewState(iTransitionTable[m_iCurrentState][iTransition]); if(iNewState != ST_FORBIDDEN) { if (iNewState == ST_SHUTDOWN) { ShutdownTimer(); WriteTrainFileFull(); } m_iCurrentState = iNewState; } } void CDasherInterfaceBase::SetBuffer(int iOffset) { CreateModel(iOffset); } void CDasherInterfaceBase::UnsetBuffer() { // TODO: Write training file? if(m_pDasherModel) delete m_pDasherModel; m_pDasherModel = 0; } void CDasherInterfaceBase::SetOffset(int iOffset) { if(m_pDasherModel) m_pDasherModel->SetOffset(iOffset, m_pDasherView); } void CDasherInterfaceBase::SetControlOffset(int iOffset) { if(m_pDasherModel) m_pDasherModel->SetControlOffset(iOffset); } // Returns 0 on success, an error string on failure. const char* CDasherInterfaceBase::ClSet(const std::string &strKey, const std::string &strValue) { if(m_pSettingsStore) return m_pSettingsStore->ClSet(strKey, strValue); return 0; } void CDasherInterfaceBase::ImportTrainingText(const std::string &strPath) { if(m_pNCManager) m_pNCManager->ImportTrainingText(strPath); } diff --git a/Src/DasherCore/DasherInterfaceBase.h b/Src/DasherCore/DasherInterfaceBase.h index a73e7c9..6ca025d 100644 --- a/Src/DasherCore/DasherInterfaceBase.h +++ b/Src/DasherCore/DasherInterfaceBase.h @@ -9,571 +9,581 @@ // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #ifndef __DasherInterfaceBase_h__ #define __DasherInterfaceBase_h__ /// /// \mainpage /// /// This is the Dasher source code documentation. Please try to keep /// it up to date! /// // TODO - there is a list of things to be configurable in my notes // Check that everything that is not self-contained within the GUI is covered. #include "../Common/NoClones.h" #include "../Common/ModuleSettings.h" #include "ActionButton.h" #include "Alphabet/Alphabet.h" #include "Alphabet/AlphIO.h" #include "AutoSpeedControl.h" #include "ColourIO.h" #include "InputFilter.h" #include "ModuleManager.h" #include <map> #include <algorithm> namespace Dasher { class CDasherScreen; class CDasherView; class CDasherInput; class CDasherModel; class CEventHandler; class CEvent; class CDasherInterfaceBase; } class CSettingsStore; class CUserLogBase; class CNodeCreationManager; /// \defgroup Core Core Dasher classes /// @{ struct Dasher::SLockData { std::string strDisplay; int iPercent; }; /// The central class in the core of Dasher. Ties together the rest of /// the platform independent stuff and provides a single interface for /// the UI to use. class Dasher::CDasherInterfaceBase:private NoClones { public: CDasherInterfaceBase(); virtual ~CDasherInterfaceBase(); /// @name Access to internal member classes /// Access various classes contained within the interface. These /// should be considered dangerous and use minimised. Eventually to /// be replaced by properly encapsulated equivalents. /// @{ /// /// Return a pointer to the current EventHandler (the one /// which the CSettingsStore is using to notify parameter /// changes) /// virtual CEventHandler *GetEventHandler() { return m_pEventHandler; }; /// /// \deprecated In situ alphabet editing is no longer supported /// \todo Document this /// const CAlphIO::AlphInfo & GetInfo(const std::string & AlphID); /// \todo Document this void SetInfo(const CAlphIO::AlphInfo & NewInfo); /// \todo Document this void DeleteAlphabet(const std::string & AlphID); /// Get a pointer to the current alphabet object CAlphabet *GetAlphabet() { return m_Alphabet; } /// Gets a pointer to the object doing user logging CUserLogBase* GetUserLogPtr(); // @} /// /// @name Parameter manipulation /// Members for manipulating the parameters of the core Dasher object. /// //@{ /// /// Set a boolean parameter. /// \param iParameter The parameter to set. /// \param bValue The new value. /// void SetBoolParameter(int iParameter, bool bValue); /// /// Set a long integer parameter. /// \param iParameter The parameter to set. /// \param lValue The new value. /// void SetLongParameter(int iParameter, long lValue); /// /// Set a string parameter. /// \param iParameter The parameter to set. /// \param sValue The new value. /// void SetStringParameter(int iParameter, const std::string & sValue); /// Get a boolean parameter /// \param iParameter The parameter to get. /// \retval The current value. bool GetBoolParameter(int iParameter); /// Get a long integer parameter /// \param iParameter The parameter to get. /// \retval The current value. long GetLongParameter(int iParameter); /// Get a string parameter /// \param iParameter The parameter to get. /// \retval The current value. std::string GetStringParameter(int iParameter); /// /// Reset a parameter to the default value /// void ResetParameter(int iParmater); /// /// Obtain the permitted values for a string parameter - used to /// geneate preferences dialogues etc. /// void GetPermittedValues(int iParameter, std::vector<std::string> &vList); /// /// Get a list of settings which apply to a particular module /// bool GetModuleSettings(const std::string &strName, SModuleSettings **pSettings, int *iCount); //@} /// Forward events to listeners in the SettingsUI and Editbox. /// \param pEvent The event to forward. /// \todo Should be protected. virtual void ExternalEventHandler(Dasher::CEvent * pEvent) {}; /// Interface level event handler. For example, responsible for /// restarting the Dasher model whenever parameter changes make it /// invalid. /// \param pEvent The event. /// \todo Should be protected. void InterfaceEventHandler(Dasher::CEvent * pEvent); void PreSetNotify(int iParameter, const std::string &sValue); /// @name Starting and stopping /// Methods used to instruct dynamic motion of Dasher to start or stop /// @{ /// Resets the Dasher model. Doesn't actually unpause Dasher. /// \deprecated Use InvalidateContext() instead // void Start(); /// Pause Dasher. Sets BP_DASHER_PAUSED and broadcasts a StopEvent. /// (But does nothing if BP_DASHER_PAUSED is not set) void Pause(); // are required to make /// Unpause Dasher. Clears BP_DASHER_PAUSED, broadcasts a StartEvent. /// (But does nothing if BP_DASHER_PAUSED is currently set). /// \param Time Time in ms, used to keep a constant frame rate void Unpause(unsigned long Time); // Dasher run at the /// @} // App Interface // ----------------------------------------------------- // std::map<int, std::string>& GetAlphabets(); // map<key, value> int is a UID string can change. Store UID in preferences. Display string to user. // std::vector<std::string>& GetAlphabets(); // std::vector<std::string>& GetLangModels(); // std::vector<std::string>& GetViews(); /// Supply a new CDasherScreen object to do the rendering. /// \param NewScreen Pointer to the new CDasherScreen. void ChangeScreen(CDasherScreen * NewScreen); // We may change the widgets Dasher uses /// Train Dasher from a file /// All traing data must be in UTF-8 /// \param Filename File to load. /// \param iTotalBytes documentme /// \param iOffset Document me // int TrainFile(std::string Filename, int iTotalBytes, int iOffset); /// Set the context in which Dasher makes predictions /// \param strNewContext The new context (UTF-8) void SetContext(std::string strNewContext); /// New control mechanisms: void SetBuffer(int iOffset); void UnsetBuffer(); void SetOffset(int iOffset); /// @name Status reporting /// Get information about the runtime status of Dasher which might /// be of interest for debugging purposes etc. /// @{ /// Get the current rate of text entry. /// \retval The rate in characters per minute. /// TODO: Check that this is still used double GetCurCPM(); /// Get current refresh rate. /// \retval The rate in frames per second /// TODO: Check that this is still used double GetCurFPS(); /// Get the total number of nats (base-e bits) entered. /// \retval The current total /// \todo Obsolete since new logging code? double GetNats() const; /// Reset the count of nats entered. /// \todo Obsolete since new logging code? void ResetNats(); double GetFramerate(); /// @} /// @name Control hierarchy and action buttons /// Manipulate the hierarchy of commands presented in control mode etc /// @{ void RegisterNode( int iID, const std::string &strLabel, int iColour ); void ConnectNode(int iChild, int iParent, int iAfter); void DisconnectNode(int iChild, int iParent); void ExecuteCommand(const std::string &strName); void AddActionButton(const std::string &strName); /// @} /// @name User input /// Deals with forwarding user input to the core /// @{ void KeyDown(int iTime, int iId, bool bPos = false, int iX = 0, int iY = 0); void KeyUp(int iTime, int iId, bool bPos = false, int iX = 0, int iY = 0); void HandleClickUp(int iTime, int iX, int iY); void HandleClickDown(int iTime, int iX, int iY); /// @} // Module management functions CDasherModule *RegisterModule(CDasherModule *pModule); CDasherModule *GetModule(ModuleID_t iID); CDasherModule *GetModuleByName(const std::string &strName); CDasherModule *GetDefaultInputDevice(); CDasherModule *GetDefaultInputMethod(); void SetDefaultInputDevice(CDasherModule *); void SetDefaultInputMethod(CDasherModule *); void StartShutdown(); void AddGameModeString(const std::string &strText) { m_deGameModeStrings.push_back(strText); Pause(); // CreateDasherModel(); CreateNCManager(); // Start(); }; void GameMessageIn(int message, void* messagedata); virtual void GameMessageOut(int message, const void* messagedata) {} void ScheduleRedraw() { m_bRedrawScheduled = true; }; std::string GetContext(int iStart, int iLength); void SetControlOffset(int iOffset); /// Set a key value pair by name - designed to allow operation from /// the command line. Returns 0 on success, an error string on failure. /// const char* ClSet(const std::string &strKey, const std::string &strValue); void ImportTrainingText(const std::string &strPath); protected: /// @name Startup /// Interaction with the derived class during core startup /// @{ /// /// Allocate resources, create alphabets etc. This is a separate /// routine to the constructor to give us a chance to set up /// parameters before things are created. /// void Realize(); /// /// Notify the core that the UI has been realised. At this point drawing etc. is expected to work /// void OnUIRealised(); /// /// Creates a default set of modules. Override in subclasses to create any /// extra/different modules specific to the platform (eg input device drivers) /// virtual void CreateModules(); /// @} /// Draw a new Dasher frame, regardless of whether we're paused etc. /// \param iTime Current time in ms. /// \param bForceRedraw /// \todo See comments in cpp file for some functionality which needs to be re-implemented void NewFrame(unsigned long iTime, bool bForceRedraw); enum ETransition { TR_MODEL_INIT = 0, TR_UI_INIT, TR_LOCK, TR_UNLOCK, TR_SHUTDOWN, TR_NUM }; enum EState { ST_START = 0, ST_MODEL, ST_UI, ST_NORMAL, ST_LOCKED, ST_SHUTDOWN, ST_NUM, ST_FORBIDDEN, ST_DELAY }; /// @name State machine functions /// ... /// @{ void ChangeState(ETransition iTransition); /// @} CEventHandler *m_pEventHandler; CSettingsStore *m_pSettingsStore; private: //The default expansion policy to use - an amortized policy depending on the LP_NODE_BUDGET parameter. CExpansionPolicy *m_defaultPolicy; /// @name Platform dependent utility functions /// These functions provide various platform dependent functions /// required by the core. A derived class is created for each /// supported platform which implements these. // @{ /// /// Initialise the SP_SYSTEM_LOC and SP_USER_LOC paths - the exact /// method of doing this will be OS dependent /// virtual void SetupPaths() = 0; /// /// Produce a list of filenames for alphabet files /// virtual void ScanAlphabetFiles(std::vector<std::string> &vFileList) = 0; /// /// Produce a list of filenames for colour files /// virtual void ScanColourFiles(std::vector<std::string> &vFileList) = 0; /// /// Set up the platform dependent UI for the widget (not the wider /// app). Note that the constructor of the derived class will /// probably want to return details of what was created - this will /// have to happen separately, but we'll need to be careful with the /// semantics. /// virtual void SetupUI() = 0; /// /// Create settings store object, which will be platform dependent /// TODO: Can this not be done just by selecting which settings /// store implementation to instantiate? /// virtual void CreateSettingsStore() = 0; /// /// Obtain the size in bytes of a file - the way to do this is /// dependent on the OS (TODO: Check this - any posix on Windows?) /// virtual int GetFileSize(const std::string &strFileName) = 0; /// /// Start the callback timer /// virtual void StartTimer() = 0; /// /// Shutdown the callback timer (permenantly - this is called once /// Dasher is committed to closing). /// virtual void ShutdownTimer() = 0; /// /// Append text to the training file - used to store state between /// sessions /// @todo Pass file path to the function rather than having implementations work it out themselves /// virtual void WriteTrainFile(const std::string &strNewText) { }; /// @} /// Provide a new CDasherInput input device object. void CreateInput(); + + /* Initialize m_pGameModule by fetching the + * constructed module from the module manager. + */ + void InitGameModule(); + void CreateInputFilter(); void CreateModel(int iOffset); void CreateNCManager(); void ChangeAlphabet(); void ChangeColours(); void ChangeView(); void Redraw(bool bRedrawNodes, CExpansionPolicy &policy); void SetupActionButtons(); void DestroyActionButtons(); void PositionActionButtons(); bool DrawActionButtons(); void WriteTrainFileFull(); void WriteTrainFilePartial(); std::deque<std::string> m_deGameModeStrings; std::vector<CActionButton *> m_vLeftButtons; std::vector<CActionButton *> m_vRightButtons; /// @name Child components /// Various objects which are 'owned' by the core. /// @{ CAlphabet *m_Alphabet; CDasherModel *m_pDasherModel; CDasherScreen *m_DasherScreen; CDasherView *m_pDasherView; CDasherInput *m_pInput; CInputFilter* m_pInputFilter; CModuleManager m_oModuleManager; CAlphIO *m_AlphIO; CColourIO *m_ColourIO; CNodeCreationManager *m_pNCManager; - CUserLogBase *m_pUserLog; + CUserLogBase *m_pUserLog; + + // the game mode module - only + // initialized if game mode is enabled + CGameModule *m_pGameModule; /// @} std::string strTrainfileBuffer; std::string strCurrentContext; std::string m_strContext; /// @name State variables /// Represent the current overall state of the core /// @{ // bool m_bGlobalLock; // The big lock bool m_bRedrawScheduled; EState m_iCurrentState; bool m_bOldVisible; /// @} bool m_bLastChanged; }; /// @} #endif /* #ifndef __DasherInterfaceBase_h__ */ diff --git a/Src/DasherCore/Parameters.h b/Src/DasherCore/Parameters.h index 3de96ba..d0d25dd 100644 --- a/Src/DasherCore/Parameters.h +++ b/Src/DasherCore/Parameters.h @@ -1,367 +1,367 @@ // Parameters.h // // Copyright (c) 2007 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #ifndef __parameters_h__ #define __parameters_h__ #include <string> #ifdef HAVE_CONFIG_H #include <config.h> #endif // All parameters go into the enums here // They are unique across the different types enum { BP_DRAW_MOUSE_LINE, BP_DRAW_MOUSE, BP_CURVE_MOUSE_LINE, BP_SHOW_SLIDER, BP_START_MOUSE, BP_START_SPACE, BP_STOP_IDLE, BP_CONTROL_MODE, BP_COLOUR_MODE, BP_MOUSEPOS_MODE, BP_OUTLINE_MODE, BP_PALETTE_CHANGE, BP_AUTOCALIBRATE, BP_DASHER_PAUSED, BP_GAME_MODE, BP_TRAINING, BP_REDRAW, BP_LM_DICTIONARY, BP_LM_LETTER_EXCLUSION, BP_AUTO_SPEEDCONTROL, BP_LM_ADAPTIVE, BP_SOCKET_INPUT_ENABLE, BP_SOCKET_DEBUG, BP_CIRCLE_START, BP_GLOBAL_KEYBOARD, BP_NONLINEAR_Y, BP_SMOOTH_OFFSET, BP_CONVERSION_MODE, BP_PAUSE_OUTSIDE, BP_BACKOFF_BUTTON, BP_TWOBUTTON_REVERSE, BP_2B_INVERT_DOUBLE, BP_SLOW_START, #ifdef TARGET_OS_IPHONE BP_CUSTOM_TILT, BP_DOUBLE_X, #endif END_OF_BPS }; enum { LP_ORIENTATION = END_OF_BPS, LP_REAL_ORIENTATION, LP_MAX_BITRATE, LP_FRAMERATE, LP_VIEW_ID, LP_LANGUAGE_MODEL_ID, LP_DASHER_FONTSIZE, LP_UNIFORM, LP_YSCALE, LP_MOUSEPOSDIST, LP_STOP_IDLETIME, LP_LM_MAX_ORDER, LP_LM_EXCLUSION, LP_LM_UPDATE_EXCLUSION, LP_LM_ALPHA, LP_LM_BETA, LP_LM_MIXTURE, LP_MOUSE_POS_BOX, LP_NORMALIZATION, LP_LINE_WIDTH, LP_LM_WORD_ALPHA, LP_USER_LOG_LEVEL_MASK, LP_ZOOMSTEPS, LP_B, LP_S, LP_BUTTON_SCAN_TIME, LP_R, LP_RIGHTZOOM, LP_NODE_BUDGET, LP_NONLINEAR_X, LP_BOOSTFACTOR, LP_AUTOSPEED_SENSITIVITY, LP_SOCKET_PORT, LP_SOCKET_INPUT_X_MIN, LP_SOCKET_INPUT_X_MAX, LP_SOCKET_INPUT_Y_MIN, LP_SOCKET_INPUT_Y_MAX, LP_OX, LP_OY, LP_MAX_Y, LP_INPUT_FILTER, LP_CIRCLE_PERCENT, LP_TWO_BUTTON_OFFSET, LP_HOLD_TIME, LP_MULTIPRESS_TIME, LP_SLOW_START_TIME, LP_CONVERSION_ORDER, LP_CONVERSION_TYPE, LP_TWO_PUSH_OUTER, LP_TWO_PUSH_UP, LP_TWO_PUSH_DOWN, LP_TWO_PUSH_TOLERANCE, LP_DYNAMIC_BUTTON_LAG, LP_STATIC1B_TIME, LP_STATIC1B_ZOOM, LP_DEMO_SPRING, LP_DEMO_NOISE_MEM, LP_DEMO_NOISE_MAG, LP_MAXZOOM, LP_DYNAMIC_SPEED_INC, LP_DYNAMIC_SPEED_FREQ, LP_DYNAMIC_SPEED_DEC, LP_TAP_TIME, LP_MARGIN_WIDTH, END_OF_LPS }; enum { SP_ALPHABET_ID = END_OF_LPS, SP_ALPHABET_1, SP_ALPHABET_2, SP_ALPHABET_3, SP_ALPHABET_4, SP_COLOUR_ID, SP_DEFAULT_COLOUR_ID, SP_DASHER_FONT, SP_SYSTEM_LOC, SP_USER_LOC, SP_GAME_TEXT_FILE, SP_TRAIN_FILE, SP_SOCKET_INPUT_X_LABEL, SP_SOCKET_INPUT_Y_LABEL, SP_INPUT_FILTER, SP_INPUT_DEVICE, SP_BUTTON_0, SP_BUTTON_1, SP_BUTTON_2, SP_BUTTON_3, SP_BUTTON_4, SP_BUTTON_10, SP_JOYSTICK_DEVICE, #ifdef TARGET_OS_IPHONE SP_CUSTOM_TILT, SP_VERTICAL_TILT, #endif END_OF_SPS }; // Define first int value of the first element of each type. // Useful for offsetting into specific arrays, // since each setting is a unique int, but all 3 arrays start at 0 #define FIRST_BP 0 #define FIRST_LP END_OF_BPS #define FIRST_SP END_OF_LPS // Define the number of each type of setting #define NUM_OF_BPS END_OF_BPS #define NUM_OF_LPS (END_OF_LPS - END_OF_BPS) #define NUM_OF_SPS (END_OF_SPS - END_OF_LPS) #define PERS true // First level structures with only basic data types because you // cannot initialize struct tables with objects // These will be turned into std::strings in the ParamTables() object struct bp_table { int key; const char *regName; bool persistent; bool defaultValue; const char *humanReadable; }; struct lp_table { int key; const char *regName; bool persistent; long defaultValue; const char *humanReadable; }; struct sp_table { int key; const char *regName; bool persistent; const char *defaultValue; const char *humanReadable; }; // The only important thing here is that these are in the same order // as the enum declarations (could add check in class that enforces this instead) static bp_table boolparamtable[] = { {BP_DRAW_MOUSE_LINE, "DrawMouseLine", PERS, true, "Draw Mouse Line"}, {BP_DRAW_MOUSE, "DrawMouse", PERS, false, "Draw Mouse Position"}, {BP_CURVE_MOUSE_LINE, "CurveMouseLine", PERS, false, "Curve mouse line according to screen nonlinearity"}, #ifdef WITH_MAEMO {BP_SHOW_SLIDER, "ShowSpeedSlider", PERS, false, "ShowSpeedSlider"}, #else {BP_SHOW_SLIDER, "ShowSpeedSlider", PERS, true, "ShowSpeedSlider"}, #endif {BP_START_MOUSE, "StartOnLeft", PERS, true, "StartOnLeft"}, {BP_START_SPACE, "StartOnSpace", PERS, false, "StartOnSpace"}, {BP_STOP_IDLE, "StopOnIdle", PERS, false, "StopOnIdle"}, {BP_CONTROL_MODE, "ControlMode", PERS, false, "ControlMode"}, {BP_COLOUR_MODE, "ColourMode", PERS, true, "ColourMode"}, {BP_MOUSEPOS_MODE, "StartOnMousePosition", PERS, false, "StartOnMousePosition"}, {BP_OUTLINE_MODE, "OutlineBoxes", PERS, true, "OutlineBoxes"}, {BP_PALETTE_CHANGE, "PaletteChange", PERS, true, "PaletteChange"}, {BP_AUTOCALIBRATE, "Autocalibrate", PERS, true, "Autocalibrate"}, {BP_DASHER_PAUSED, "DasherPaused", !PERS, true, "Dasher Paused"}, - {BP_GAME_MODE, "GameMode", !PERS, false, "Dasher Game Mode"}, + {BP_GAME_MODE, "GameMode", PERS, false, "Dasher Game Mode"}, {BP_TRAINING, "Training", !PERS, false, "Provides locking during training"}, {BP_REDRAW, "Redraw", !PERS, false, "Force a full redraw at the next timer event"}, {BP_LM_DICTIONARY, "Dictionary", PERS, true, "Whether the word-based language model uses a dictionary"}, {BP_LM_LETTER_EXCLUSION, "LetterExclusion", PERS, true, "Whether to do letter exclusion in the word-based model"}, {BP_AUTO_SPEEDCONTROL, "AutoSpeedControl", PERS, true, "AutoSpeedControl"}, {BP_LM_ADAPTIVE, "LMAdaptive", PERS, true, "Whether language model should learn as you enter text"}, {BP_SOCKET_INPUT_ENABLE, "SocketInputEnable", PERS, false, "Read pointer coordinates from network socket instead of mouse"}, {BP_SOCKET_DEBUG, "SocketInputDebug", PERS, false, "Print information about socket input processing to console"}, {BP_CIRCLE_START, "CircleStart", PERS, false, "Start on circle mode"}, {BP_GLOBAL_KEYBOARD, "GlobalKeyboard", PERS, false, "Whether to assume global control of the keyboard"}, #ifdef WITH_MAEMO {BP_NONLINEAR_Y, "NonlinearY", PERS, false, "Apply nonlinearities to Y axis (i.e. compress top &amp; bottom)"}, #else {BP_NONLINEAR_Y, "NonlinearY", PERS, true, "Apply nonlinearities to Y axis (i.e. compress top &amp; bottom)"}, #endif {BP_SMOOTH_OFFSET, "DelayView", !PERS, false, "Smooth dynamic-button-mode jumps over several frames"}, {BP_CONVERSION_MODE, "ConversionMode", !PERS, false, "Whether Dasher is operating in conversion (eg Japanese) mode"}, {BP_PAUSE_OUTSIDE, "PauseOutside", PERS, false, "Whether to pause when pointer leaves canvas area"}, #ifdef TARGET_OS_IPHONE {BP_BACKOFF_BUTTON, "BackoffButton", PERS, false, "Whether to enable the extra backoff button in dynamic mode"}, #else {BP_BACKOFF_BUTTON, "BackoffButton", PERS, true, "Whether to enable the extra backoff button in dynamic mode"}, #endif {BP_TWOBUTTON_REVERSE, "TwoButtonReverse", PERS, false, "Reverse the up/down buttons in two button mode"}, {BP_2B_INVERT_DOUBLE, "TwoButtonInvertDouble", PERS, false, "Double-press acts as opposite button in two-button mode"}, {BP_SLOW_START, "SlowStart", PERS, false, "Start at low speed and increase"}, #ifdef TARGET_OS_IPHONE {BP_CUSTOM_TILT, "CustomTilt", PERS, false, "Use custom tilt axes"}, {BP_DOUBLE_X, "DoubleXCoords", PERS, false, "Double X-coordinate of touch"}, #endif }; static lp_table longparamtable[] = { {LP_ORIENTATION, "ScreenOrientation", PERS, -2, "Screen Orientation"}, {LP_REAL_ORIENTATION, "RealOrientation", !PERS, 0, "Actual screen orientation (allowing for alphabet default)"}, {LP_MAX_BITRATE, "MaxBitRateTimes100", PERS, 80, "Max Bit Rate Times 100"}, {LP_FRAMERATE, "FrameRate", PERS, 3200, "Last known frame rate, times 100"}, {LP_VIEW_ID, "ViewID", PERS, 1, "ViewID"}, {LP_LANGUAGE_MODEL_ID, "LanguageModelID", PERS, 0, "LanguageModelID"}, {LP_DASHER_FONTSIZE, "DasherFontSize", PERS, 2, "DasherFontSize"}, {LP_UNIFORM, "UniformTimes1000", PERS, 50, "UniformTimes1000"}, {LP_YSCALE, "YScaling", PERS, 0, "YScaling"}, {LP_MOUSEPOSDIST, "MousePositionBoxDistance", PERS, 50, "MousePositionBoxDistance"}, {LP_STOP_IDLETIME, "StopIdleTime", PERS, 1000, "StopIdleTime" }, {LP_LM_MAX_ORDER, "LMMaxOrder", PERS, 5, "LMMaxOrder"}, {LP_LM_EXCLUSION, "LMExclusion", PERS, 0, "LMExclusion"}, {LP_LM_UPDATE_EXCLUSION, "LMUpdateExclusion", PERS, 1, "LMUpdateExclusion"}, {LP_LM_ALPHA, "LMAlpha", PERS, 49, "LMAlpha"}, {LP_LM_BETA, "LMBeta", PERS, 77, "LMBeta"}, {LP_LM_MIXTURE, "LMMixture", PERS, 50, "LMMixture"}, {LP_MOUSE_POS_BOX, "MousePosBox", !PERS, -1, "Mouse Position Box Indicator"}, {LP_NORMALIZATION, "Normalization", !PERS, 1 << 16, "Interval for child nodes"}, {LP_LINE_WIDTH, "LineWidth", PERS, 1, "Width to draw crosshair and mouse line"}, {LP_LM_WORD_ALPHA, "WordAlpha", PERS, 50, "Alpha value for word-based model"}, {LP_USER_LOG_LEVEL_MASK, "UserLogLevelMask", PERS, 0, "Controls level of user logging, 0 = none, 1 = short, 2 = detailed, 3 = both"}, {LP_ZOOMSTEPS, "Zoomsteps", PERS, 32, "Integerised ratio of zoom size for click/button mode, denom 64."}, {LP_B, "ButtonMenuBoxes", PERS, 4, "Number of boxes for button menu mode"}, {LP_S, "ButtonMenuSafety", PERS, 25, "Safety parameter for button mode, in percent."}, #ifdef TARGET_OS_IPHONE {LP_BUTTON_SCAN_TIME, "ButtonMenuScanTime", PERS, 600, "Scanning time in menu mode (0 = don't scan), in ms"}, #else {LP_BUTTON_SCAN_TIME, "ButtonMenuScanTime", PERS, 0, "Scanning time in menu mode (0 = don't scan), in ms"}, #endif {LP_R, "ButtonModeNonuniformity", PERS, 0, "Button mode box non-uniformity"}, {LP_RIGHTZOOM, "ButtonCompassModeRightZoom", PERS, 5120, "Zoomfactor (*1024) for compass mode"}, #if defined(WITH_MAEMO) || defined (TARGET_OS_IPHONE) {LP_NODE_BUDGET, "NodeBudget", PERS, 1000, "Target (min) number of node objects to maintain"}, #else {LP_NODE_BUDGET, "NodeBudget", PERS, 3000, "Target (min) number of node objects to maintain"}, #endif #ifdef WITH_MAEMO {LP_NONLINEAR_X, "NonLinearX", PERS, 0, "Nonlinear compression of X-axis (0 = none, higher = more extreme)"}, #else {LP_NONLINEAR_X, "NonLinearX", PERS, 5, "Nonlinear compression of X-axis (0 = none, higher = more extreme)"}, #endif {LP_BOOSTFACTOR, "BoostFactor", !PERS, 100, "Boost/brake factor (multiplied by 100)"}, {LP_AUTOSPEED_SENSITIVITY, "AutospeedSensitivity", PERS, 100, "Sensitivity of automatic speed control (percent)"}, {LP_SOCKET_PORT, "SocketPort", PERS, 20320, "UDP/TCP socket to use for network socket input"}, {LP_SOCKET_INPUT_X_MIN, "SocketInputXMinTimes1000", PERS, 0, "Bottom of range of X values expected from network input"}, {LP_SOCKET_INPUT_X_MAX, "SocketInputXMaxTimes1000", PERS, 1000, "Top of range of X values expected from network input"}, {LP_SOCKET_INPUT_Y_MIN, "SocketInputYMinTimes1000", PERS, 0, "Bottom of range of Y values expected from network input"}, {LP_SOCKET_INPUT_Y_MAX, "SocketInputYMaxTimes1000", PERS, 1000, "Top of range of Y values expected from network input"}, {LP_OX, "OX", PERS, 2048, "X coordinate of crosshair"}, {LP_OY, "OY", PERS, 2048, "Y coordinate of crosshair"}, {LP_MAX_Y, "MaxY", PERS, 4096, "Maximum Y coordinate"}, {LP_INPUT_FILTER, "InputFilterID", PERS, 3, "Module ID of input filter"}, {LP_CIRCLE_PERCENT, "CirclePercent", PERS, 10, "Percentage of nominal vertical range to use for radius of start circle"}, {LP_TWO_BUTTON_OFFSET, "TwoButtonOffset", PERS, 1638, "Offset for two button dynamic mode"}, {LP_HOLD_TIME, "HoldTime", PERS, 1000, "Time for which buttons must be held to count as long presses, in ms"}, {LP_MULTIPRESS_TIME, "MultipressTime", PERS, 1000, "Time in which multiple presses must occur, in ms"}, {LP_SLOW_START_TIME, "SlowStartTime", PERS, 1000, "Time over which slow start occurs"}, {LP_CONVERSION_ORDER, "ConversionOrder", PERS, 0, "Conversion ordering"}, {LP_CONVERSION_TYPE, "ConversionType", PERS, 0, "Conversion type"}, {LP_TWO_PUSH_OUTER, "TwoPushOuter", PERS, 1792, "Offset for one button dynamic mode outer marker"}, {LP_TWO_PUSH_UP, "TwoPushUp", PERS, 1536, "Offset to up marker in one button dynamic"}, {LP_TWO_PUSH_DOWN, "TwoPushDown", PERS, 1280, "Offset to down marker in one button dynamic"}, {LP_TWO_PUSH_TOLERANCE, "TwoPushTolerance", PERS, 100, "Tolerance of two-push-mode pushes, in ms"}, {LP_DYNAMIC_BUTTON_LAG, "DynamicButtonLag", PERS, 50, "Lag of pushes in dynamic button mode (ms)"}, {LP_STATIC1B_TIME, "Static1BTime", PERS, 2000, "Time for static-1B mode to scan from top to bottom (ms)"}, {LP_STATIC1B_ZOOM, "Static1BZoom", PERS, 8, "Zoom factor for static-1B mode"}, {LP_DEMO_SPRING, "DemoSpring", PERS, 100, "Springyness in Demo-mode"}, {LP_DEMO_NOISE_MEM, "DemoNoiseMem", PERS, 100, "Memory parameter for noise in Demo-mode"}, {LP_DEMO_NOISE_MAG, "DemoNoiseMag", PERS, 325, "Magnitude of noise in Demo-mode"}, {LP_MAXZOOM, "ClickMaxZoom", PERS, 200, "Maximum zoom possible in click mode (times 10)"}, {LP_DYNAMIC_SPEED_INC, "DynamicSpeedInc", PERS, 3, "%age by which dynamic mode auto speed control increases speed"}, {LP_DYNAMIC_SPEED_FREQ, "DynamicSpeedFreq", PERS, 10, "Seconds after which dynamic mode auto speed control increases speed"}, {LP_DYNAMIC_SPEED_DEC, "DynamicSpeedDec", PERS, 8, "%age by which dynamic mode auto speed control decreases speed on reverse"}, {LP_TAP_TIME, "TapTime", PERS, 200, "Max length of a stylus 'tap' rather than hold (ms)"}, #ifdef TARGET_OS_IPHONE {LP_MARGIN_WIDTH, "MarginWidth", PERS, 500, "Width of RHS margin (in Dasher co-ords)"}, #else {LP_MARGIN_WIDTH, "MarginWidth", PERS, 300, "Width of RHS margin (in Dasher co-ords)"}, #endif }; static sp_table stringparamtable[] = { {SP_ALPHABET_ID, "AlphabetID", PERS, "", "AlphabetID"}, {SP_ALPHABET_1, "Alphabet1", PERS, "", "Alphabet History 1"}, {SP_ALPHABET_2, "Alphabet2", PERS, "", "Alphabet History 2"}, {SP_ALPHABET_3, "Alphabet3", PERS, "", "Alphabet History 3"}, {SP_ALPHABET_4, "Alphabet4", PERS, "", "Alphabet History 4"}, {SP_COLOUR_ID, "ColourID", PERS, "", "ColourID"}, {SP_DEFAULT_COLOUR_ID, "DefaultColourID", !PERS, "", "Default Colour ID (Used for auto-colour mode)"}, {SP_DASHER_FONT, "DasherFont", PERS, "", "DasherFont"}, {SP_SYSTEM_LOC, "SystemLocation", !PERS, "sys_", "System Directory"}, {SP_USER_LOC, "UserLocation", !PERS, "usr_", "User Directory"}, {SP_GAME_TEXT_FILE, "GameTextFile", !PERS, "", "File with strings to practice writing"}, {SP_TRAIN_FILE, "TrainingFile", !PERS, "", "Training text for alphabet"}, {SP_SOCKET_INPUT_X_LABEL, "SocketInputXLabel", PERS, "x", "Label preceding X values for network input"}, {SP_SOCKET_INPUT_Y_LABEL, "SocketInputYLabel", PERS, "y", "Label preceding Y values for network input"}, #if defined(WITH_MAEMO) || defined(TARGET_OS_IPHONE) {SP_INPUT_FILTER, "InputFilter", PERS, "Stylus Control", "Input filter used to provide the current control mode"}, #else {SP_INPUT_FILTER, "InputFilter", PERS, "Normal Control", "Input filter used to provide the current control mode"}, #endif {SP_INPUT_DEVICE, "InputDevice", PERS, "Mouse Input", "Driver for the input device"}, {SP_BUTTON_0, "Button0", PERS, "", "Assignment to button 0"}, {SP_BUTTON_1, "Button1", PERS, "", "Assignment to button 1"}, {SP_BUTTON_2, "Button2", PERS, "", "Assignment to button 2"}, {SP_BUTTON_3, "Button3", PERS, "", "Assignment to button 3"}, {SP_BUTTON_4, "Button4", PERS, "", "Assignment to button 4"}, {SP_BUTTON_10, "Button10", PERS, "", "Assignment to button 10"}, {SP_JOYSTICK_DEVICE, "JoystickDevice", PERS, "/dev/input/js0", "Joystick device"}, #ifdef TARGET_OS_IPHONE {SP_CUSTOM_TILT, "CustomTiltParams", PERS, "(0.0,0.0,0.0) - (0.0,-1.0,0.0) / (-1.0,0.0,0.0)", "Custom tilt axes"}, {SP_VERTICAL_TILT, "VerticalTiltParams", PERS, "-0.1 - -0.9 / -0.4 - 0.4", "Limits of vertical tilting"}, #endif }; // This is the structure of each table that the settings will access // Everything is const except the current value of the setting struct bp_info { int key; std::string regName; bool persistent; bool value; bool defaultVal; std::string humanReadable; }; struct lp_info { int key; std::string regName; bool persistent; long value; long defaultVal; std::string humanReadable; }; struct sp_info { int key; std::string regName; bool persistent; std::string value; std::string defaultVal; std::string humanReadable; }; namespace Dasher { class CParamTables; } /// \ingroup Core /// \{ class Dasher::CParamTables { // These are the parameter tables that store everything public: bp_info BoolParamTable[NUM_OF_BPS]; lp_info LongParamTable[NUM_OF_LPS]; sp_info StringParamTable[NUM_OF_SPS]; public: CParamTables() { // Initialize all the tables with default values // and convert the char* to std::string in the object for(int ii = 0; ii < NUM_OF_BPS; ii++) { BoolParamTable[ii].key = boolparamtable[ii].key; BoolParamTable[ii].value = boolparamtable[ii].defaultValue; BoolParamTable[ii].defaultVal = boolparamtable[ii].defaultValue; BoolParamTable[ii].humanReadable = boolparamtable[ii].humanReadable; BoolParamTable[ii].persistent = boolparamtable[ii].persistent; BoolParamTable[ii].regName = boolparamtable[ii].regName; } for(int ij = 0; ij < NUM_OF_LPS; ij++) { LongParamTable[ij].key = longparamtable[ij].key; LongParamTable[ij].value = longparamtable[ij].defaultValue; LongParamTable[ij].defaultVal = longparamtable[ij].defaultValue; LongParamTable[ij].humanReadable = longparamtable[ij].humanReadable; LongParamTable[ij].persistent = longparamtable[ij].persistent; LongParamTable[ij].regName = longparamtable[ij].regName; } for(int ik = 0; ik < NUM_OF_SPS; ik++) { StringParamTable[ik].key = stringparamtable[ik].key; StringParamTable[ik].value = stringparamtable[ik].defaultValue; StringParamTable[ik].defaultVal = stringparamtable[ik].defaultValue; StringParamTable[ik].humanReadable = stringparamtable[ik].humanReadable; StringParamTable[ik].persistent = stringparamtable[ik].persistent; StringParamTable[ik].regName = stringparamtable[ik].regName; } }; /// \} }; #endif
rgee/HFOSS-Dasher
742e86903b44718875f2bad4065ec5cb4a260b90
Added string partitioning functions to GameModule
diff --git a/Src/DasherCore/GameModule.cpp b/Src/DasherCore/GameModule.cpp index e69de29..9b73984 100644 --- a/Src/DasherCore/GameModule.cpp +++ b/Src/DasherCore/GameModule.cpp @@ -0,0 +1,38 @@ +#include "GameModule.h" + +void CGameModule::HandleEvent(Dasher::CEvent *pEvent) { + switch(pEvent->m_iEventType) + { + case EV_EDIT: + switch(static_cast<CEditEvent*>(pEvent)->m_iEditType) + { + // Added a new character (Stepped one node forward) + case 0: + currentStringPos++; + pLastTypedNode = StringToNode(pEvent->m_sText); + break; + // Removed a character (Stepped one node back) + case 1: + break; + default: + break; + } + break; + default: + break; + + } + return; +} + +CDasherNode CGameModule::StringToNode(std::string sText) { + +} + +std::string CGameModule::GetTypedTarget() { + return m_sTargetString.substr(0, m_stCurrentStringPos - 1); +} + +std::string CGameModule::GetUntypedtarget() { + return m_sTargetString.substr(m_stCurrentStringPos); +} diff --git a/Src/DasherCore/GameModule.h b/Src/DasherCore/GameModule.h index 4980853..2c15a23 100644 --- a/Src/DasherCore/GameModule.h +++ b/Src/DasherCore/GameModule.h @@ -1,65 +1,92 @@ // GameModule.h #ifndef GAME_MODULE_H #define GAME_MODULE_H #include <string> using namespace std; #include "DasherModule.h" #include "DasherModel.h" #include "DasherNode.h" #include "DasherView.h" namespace Dasher { class CDasherInterfaceBase; } namespace Dasher { /** * This Dasher Module encapsulates all game mode logic. In game mode, users will be given * a target string to type as well as visual feedback for their progress and a helpful * arrow to guide them in the right path through the dasher model. * * This class handles logic and drawing code with respect to the above. */ class CGameModule : public CDasherModule { public: // I don't actually know what the type is supposed to be for this...it's not an input method or an input filter. // Maybe we should define a new one. I've labeled it 0 for now. - rgee CGameModule(Dasher::CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CDasherInterfaceBase *pInterface, ModuleID_t iID, const char *szName) : CDasherModule(pEventHandler, pSettingsStore, iID, 0, szName) + { m_pInterface = pInterface; } /** * Handle events from the event processing system * @param pEvent The event to be processed. */ void HandleEvent(Dasher::CEvent *pEvent); + /** + * Gets the typed portion of the target string + * @return The string that represents the current word(s) that have not been typed + */ + inline std::string GetTypedTarget(); + + /** + * Gets the portion of the target string that has yet to be completed + * @return The string that represents the current word(s) that have been typed + */ + inline std::string GetUntypedTarget(); + + inline void SetDasherModel(CDasherModel *pModel) { m_pModel = pModel; } + private: + /** + * Searches for the dasher node under the current root that represents the desired string + * @param text The string to search for + * @return The node representing the string parameter + */ + CDasherNode StringToNode(std::string sText) + /** * The last node the user typed. */ CDasherNode *pLastTypedNode; /** * The next node (character) the user must type. */ CDasherNode *pNextTargetNode; /** * The target string the user must type. */ - std::string targetString; + std::string m_sTargetString; /** * The current position in the string. * Stored as a size_t to easily use substrings to determine what's been typed and what hasn't. */ - size_t currentStringPos; + size_t m_stCurrentStringPos; + + /** + * The dasher model. + */ + CDasherModel *m_pModel; }; } #endif
rgee/HFOSS-Dasher
1bf05ae2dbb0308a33c9b277671cd9efb3ce0aa7
Added method declaration for DecorateView to GameModule.h
diff --git a/Src/DasherCore/GameModule.h b/Src/DasherCore/GameModule.h index 1d82437..48cf25a 100644 --- a/Src/DasherCore/GameModule.h +++ b/Src/DasherCore/GameModule.h @@ -1,61 +1,61 @@ // GameModule.h #ifndef GAME_MODULE_H #define GAME_MODULE_H #include <string> using namespace std; #include "DasherModule.h" #include "DasherModel.h" #include "DasherNode.h" #include "DasherView.h" namespace Dasher { class CDasherInterfaceBase; } namespace Dasher { /* * This Dasher Module encapsulates all game mode logic. In game mode, users will be given * a target string to type as well as visual feedback for their progress and a helpful * arrow to guide them in the right path through the dasher model. * * This class handles logic and drawing code with respect to the above. */ class CGameModule : public CDasherModule { - pulbic: + public: // I don't actually know what the type is supposed to be for this...it's not an input method or an input filter. // Maybe we should define a new one. I've labeled it 0 for now. - rgee CGameModule(Dasher::CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CDasherInterfaceBase *pInterface, ModuleID_t iID, const char *szName) : CDasherModule(pEventHandler, pSettingsStore, iID, 0, szName) - // TODO: Methods will go here, clearly. + private: // // The last node the user typed. // CDasherNode *pLastTypedNode; // // The next node the user must type // CDasherNode *pNextTargetNode; // // The current target string (That the user must type) // std::string targetString; // // The current position in the string. Stored as a size_t to easily use // substring to determine what's been typed and what hasn't. // size_t currentStringPos; }; } #endif
rgee/HFOSS-Dasher
b2e0ec91bf2acdf4eb10e3480d735858d4287743
Created CPP for GameModule and wrote event handler
diff --git a/Src/DasherCore/GameModule.cpp b/Src/DasherCore/GameModule.cpp new file mode 100644 index 0000000..e69de29 diff --git a/Src/DasherCore/GameModule.h b/Src/DasherCore/GameModule.h index 1d82437..fe9ca7a 100644 --- a/Src/DasherCore/GameModule.h +++ b/Src/DasherCore/GameModule.h @@ -1,61 +1,64 @@ // GameModule.h #ifndef GAME_MODULE_H #define GAME_MODULE_H #include <string> using namespace std; #include "DasherModule.h" #include "DasherModel.h" #include "DasherNode.h" #include "DasherView.h" namespace Dasher { class CDasherInterfaceBase; } namespace Dasher { -/* +/** * This Dasher Module encapsulates all game mode logic. In game mode, users will be given * a target string to type as well as visual feedback for their progress and a helpful * arrow to guide them in the right path through the dasher model. * * This class handles logic and drawing code with respect to the above. */ class CGameModule : public CDasherModule { pulbic: // I don't actually know what the type is supposed to be for this...it's not an input method or an input filter. // Maybe we should define a new one. I've labeled it 0 for now. - rgee CGameModule(Dasher::CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CDasherInterfaceBase *pInterface, ModuleID_t iID, const char *szName) : CDasherModule(pEventHandler, pSettingsStore, iID, 0, szName) - // TODO: Methods will go here, clearly. - + /** + * Handle events from the event processing system + * @param pEvent The event to be processed. + */ + void HandleEvent(Dasher::CEvent *pEvent); private: - // - // The last node the user typed. - // + /** + * The last node the user typed. + */ CDasherNode *pLastTypedNode; - // - // The next node the user must type - // + /** + * The next node (character) the user must type. + */ CDasherNode *pNextTargetNode; - - // - // The current target string (That the user must type) - // + + /** + * The target string the user must type. + */ std::string targetString; - // - // The current position in the string. Stored as a size_t to easily use - // substring to determine what's been typed and what hasn't. - // + /** + * The current position in the string. + * Stored as a size_t to easily use substrings to determine what's been typed and what hasn't. + */ size_t currentStringPos; }; } #endif
rgee/HFOSS-Dasher
6b0284660b423e06eb1b36dcb48b9a756995ab1f
Wrote skeleton for game mode module. COMPLETELY UNTESTED. DO NOT PULL. MAY NOT COMPILE UNTIL 6/15. I just pushed to my repo to save changes somewhere
diff --git a/Src/DasherCore/GameModule.h b/Src/DasherCore/GameModule.h new file mode 100644 index 0000000..1d82437 --- /dev/null +++ b/Src/DasherCore/GameModule.h @@ -0,0 +1,61 @@ +// GameModule.h + +#ifndef GAME_MODULE_H +#define GAME_MODULE_H + +#include <string> +using namespace std; + +#include "DasherModule.h" +#include "DasherModel.h" +#include "DasherNode.h" +#include "DasherView.h" + +namespace Dasher { + class CDasherInterfaceBase; +} + +namespace Dasher { + +/* + * This Dasher Module encapsulates all game mode logic. In game mode, users will be given + * a target string to type as well as visual feedback for their progress and a helpful + * arrow to guide them in the right path through the dasher model. + * + * This class handles logic and drawing code with respect to the above. + */ +class CGameModule : public CDasherModule { + pulbic: + // I don't actually know what the type is supposed to be for this...it's not an input method or an input filter. + // Maybe we should define a new one. I've labeled it 0 for now. - rgee + CGameModule(Dasher::CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CDasherInterfaceBase *pInterface, ModuleID_t iID, const char *szName) + : CDasherModule(pEventHandler, pSettingsStore, iID, 0, szName) + + // TODO: Methods will go here, clearly. + + private: + // + // The last node the user typed. + // + CDasherNode *pLastTypedNode; + + // + // The next node the user must type + // + CDasherNode *pNextTargetNode; + + // + // The current target string (That the user must type) + // + std::string targetString; + + // + // The current position in the string. Stored as a size_t to easily use + // substring to determine what's been typed and what hasn't. + // + size_t currentStringPos; +}; +} + + +#endif
rgee/HFOSS-Dasher
0b2c40efcab9aef6966496829e6e63fc711286c7
Fix 578d5f151ef0e705f4d52908e30439c20593aa21
diff --git a/Src/Gtk2/DasherControl.cpp b/Src/Gtk2/DasherControl.cpp index 96458e5..e743238 100644 --- a/Src/Gtk2/DasherControl.cpp +++ b/Src/Gtk2/DasherControl.cpp @@ -1,625 +1,625 @@ #include "../Common/Common.h" #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <cstring> #include <iostream> #include "DasherControl.h" #include "Timer.h" #include "../DasherCore/Event.h" #include "../DasherCore/ModuleManager.h" #include <fcntl.h> #include <gtk/gtk.h> #include <gdk/gdk.h> #include <gdk/gdkkeysyms.h> #include <sys/stat.h> #include <unistd.h> using namespace std; // 'Private' methods (only used in this file) extern "C" gint key_release_event(GtkWidget *widget, GdkEventKey *event, gpointer user_data); extern "C" gboolean button_press_event(GtkWidget *widget, GdkEventButton *event, gpointer data); extern "C" void realize_canvas(GtkWidget *widget, gpointer user_data); extern "C" gint canvas_configure_event(GtkWidget *widget, GdkEventConfigure *event, gpointer data); extern "C" gint key_press_event(GtkWidget *widget, GdkEventKey *event, gpointer data); extern "C" void canvas_destroy_event(GtkWidget *pWidget, gpointer pUserData); extern "C" gboolean canvas_focus_event(GtkWidget *widget, GdkEventFocus *event, gpointer data); extern "C" gint canvas_expose_event(GtkWidget *widget, GdkEventExpose *event, gpointer data); static bool g_iTimeoutID = 0; // CDasherControl class definitions CDasherControl::CDasherControl(GtkVBox *pVBox, GtkDasherControl *pDasherControl) { m_pPangoCache = NULL; m_pScreen = NULL; m_pDasherControl = pDasherControl; m_pVBox = GTK_WIDGET(pVBox); Realize(); // m_pKeyboardHelper = new CKeyboardHelper(this); // m_pKeyboardHelper->Grab(GetBoolParameter(BP_GLOBAL_KEYBOARD)); } void CDasherControl::CreateModules() { CDasherInterfaceBase::CreateModules(); //create default set first // Create locally cached copies of the mouse input objects, as we // need to pass coordinates to them from the timer callback m_pMouseInput = (CDasherMouseInput *) RegisterModule(new CDasherMouseInput(m_pEventHandler, m_pSettingsStore)); SetDefaultInputDevice(m_pMouseInput); m_p1DMouseInput = (CDasher1DMouseInput *)RegisterModule(new CDasher1DMouseInput(m_pEventHandler, m_pSettingsStore)); RegisterModule(new CSocketInput(m_pEventHandler, m_pSettingsStore)); #ifdef JOYSTICK RegisterModule(new CDasherJoystickInput(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CDasherJoystickInputDiscrete(m_pEventHandler, m_pSettingsStore, this)); #endif #ifdef TILT RegisterModule(new CDasherTiltInput(m_pEventHandler, m_pSettingsStore, this)); #endif } void CDasherControl::SetupUI() { m_pCanvas = gtk_drawing_area_new(); #if GTK_CHECK_VERSION (2,18,0) gtk_widget_set_can_focus(m_pCanvas, TRUE); #else GTK_WIDGET_SET_FLAGS(m_pCanvas, GTK_CAN_FOCUS); #endif gtk_widget_set_double_buffered(m_pCanvas, FALSE); GtkWidget *pFrame = gtk_frame_new(NULL); gtk_frame_set_shadow_type(GTK_FRAME(pFrame), GTK_SHADOW_IN); gtk_container_add(GTK_CONTAINER(pFrame), m_pCanvas); gtk_box_pack_start(GTK_BOX(m_pVBox), pFrame, TRUE, TRUE, 0); gtk_widget_show_all(GTK_WIDGET(m_pVBox)); // Connect callbacks - note that we need to implement the callbacks // as "C" style functions and pass this as user data so they can // call the object g_signal_connect(m_pCanvas, "button_press_event", G_CALLBACK(button_press_event), this); g_signal_connect(m_pCanvas, "button_release_event", G_CALLBACK(button_press_event), this); g_signal_connect_after(m_pCanvas, "realize", G_CALLBACK(realize_canvas), this); g_signal_connect(m_pCanvas, "configure_event", G_CALLBACK(canvas_configure_event), this); g_signal_connect(m_pCanvas, "destroy", G_CALLBACK(canvas_destroy_event), this); g_signal_connect(m_pCanvas, "key-release-event", G_CALLBACK(key_release_event), this); g_signal_connect(m_pCanvas, "key_press_event", G_CALLBACK(key_press_event), this); g_signal_connect(m_pCanvas, "focus_in_event", G_CALLBACK(canvas_focus_event), this); g_signal_connect(m_pCanvas, "expose_event", G_CALLBACK(canvas_expose_event), this); // Create the Pango cache // TODO: Use system defaults? if(GetStringParameter(SP_DASHER_FONT) == "") SetStringParameter(SP_DASHER_FONT, "Sans 10"); m_pPangoCache = new CPangoCache(GetStringParameter(SP_DASHER_FONT)); } void CDasherControl::SetupPaths() { char *home_dir; char *user_data_dir; const char *system_data_dir; home_dir = getenv("HOME"); user_data_dir = new char[strlen(home_dir) + 10]; sprintf(user_data_dir, "%s/.dasher/", home_dir); mkdir(user_data_dir, S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); // PROGDATA is provided by the makefile system_data_dir = PROGDATA "/"; SetStringParameter(SP_SYSTEM_LOC, system_data_dir); SetStringParameter(SP_USER_LOC, user_data_dir); delete[] user_data_dir; } void CDasherControl::CreateSettingsStore() { m_pSettingsStore = new CGnomeSettingsStore(m_pEventHandler); } void CDasherControl::ScanAlphabetFiles(std::vector<std::string> &vFileList) { GDir *directory; G_CONST_RETURN gchar *filename; GPatternSpec *alphabetglob; alphabetglob = g_pattern_spec_new("alphabet*xml"); directory = g_dir_open(GetStringParameter(SP_SYSTEM_LOC).c_str(), 0, NULL); if(directory) { while((filename = g_dir_read_name(directory))) { if(g_pattern_match_string(alphabetglob, filename)) vFileList.push_back(filename); } g_dir_close(directory); } directory = g_dir_open(GetStringParameter(SP_USER_LOC).c_str(), 0, NULL); if(directory) { while((filename = g_dir_read_name(directory))) { if(g_pattern_match_string(alphabetglob, filename)) vFileList.push_back(filename); } g_dir_close(directory); } g_pattern_spec_free(alphabetglob); } void CDasherControl::ScanColourFiles(std::vector<std::string> &vFileList) { GDir *directory; G_CONST_RETURN gchar *filename; GPatternSpec *colourglob; colourglob = g_pattern_spec_new("colour*xml"); directory = g_dir_open(GetStringParameter(SP_SYSTEM_LOC).c_str(), 0, NULL); if(directory) { while((filename = g_dir_read_name(directory))) { if(g_pattern_match_string(colourglob, filename)) vFileList.push_back(filename); } g_dir_close(directory); } directory = g_dir_open(GetStringParameter(SP_USER_LOC).c_str(), 0, NULL); if(directory) { while((filename = g_dir_read_name(directory))) { if(g_pattern_match_string(colourglob, filename)) vFileList.push_back(filename); } g_dir_close(directory); } g_pattern_spec_free(colourglob); } CDasherControl::~CDasherControl() { if(m_pMouseInput) { m_pMouseInput = NULL; } if(m_p1DMouseInput) { m_p1DMouseInput = NULL; } if(m_pPangoCache) { delete m_pPangoCache; m_pPangoCache = NULL; } // if(m_pKeyboardHelper) { // delete m_pKeyboardHelper; // m_pKeyboardHelper = 0; // } } bool CDasherControl::FocusEvent(GtkWidget *pWidget, GdkEventFocus *pEvent) { if((pEvent->type == GDK_FOCUS_CHANGE) && (pEvent->in)) { GdkEventFocus *focusEvent = (GdkEventFocus *) g_malloc(sizeof(GdkEventFocus)); gboolean *returnType; focusEvent->type = GDK_FOCUS_CHANGE; focusEvent->window = (GdkWindow *) m_pDasherControl; focusEvent->send_event = FALSE; focusEvent->in = TRUE; g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "focus_in_event", GTK_WIDGET(m_pDasherControl), focusEvent, NULL, &returnType); } return true; } void CDasherControl::SetFocus() { gtk_widget_grab_focus(m_pCanvas); } void CDasherControl::GameMessageOut(int message, const void* messagedata) { gtk_dasher_control_game_messageout(m_pDasherControl, message, messagedata); } GArray *CDasherControl::GetAllowedValues(int iParameter) { // Glib version of the STL based core function GArray *pRetVal(g_array_new(false, false, sizeof(gchar *))); std::vector < std::string > vList; GetPermittedValues(iParameter, vList); for(std::vector < std::string >::iterator it(vList.begin()); it != vList.end(); ++it) { // For internal glib reasons we need to make a variable and then // pass - we can't use the iterator directly const char *pTemp(it->c_str()); char *pTempNew = new char[strlen(pTemp) + 1]; strcpy(pTempNew, pTemp); g_array_append_val(pRetVal, pTempNew); } return pRetVal; } void CDasherControl::RealizeCanvas(GtkWidget *pWidget) { // TODO: Pointless function - call directly from C callback. #ifdef DEBUG std::cout << "RealizeCanvas()" << std::endl; #endif OnUIRealised(); } void CDasherControl::StartTimer() { // Start the timer loops as everything is set up. // Aim for 40 frames per second, computers are getting faster. if(g_iTimeoutID == 0) { g_iTimeoutID = g_timeout_add_full(G_PRIORITY_DEFAULT_IDLE, 25, timer_callback, this, NULL); // TODO: Reimplement this (or at least reimplement some kind of status reporting) //g_timeout_add_full(G_PRIORITY_DEFAULT_IDLE, 5000, long_timer_callback, this, NULL); } } void CDasherControl::ShutdownTimer() { // TODO: Figure out how to implement this - at the moment it's done // through a return value from the timer callback, but it would be // nicer to prevent any further calls as soon as the shutdown signal // has been receieved. } int CDasherControl::CanvasConfigureEvent() { GtkAllocation a; #if GTK_CHECK_VERSION (2,18,0) gtk_widget_get_allocation(m_pCanvas, &a); #else - a.width = m_pCanvas->width; - a.height = m_pCanvas->height; + a.width = m_pCanvas->allocation.width; + a.height = m_pCanvas->allocation.height; #endif if(m_pScreen != NULL) delete m_pScreen; m_pScreen = new CCanvas(m_pCanvas, m_pPangoCache, a.width, a.height); ChangeScreen(m_pScreen); return 0; } void CDasherControl::ExternalEventHandler(Dasher::CEvent *pEvent) { // Convert events coming from the core to Glib signals. if(pEvent->m_iEventType == EV_PARAM_NOTIFY) { Dasher::CParameterNotificationEvent * pEvt(static_cast < Dasher::CParameterNotificationEvent * >(pEvent)); HandleParameterNotification(pEvt->m_iParameter); g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_changed", pEvt->m_iParameter); } else if(pEvent->m_iEventType == EV_EDIT) { CEditEvent *pEditEvent(static_cast < CEditEvent * >(pEvent)); if(pEditEvent->m_iEditType == 1) { // Insert event g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_edit_insert", pEditEvent->m_sText.c_str(), pEditEvent->m_iOffset); } else if(pEditEvent->m_iEditType == 2) { // Delete event g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_edit_delete", pEditEvent->m_sText.c_str(), pEditEvent->m_iOffset); } else if(pEditEvent->m_iEditType == 10) { g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_edit_convert"); } else if(pEditEvent->m_iEditType == 11) { g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_edit_protect"); } } else if(pEvent->m_iEventType == EV_EDIT_CONTEXT) { CEditContextEvent *pEditContextEvent(static_cast < CEditContextEvent * >(pEvent)); g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_context_request", pEditContextEvent->m_iOffset, pEditContextEvent->m_iLength); } else if(pEvent->m_iEventType == EV_START) { g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_start"); } else if(pEvent->m_iEventType == EV_STOP) { g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_stop"); } else if(pEvent->m_iEventType == EV_CONTROL) { CControlEvent *pControlEvent(static_cast < CControlEvent * >(pEvent)); g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_control", pControlEvent->m_iID); } else if(pEvent->m_iEventType == EV_LOCK) { CLockEvent *pLockEvent(static_cast<CLockEvent *>(pEvent)); DasherLockInfo sInfo; sInfo.szMessage = pLockEvent->m_strMessage.c_str(); sInfo.bLock = pLockEvent->m_bLock; sInfo.iPercent = pLockEvent->m_iPercent; g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_lock_info", &sInfo); } else if(pEvent->m_iEventType == EV_MESSAGE) { CMessageEvent *pMessageEvent(static_cast<CMessageEvent *>(pEvent)); DasherMessageInfo sInfo; sInfo.szMessage = pMessageEvent->m_strMessage.c_str(); sInfo.iID = pMessageEvent->m_iID; sInfo.iType = pMessageEvent->m_iType; g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_message", &sInfo); } else if(pEvent->m_iEventType == EV_COMMAND) { CCommandEvent *pCommandEvent(static_cast<CCommandEvent *>(pEvent)); g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_command", pCommandEvent->m_strCommand.c_str()); } }; void CDasherControl::WriteTrainFile(const std::string &strNewText) { if(strNewText.length() == 0) return; std::string strFilename(GetStringParameter(SP_USER_LOC) + GetStringParameter(SP_TRAIN_FILE)); int fd=open(strFilename.c_str(),O_CREAT|O_WRONLY|O_APPEND,S_IRUSR|S_IWUSR); write(fd,strNewText.c_str(),strNewText.length()); close(fd); } // TODO: Sort these methods out void CDasherControl::ExternalKeyDown(int iKeyVal) { // if(m_pKeyboardHelper) { // int iButtonID(m_pKeyboardHelper->ConvertKeycode(iKeyVal)); // if(iButtonID != -1) // KeyDown(get_time(), iButtonID); // } KeyDown(get_time(), iKeyVal); } void CDasherControl::ExternalKeyUp(int iKeyVal) { // if(m_pKeyboardHelper) { // int iButtonID(m_pKeyboardHelper->ConvertKeycode(iKeyVal)); // if(iButtonID != -1) // KeyUp(get_time(), iButtonID); // } KeyUp(get_time(), iKeyVal); } void CDasherControl::HandleParameterNotification(int iParameter) { switch(iParameter) { case SP_DASHER_FONT: if(m_pPangoCache) { m_pPangoCache->ChangeFont(GetStringParameter(SP_DASHER_FONT)); ScheduleRedraw(); } break; case BP_GLOBAL_KEYBOARD: // TODO: reimplement // if(m_pKeyboardHelper) // m_pKeyboardHelper->Grab(GetBoolParameter(BP_GLOBAL_KEYBOARD)); break; } } int CDasherControl::TimerEvent() { int x, y; #if GTK_CHECK_VERSION (2,14,0) gdk_window_get_pointer(gtk_widget_get_window(m_pCanvas), &x, &y, NULL); #else gdk_window_get_pointer(m_pCanvas->window, &x, &y, NULL); #endif m_pMouseInput->SetCoordinates(x, y); gdk_window_get_pointer(gdk_get_default_root_window(), &x, &y, NULL); int iRootWidth; int iRootHeight; gdk_drawable_get_size(gdk_get_default_root_window(), &iRootWidth, &iRootHeight); if(GetLongParameter(LP_YSCALE) < 10) SetLongParameter(LP_YSCALE, 10); y = (y - iRootHeight / 2); m_p1DMouseInput->SetCoordinates(y, GetLongParameter(LP_YSCALE)); NewFrame(get_time(), false); // Update our UserLog object about the current mouse position CUserLogBase* pUserLog = GetUserLogPtr(); if (pUserLog != NULL) { // We want current canvas and window coordinates so normalization // is done properly with respect to the canvas. GdkRectangle sWindowRect; GdkRectangle sCanvasRect; #if GTK_CHECK_VERSION (2,14,0) gdk_window_get_frame_extents(gtk_widget_get_window(m_pCanvas), &sWindowRect); #else gdk_window_get_frame_extents(m_pCanvas->window, &sWindowRect); #endif pUserLog->AddWindowSize(sWindowRect.y, sWindowRect.x, sWindowRect.y + sWindowRect.height, sWindowRect.x + sWindowRect.width); if (m_pScreen != NULL) { if (m_pScreen->GetCanvasSize(&sCanvasRect)) pUserLog->AddCanvasSize(sCanvasRect.y, sCanvasRect.x, sCanvasRect.y + sCanvasRect.height, sCanvasRect.x + sCanvasRect.width); } int iMouseX = 0; int iMouseY = 0; gdk_window_get_pointer(NULL, &iMouseX, &iMouseY, NULL); // TODO: This sort of thing shouldn't be in specialised methods, move into base class somewhere pUserLog->AddMouseLocationNormalized(iMouseX, iMouseY, true, GetNats()); } return 1; // See CVS for code which used to be here } int CDasherControl::LongTimerEvent() { // std::cout << "Framerate: " << GetFramerate() << std::endl; // std::cout << "Render count: " << GetRenderCount() << std::endl; return 1; } gboolean CDasherControl::ExposeEvent() { NewFrame(get_time(), true); return 0; } gboolean CDasherControl::ButtonPressEvent(GdkEventButton *event) { // Take the focus if we click on the canvas // GdkEventFocus *focusEvent = (GdkEventFocus *) g_malloc(sizeof(GdkEventFocus)); // gboolean *returnType; // focusEvent->type = GDK_FOCUS_CHANGE; // focusEvent->window = (GdkWindow *) m_pCanvas; // focusEvent->send_event = FALSE; // focusEvent->in = TRUE; // gtk_widget_grab_focus(GTK_WIDGET(m_pCanvas)); // g_signal_emit_by_name(GTK_OBJECT(m_pCanvas), "focus_in_event", GTK_WIDGET(m_pCanvas), focusEvent, NULL, &returnType); // No - don't take the focus - give it to the text area instead if(event->type == GDK_BUTTON_PRESS) HandleClickDown(get_time(), (int)event->x, (int)event->y); else if(event->type == GDK_BUTTON_RELEASE) HandleClickUp(get_time(), (int)event->x, (int)event->y); return false; } gint CDasherControl::KeyReleaseEvent(GdkEventKey *event) { // TODO: This is seriously flawed - the semantics of of X11 Keyboard // events mean the there's no guarantee that key up/down events will // be received in pairs. if((event->keyval == GDK_Shift_L) || (event->keyval == GDK_Shift_R)) { // if(event->state & GDK_CONTROL_MASK) // SetLongParameter(LP_BOOSTFACTOR, 25); // else // SetLongParameter(LP_BOOSTFACTOR, 100); } else if((event->keyval == GDK_Control_L) || (event->keyval == GDK_Control_R)) { // if(event->state & GDK_SHIFT_MASK) // SetLongParameter(LP_BOOSTFACTOR, 175); // else // SetLongParameter(LP_BOOSTFACTOR, 100); } else { // if(m_pKeyboardHelper) { // int iKeyVal(m_pKeyboardHelper->ConvertKeycode(event->keyval)); // if(iKeyVal != -1) // KeyUp(get_time(), iKeyVal); // } } return 0; } gint CDasherControl::KeyPressEvent(GdkEventKey *event) { // if((event->keyval == GDK_Shift_L) || (event->keyval == GDK_Shift_R)) // SetLongParameter(LP_BOOSTFACTOR, 175); // else if((event->keyval == GDK_Control_L) || (event->keyval == GDK_Control_R)) // SetLongParameter(LP_BOOSTFACTOR, 25); // else { // if(m_pKeyboardHelper) { // int iKeyVal(m_pKeyboardHelper->ConvertKeycode(event->keyval)); // if(iKeyVal != -1) // KeyDown(get_time(), iKeyVal); // } // } return 0; } void CDasherControl::CanvasDestroyEvent() { // Delete the screen if(m_pScreen != NULL) { delete m_pScreen; m_pScreen = NULL; } } // Tell the logging object that a new user trial is starting. void CDasherControl::UserLogNewTrial() { CUserLogBase* pUserLog = GetUserLogPtr(); if (pUserLog != NULL) { pUserLog->NewTrial(); } } int CDasherControl::GetFileSize(const std::string &strFileName) { struct stat sStatInfo; if(!stat(strFileName.c_str(), &sStatInfo)) return sStatInfo.st_size; else return 0; } // "C" style callbacks - these are here just because it's not possible // (or at least not easy) to connect a callback directly to a C++ // method, so we pass a pointer to th object in the user_data field // and use a wrapper function. Please do not put any functional code // here. extern "C" void realize_canvas(GtkWidget *widget, gpointer user_data) { static_cast < CDasherControl * >(user_data)->RealizeCanvas(widget); } extern "C" gboolean button_press_event(GtkWidget *widget, GdkEventButton *event, gpointer data) { return static_cast < CDasherControl * >(data)->ButtonPressEvent(event); } extern "C" gint key_press_event(GtkWidget *widget, GdkEventKey *event, gpointer data) { return static_cast < CDasherControl * >(data)->KeyPressEvent(event); } extern "C" gint canvas_configure_event(GtkWidget *widget, GdkEventConfigure *event, gpointer data) { return static_cast < CDasherControl * >(data)->CanvasConfigureEvent(); } extern "C" void canvas_destroy_event(GtkWidget *pWidget, gpointer pUserData) { static_cast<CDasherControl*>(pUserData)->CanvasDestroyEvent(); } extern "C" gint key_release_event(GtkWidget *pWidget, GdkEventKey *event, gpointer pUserData) { return static_cast<CDasherControl*>(pUserData)->KeyReleaseEvent(event); } extern "C" gboolean canvas_focus_event(GtkWidget *widget, GdkEventFocus *event, gpointer data) { return static_cast < CDasherControl * >(data)->FocusEvent(widget, event); } extern "C" gint canvas_expose_event(GtkWidget *widget, GdkEventExpose *event, gpointer data) { return ((CDasherControl*)data)->ExposeEvent(); }
rgee/HFOSS-Dasher
5050cc867ec3451724218d0f6a98008e6c670144
Make CDasherNode::m_iOffset private, rather than protected
diff --git a/Src/DasherCore/AlphabetManager.cpp b/Src/DasherCore/AlphabetManager.cpp index a39c35d..bd5ce3e 100644 --- a/Src/DasherCore/AlphabetManager.cpp +++ b/Src/DasherCore/AlphabetManager.cpp @@ -1,461 +1,461 @@ // AlphabetManager.cpp // // Copyright (c) 2007 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" #include "AlphabetManager.h" #include "ConversionManager.h" #include "DasherInterfaceBase.h" #include "DasherNode.h" #include "Event.h" #include "EventHandler.h" #include "NodeCreationManager.h" #include <vector> #include <sstream> #include <iostream> using namespace Dasher; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG_MEMLEAKS #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif CAlphabetManager::CAlphabetManager(CDasherInterfaceBase *pInterface, CNodeCreationManager *pNCManager, CLanguageModel *pLanguageModel) : m_pLanguageModel(pLanguageModel), m_pNCManager(pNCManager) { m_pInterface = pInterface; m_iLearnContext = m_pLanguageModel->CreateEmptyContext(); } CAlphabetManager::CAlphNode::CAlphNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, int iColour, const string &strDisplayText, CAlphabetManager *pMgr) : CDasherNode(pParent, iOffset, iLbnd, iHbnd, iColour, strDisplayText), m_pProbInfo(NULL), m_pMgr(pMgr) { }; CAlphabetManager::CSymbolNode::CSymbolNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, CAlphabetManager *pMgr, symbol _iSymbol) : CAlphNode(pParent, iOffset, iLbnd, iHbnd, pMgr->m_pNCManager->GetAlphabet()->GetColour(_iSymbol, iOffset%2), pMgr->m_pNCManager->GetAlphabet()->GetDisplayText(_iSymbol), pMgr), iSymbol(_iSymbol) { }; CAlphabetManager::CSymbolNode::CSymbolNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, int iColour, const string &strDisplayText, CAlphabetManager *pMgr, symbol _iSymbol) : CAlphNode(pParent, iOffset, iLbnd, iHbnd, iColour, strDisplayText, pMgr), iSymbol(_iSymbol) { }; CAlphabetManager::CGroupNode::CGroupNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, CAlphabetManager *pMgr, SGroupInfo *pGroup) : CAlphNode(pParent, iOffset, iLbnd, iHbnd, pGroup ? (pGroup->bVisible ? pGroup->iColour : pParent->getColour()) : pMgr->m_pNCManager->GetAlphabet()->GetColour(0, iOffset%2), pGroup ? pGroup->strLabel : "", pMgr), m_pGroup(pGroup) { }; CAlphabetManager::CSymbolNode *CAlphabetManager::makeSymbol(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, symbol iSymbol) { return new CSymbolNode(pParent, iOffset, iLbnd, iHbnd, this, iSymbol); } CAlphabetManager::CGroupNode *CAlphabetManager::makeGroup(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, SGroupInfo *pGroup) { return new CGroupNode(pParent, iOffset, iLbnd, iHbnd, this, pGroup); } CAlphabetManager::CAlphNode *CAlphabetManager::GetRoot(CDasherNode *pParent, unsigned int iLower, unsigned int iUpper, bool bEnteredLast, int iOffset) { int iNewOffset(max(-1,iOffset-1)); std::vector<symbol> vContextSymbols; // TODO: make the LM get the context, rather than force it to fix max context length as an int int iStart = max(0, iNewOffset - m_pLanguageModel->GetContextLength()); if(pParent) { pParent->GetContext(m_pInterface, vContextSymbols, iStart, iNewOffset+1 - iStart); } else { std::string strContext = (iNewOffset == -1) ? m_pNCManager->GetAlphabet()->GetDefaultContext() : m_pInterface->GetContext(iStart, iNewOffset+1 - iStart); m_pNCManager->GetAlphabet()->GetSymbols(vContextSymbols, strContext); } CAlphNode *pNewNode; CLanguageModel::Context iContext = m_pLanguageModel->CreateEmptyContext(); std::vector<symbol>::iterator it = vContextSymbols.end(); while (it!=vContextSymbols.begin()) { if (*(--it) == 0) { //found an impossible symbol! start after it ++it; break; } } if (it == vContextSymbols.end()) { //previous character was not in the alphabet! //can't construct a node "responsible" for entering it bEnteredLast=false; //instead, Create a node as if we were starting a new sentence... vContextSymbols.clear(); m_pNCManager->GetAlphabet()->GetSymbols(vContextSymbols, m_pNCManager->GetAlphabet()->GetDefaultContext()); it = vContextSymbols.begin(); //TODO: What it the default context somehow contains symbols not in the alphabet? } //enter the symbols we could make sense of, into the LM context... while (it != vContextSymbols.end()) { m_pLanguageModel->EnterSymbol(iContext, *(it++)); } if(!bEnteredLast) { pNewNode = makeGroup(pParent, iNewOffset, iLower, iUpper, NULL); } else { const symbol iSymbol(vContextSymbols[vContextSymbols.size() - 1]); pNewNode = makeSymbol(pParent, iNewOffset, iLower, iUpper, iSymbol); //if the new node is not child of an existing node, then it // represents a symbol that's already happened - so we're either // going backwards (rebuildParent) or creating a new root after a language change DASHER_ASSERT (!pParent); pNewNode->SetFlag(NF_SEEN, true); } pNewNode->iContext = iContext; return pNewNode; } bool CAlphabetManager::CSymbolNode::GameSearchNode(string strTargetUtf8Char) { if (m_pMgr->m_pNCManager->GetAlphabet()->GetText(iSymbol) == strTargetUtf8Char) { SetFlag(NF_GAME, true); return true; } return false; } bool CAlphabetManager::CGroupNode::GameSearchNode(string strTargetUtf8Char) { if (GameSearchChildren(strTargetUtf8Char)) { SetFlag(NF_GAME, true); return true; } return false; } CLanguageModel::Context CAlphabetManager::CAlphNode::CloneAlphContext(CLanguageModel *pLanguageModel) { if (iContext) return pLanguageModel->CloneContext(iContext); return CDasherNode::CloneAlphContext(pLanguageModel); } void CAlphabetManager::CSymbolNode::GetContext(CDasherInterfaceBase *pInterface, vector<symbol> &vContextSymbols, int iOffset, int iLength) { - if (!GetFlag(NF_SEEN) && iOffset+iLength-1 == m_iOffset) { + if (!GetFlag(NF_SEEN) && iOffset+iLength-1 == offset()) { if (iLength > 1) Parent()->GetContext(pInterface, vContextSymbols, iOffset, iLength-1); vContextSymbols.push_back(iSymbol); } else { CDasherNode::GetContext(pInterface, vContextSymbols, iOffset, iLength); } } symbol CAlphabetManager::CSymbolNode::GetAlphSymbol() { return iSymbol; } void CAlphabetManager::CSymbolNode::PopulateChildren() { m_pMgr->IterateChildGroups(this, NULL, NULL); } int CAlphabetManager::CAlphNode::ExpectedNumChildren() { return m_pMgr->m_pNCManager->GetAlphabet()->iNumChildNodes; } std::vector<unsigned int> *CAlphabetManager::CAlphNode::GetProbInfo() { if (!m_pProbInfo) { m_pProbInfo = new std::vector<unsigned int>(); m_pMgr->m_pNCManager->GetProbs(iContext, *m_pProbInfo, m_pMgr->m_pNCManager->GetLongParameter(LP_NORMALIZATION)); // work out cumulative probs in place for(unsigned int i = 1; i < m_pProbInfo->size(); i++) { (*m_pProbInfo)[i] += (*m_pProbInfo)[i - 1]; } } return m_pProbInfo; } std::vector<unsigned int> *CAlphabetManager::CGroupNode::GetProbInfo() { if (m_pGroup && Parent() && Parent()->mgr() == mgr()) { DASHER_ASSERT(Parent()->offset() == offset()); return (static_cast<CAlphNode *>(Parent()))->GetProbInfo(); } //nope, no usable parent. compute here... return CAlphNode::GetProbInfo(); } void CAlphabetManager::CGroupNode::PopulateChildren() { m_pMgr->IterateChildGroups(this, m_pGroup, NULL); } int CAlphabetManager::CGroupNode::ExpectedNumChildren() { return (m_pGroup) ? m_pGroup->iNumChildNodes : CAlphNode::ExpectedNumChildren(); } CAlphabetManager::CGroupNode *CAlphabetManager::CreateGroupNode(CAlphNode *pParent, SGroupInfo *pInfo, unsigned int iLbnd, unsigned int iHbnd) { // When creating a group node... // ...the offset is the same as the parent... CGroupNode *pNewNode = makeGroup(pParent, pParent->offset(), iLbnd, iHbnd, pInfo); //...as is the context! pNewNode->iContext = m_pLanguageModel->CloneContext(pParent->iContext); return pNewNode; } CAlphabetManager::CGroupNode *CAlphabetManager::CGroupNode::RebuildGroup(CAlphNode *pParent, SGroupInfo *pInfo, unsigned int iLbnd, unsigned int iHbnd) { if (pInfo == m_pGroup) { SetRange(iLbnd, iHbnd); SetParent(pParent); //offset doesn't increase for groups... DASHER_ASSERT (offset() == pParent->offset()); return this; } CGroupNode *pRet=m_pMgr->CreateGroupNode(pParent, pInfo, iLbnd, iHbnd); if (pInfo->iStart <= m_pGroup->iStart && pInfo->iEnd >= m_pGroup->iEnd) { //created group node should contain this one m_pMgr->IterateChildGroups(pRet,pInfo,this); } return pRet; } CAlphabetManager::CGroupNode *CAlphabetManager::CSymbolNode::RebuildGroup(CAlphNode *pParent, SGroupInfo *pInfo, unsigned int iLbnd, unsigned int iHbnd) { CGroupNode *pRet=m_pMgr->CreateGroupNode(pParent, pInfo, iLbnd, iHbnd); if (pInfo->iStart <= iSymbol && pInfo->iEnd > iSymbol) { m_pMgr->IterateChildGroups(pRet, pInfo, this); } return pRet; } CLanguageModel::Context CAlphabetManager::CreateSymbolContext(CAlphNode *pParent, symbol iSymbol) { CLanguageModel::Context iContext = m_pLanguageModel->CloneContext(pParent->iContext); m_pLanguageModel->EnterSymbol(iContext, iSymbol); // TODO: Don't use symbols? return iContext; } CDasherNode *CAlphabetManager::CreateSymbolNode(CAlphNode *pParent, symbol iSymbol, unsigned int iLbnd, unsigned int iHbnd) { CDasherNode *pNewNode = NULL; //Does not invoke conversion node // TODO: Better way of specifying alternate roots // TODO: Need to fix fact that this is created even when control mode is switched off if(iSymbol == m_pNCManager->GetAlphabet()->GetControlSymbol()) { //ACL setting offset as one more than parent for consistency with "proper" symbol nodes... pNewNode = m_pNCManager->GetCtrlRoot(pParent, iLbnd, iHbnd, pParent->offset()+1); #ifdef _WIN32_WCE //no control manager - but (TODO!) we still try to create (0-size!) control node... DASHER_ASSERT(!pNewNode); // For now, just hack it so we get a normal root node here pNewNode = m_pNCManager->GetAlphRoot(pParent, iLbnd, iHbnd, false, pParent->m_iOffset+1); #else DASHER_ASSERT(pNewNode); #endif } else if(iSymbol == m_pNCManager->GetAlphabet()->GetStartConversionSymbol()) { // else if(iSymbol == m_pNCManager->GetSpaceSymbol()) { //ACL setting m_iOffset+1 for consistency with "proper" symbol nodes... pNewNode = m_pNCManager->GetConvRoot(pParent, iLbnd, iHbnd, pParent->offset()+1); } else { // TODO: Exceptions / error handling in general CAlphNode *pAlphNode; pNewNode = pAlphNode = makeSymbol(pParent, pParent->offset()+1, iLbnd, iHbnd, iSymbol); // std::stringstream ssLabel; // ssLabel << m_pNCManager->GetAlphabet()->GetDisplayText(iSymbol) << ": " << pNewNode; // pDisplayInfo->strDisplayText = ssLabel.str(); pAlphNode->iContext = CreateSymbolContext(pParent, iSymbol); } return pNewNode; } CDasherNode *CAlphabetManager::CSymbolNode::RebuildSymbol(CAlphNode *pParent, symbol iSymbol, unsigned int iLbnd, unsigned int iHbnd) { if(iSymbol == this->iSymbol) { SetRange(iLbnd, iHbnd); SetParent(pParent); DASHER_ASSERT(offset() == pParent->offset() + 1); return this; } return m_pMgr->CreateSymbolNode(pParent, iSymbol, iLbnd, iHbnd); } CDasherNode *CAlphabetManager::CGroupNode::RebuildSymbol(CAlphNode *pParent, symbol iSymbol, unsigned int iLbnd, unsigned int iHbnd) { return m_pMgr->CreateSymbolNode(pParent, iSymbol, iLbnd, iHbnd); } void CAlphabetManager::IterateChildGroups(CAlphNode *pParent, SGroupInfo *pParentGroup, CAlphNode *buildAround) { std::vector<unsigned int> *pCProb(pParent->GetProbInfo()); const int iMin(pParentGroup ? pParentGroup->iStart : 1); const int iMax(pParentGroup ? pParentGroup->iEnd : pCProb->size()); // TODO: Think through alphabet file formats etc. to make this class easier. // TODO: Throw a warning if parent node already has children // Create child nodes and add them int i(iMin); //lowest index of child which we haven't yet added SGroupInfo *pCurrentNode(pParentGroup ? pParentGroup->pChild : m_pNCManager->GetAlphabet()->m_pBaseGroup); // The SGroupInfo structure has something like linked list behaviour // Each SGroupInfo contains a pNext, a pointer to a sibling group info while (i < iMax) { CDasherNode *pNewChild; bool bSymbol = !pCurrentNode //gone past last subgroup || i < pCurrentNode->iStart; //not reached next subgroup const int iStart=i, iEnd = (bSymbol) ? i+1 : pCurrentNode->iEnd; //uint64 is platform-dependently #defined in DasherTypes.h as an (unsigned) 64-bit int ("__int64" or "long long int") unsigned int iLbnd = (((*pCProb)[iStart-1] - (*pCProb)[iMin-1]) * (uint64)(m_pNCManager->GetLongParameter(LP_NORMALIZATION))) / ((*pCProb)[iMax-1] - (*pCProb)[iMin-1]); unsigned int iHbnd = (((*pCProb)[iEnd-1] - (*pCProb)[iMin-1]) * (uint64)(m_pNCManager->GetLongParameter(LP_NORMALIZATION))) / ((*pCProb)[iMax-1] - (*pCProb)[iMin-1]); //loop for eliding groups with single children (see below). // Variables store necessary properties of any elided groups: std::string groupPrefix=""; int iOverrideColour=-1; SGroupInfo *pInner=pCurrentNode; while (true) { if (bSymbol) { pNewChild = (buildAround) ? buildAround->RebuildSymbol(pParent, i, iLbnd, iHbnd) : CreateSymbolNode(pParent, i, iLbnd, iHbnd); i++; //make one symbol at a time - move onto next symbol in next iteration of (outer) loop break; //exit inner (group elision) loop } else if (pInner->iNumChildNodes>1) { //in/reached nontrivial subgroup - do make node for entire group: pNewChild= (buildAround) ? buildAround->RebuildGroup(pParent, pInner, iLbnd, iHbnd) : CreateGroupNode(pParent, pInner, iLbnd, iHbnd); i = pInner->iEnd; //make one group at a time - so move past entire group... pCurrentNode = pCurrentNode->pNext; //next sibling of _original_ pCurrentNode (above) // (maybe not of pCurrentNode now, which might be a subgroup filling the original) break; //exit inner (group elision) loop } //were about to create a group node, which would have only one child // (eventually, if the group node were PopulateChildren'd). // Such a child would entirely fill it's parent (the group), and thus, // creation/destruction of the child would cause the node's colour to flash // between that for parent group and child. // Hence, instead we elide the group node and create the child _here_... //1. however we also have to take account of the appearance of the elided group. Hence: groupPrefix += pInner->strLabel; if (pInner->bVisible) iOverrideColour=pInner->iColour; //2. now go into the group... pInner = pInner->pChild; bSymbol = (pInner==NULL); //which might contain a single subgroup, or a single symbol if (bSymbol) pCurrentNode = pCurrentNode->pNext; //if a symbol, we've still moved past the outer (elided) group DASHER_ASSERT(iEnd == (bSymbol ? i+1 : pInner->iEnd)); //probability calcs still ok //3. loop round inner loop... } //created a new node - symbol or (group which will have >1 child). DASHER_ASSERT(pParent->GetChildren().back()==pNewChild); //now adjust the node we've actually created, to take account of any elided group(s)... // tho not if we've reused the existing node, assume that's been adjusted already if (pNewChild && pNewChild!=buildAround) pNewChild->PrependElidedGroup(iOverrideColour, groupPrefix); } pParent->SetFlag(NF_ALLCHILDREN, true); } CAlphabetManager::CAlphNode::~CAlphNode() { delete m_pProbInfo; m_pMgr->m_pLanguageModel->ReleaseContext(iContext); } const std::string &CAlphabetManager::CSymbolNode::outputText() { return mgr()->m_pNCManager->GetAlphabet()->GetText(iSymbol); } void CAlphabetManager::CSymbolNode::Output(Dasher::VECTOR_SYMBOL_PROB* pAdded, int iNormalization) { //std::cout << this << " " << Parent() << ": Output at offset " << m_iOffset << " *" << m_pMgr->m_pNCManager->GetAlphabet()->GetText(t) << "* " << std::endl; - Dasher::CEditEvent oEvent(1, outputText(), m_iOffset); + Dasher::CEditEvent oEvent(1, outputText(), offset()); m_pMgr->m_pNCManager->InsertEvent(&oEvent); // Track this symbol and its probability for logging purposes if (pAdded != NULL) { Dasher::SymbolProb sItem; sItem.sym = iSymbol; sItem.prob = Range() / (double)iNormalization; pAdded->push_back(sItem); } } void CAlphabetManager::CSymbolNode::Undo(int *pNumDeleted) { - Dasher::CEditEvent oEvent(2, outputText(), m_iOffset); + Dasher::CEditEvent oEvent(2, outputText(), offset()); m_pMgr->m_pNCManager->InsertEvent(&oEvent); if (pNumDeleted) (*pNumDeleted)++; } CDasherNode *CAlphabetManager::CGroupNode::RebuildParent() { // CAlphNode's always have a parent, they inserted a symbol; CGroupNode's // with an m_pGroup have a container i.e. the parent group, unless // m_pGroup==NULL => "root" node where Alphabet->m_pBaseGroup is the *first*child*... if (m_pGroup == NULL) return NULL; //offset of group node is same as parent... - return CAlphNode::RebuildParent(m_iOffset); + return CAlphNode::RebuildParent(offset()); } CDasherNode *CAlphabetManager::CSymbolNode::RebuildParent() { //parent's offset is one less than this. - return CAlphNode::RebuildParent(m_iOffset-1); + return CAlphNode::RebuildParent(offset()-1); } CDasherNode *CAlphabetManager::CAlphNode::RebuildParent(int iNewOffset) { //possible that we have a parent, as RebuildParent() rebuilds back to closest AlphNode. if (Parent()) return Parent(); CAlphNode *pNewNode = m_pMgr->GetRoot(NULL, 0, 0, iNewOffset!=-1, iNewOffset+1); //now fill in the new node - recursively - until it reaches us m_pMgr->IterateChildGroups(pNewNode, NULL, this); //finally return our immediate parent (pNewNode may be an ancestor rather than immediate parent!) DASHER_ASSERT(Parent() != NULL); //although not required, we believe only NF_SEEN nodes are ever requested to rebuild their parents... DASHER_ASSERT(GetFlag(NF_SEEN)); //so set NF_SEEN on all created ancestors (of which pNewNode is the last) CDasherNode *pNode = this; do { pNode = pNode->Parent(); pNode->SetFlag(NF_SEEN, true); } while (pNode != pNewNode); return Parent(); } // TODO: Shouldn't there be an option whether or not to learn as we write? // For want of a better solution, game mode exemption explicit in this function void CAlphabetManager::CSymbolNode::SetFlag(int iFlag, bool bValue) { CDasherNode::SetFlag(iFlag, bValue); switch(iFlag) { case NF_COMMITTED: if(bValue && !GetFlag(NF_GAME) && m_pMgr->m_pInterface->GetBoolParameter(BP_LM_ADAPTIVE)) m_pMgr->m_pLanguageModel->LearnSymbol(m_pMgr->m_iLearnContext, iSymbol); break; } } diff --git a/Src/DasherCore/ControlManager.cpp b/Src/DasherCore/ControlManager.cpp index 5589384..da580f9 100644 --- a/Src/DasherCore/ControlManager.cpp +++ b/Src/DasherCore/ControlManager.cpp @@ -1,376 +1,372 @@ // ControlManager.cpp // // Copyright (c) 2007 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" #include "ControlManager.h" #include <cstring> using namespace Dasher; using namespace std; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG_MEMLEAKS #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif int CControlManager::m_iNextID = 0; CControlManager::CControlManager( CNodeCreationManager *pNCManager ) : m_pNCManager(pNCManager) { string SystemString = m_pNCManager->GetStringParameter(SP_SYSTEM_LOC); string UserLocation = m_pNCManager->GetStringParameter(SP_USER_LOC); m_iNextID = 0; // TODO: Need to fix this on WinCE build #ifndef _WIN32_WCE struct stat sFileInfo; string strFileName = UserLocation + "controllabels.xml"; // check first location for file if(stat(strFileName.c_str(), &sFileInfo) == -1) { // something went wrong strFileName = SystemString + "controllabels.xml"; // check second location for file if(stat(strFileName.c_str(), &sFileInfo) == -1) { // all else fails do something default LoadDefaultLabels(); } else LoadLabelsFromFile(strFileName, sFileInfo.st_size); } else LoadLabelsFromFile(strFileName, sFileInfo.st_size); ConnectNodes(); #endif } int CControlManager::LoadLabelsFromFile(string strFileName, int iFileSize) { // Implement Unicode names via xml from file: char* szFileBuffer = new char[iFileSize]; ifstream oFile(strFileName.c_str()); oFile.read(szFileBuffer, iFileSize); XML_Parser Parser = XML_ParserCreate(NULL); // Members passed as callbacks must be static, so don't have a "this" pointer. // We give them one through horrible casting so they can effect changes. XML_SetUserData(Parser, this); XML_SetElementHandler(Parser, XmlStartHandler, XmlEndHandler); XML_SetCharacterDataHandler(Parser, XmlCDataHandler); XML_Parse(Parser, szFileBuffer, iFileSize, false); // deallocate resources XML_ParserFree(Parser); oFile.close(); delete [] szFileBuffer; return 0; } int CControlManager::LoadDefaultLabels() { // TODO: Need to figure out how to handle offset changes here RegisterNode(CTL_ROOT, "Control", 8); RegisterNode(CTL_STOP, "Stop", 242); RegisterNode(CTL_PAUSE, "Pause", 241); RegisterNode(CTL_MOVE, "Move", -1); RegisterNode(CTL_MOVE_FORWARD, "->", -1); RegisterNode(CTL_MOVE_FORWARD_CHAR, ">", -1); RegisterNode(CTL_MOVE_FORWARD_WORD, ">>", -1); RegisterNode(CTL_MOVE_FORWARD_LINE, ">>>", -1); RegisterNode(CTL_MOVE_FORWARD_FILE, ">>>>", -1); RegisterNode(CTL_MOVE_BACKWARD, "<-", -1); RegisterNode(CTL_MOVE_BACKWARD_CHAR, "<", -1); RegisterNode(CTL_MOVE_BACKWARD_WORD, "<<", -1); RegisterNode(CTL_MOVE_BACKWARD_LINE, "<<<", -1); RegisterNode(CTL_MOVE_BACKWARD_FILE, "<<<<", -1); RegisterNode(CTL_DELETE, "Delete", -1); RegisterNode(CTL_DELETE_FORWARD, "->", -1); RegisterNode(CTL_DELETE_FORWARD_CHAR, ">", -1); RegisterNode(CTL_DELETE_FORWARD_WORD, ">>", -1); RegisterNode(CTL_DELETE_FORWARD_LINE, ">>>", -1); RegisterNode(CTL_DELETE_FORWARD_FILE, ">>>>", -1); RegisterNode(CTL_DELETE_BACKWARD, "<-", -1); RegisterNode(CTL_DELETE_BACKWARD_CHAR, "<", -1); RegisterNode(CTL_DELETE_BACKWARD_WORD, "<<", -1); RegisterNode(CTL_DELETE_BACKWARD_LINE, "<<<", -1); RegisterNode(CTL_DELETE_BACKWARD_FILE, "<<<<", -1); return 0; } int CControlManager::ConnectNodes() { ConnectNode(-1, CTL_ROOT, -2); ConnectNode(CTL_STOP, CTL_ROOT, -2); ConnectNode(CTL_PAUSE, CTL_ROOT, -2); ConnectNode(CTL_MOVE, CTL_ROOT, -2); ConnectNode(CTL_DELETE, CTL_ROOT, -2); ConnectNode(-1, CTL_STOP, -2); ConnectNode(CTL_ROOT, CTL_STOP, -2); ConnectNode(-1, CTL_PAUSE, -2); ConnectNode(CTL_ROOT, CTL_PAUSE, -2); ConnectNode(CTL_MOVE_FORWARD, CTL_MOVE, -2); ConnectNode(CTL_MOVE_BACKWARD, CTL_MOVE, -2); ConnectNode(CTL_MOVE_FORWARD_CHAR, CTL_MOVE_FORWARD, -2); ConnectNode(CTL_MOVE_FORWARD_WORD, CTL_MOVE_FORWARD, -2); ConnectNode(CTL_MOVE_FORWARD_LINE, CTL_MOVE_FORWARD, -2); ConnectNode(CTL_MOVE_FORWARD_FILE, CTL_MOVE_FORWARD, -2); ConnectNode(CTL_ROOT, CTL_MOVE_FORWARD_CHAR, -2); ConnectNode(CTL_MOVE_FORWARD, CTL_MOVE_FORWARD_CHAR, -2); ConnectNode(CTL_MOVE_BACKWARD, CTL_MOVE_FORWARD_CHAR, -2); ConnectNode(CTL_ROOT, CTL_MOVE_FORWARD_WORD, -2); ConnectNode(CTL_MOVE_FORWARD, CTL_MOVE_FORWARD_WORD, -2); ConnectNode(CTL_MOVE_BACKWARD, CTL_MOVE_FORWARD_WORD, -2); ConnectNode(CTL_ROOT, CTL_MOVE_FORWARD_LINE, -2); ConnectNode(CTL_MOVE_FORWARD, CTL_MOVE_FORWARD_LINE, -2); ConnectNode(CTL_MOVE_BACKWARD, CTL_MOVE_FORWARD_LINE, -2); ConnectNode(CTL_ROOT, CTL_MOVE_FORWARD_FILE, -2); ConnectNode(CTL_MOVE_FORWARD, CTL_MOVE_FORWARD_FILE, -2); ConnectNode(CTL_MOVE_BACKWARD, CTL_MOVE_FORWARD_FILE, -2); ConnectNode(CTL_MOVE_BACKWARD_CHAR, CTL_MOVE_BACKWARD, -2); ConnectNode(CTL_MOVE_BACKWARD_WORD, CTL_MOVE_BACKWARD, -2); ConnectNode(CTL_MOVE_BACKWARD_LINE, CTL_MOVE_BACKWARD, -2); ConnectNode(CTL_MOVE_BACKWARD_FILE, CTL_MOVE_BACKWARD, -2); ConnectNode(CTL_ROOT, CTL_MOVE_BACKWARD_CHAR, -2); ConnectNode(CTL_MOVE_FORWARD, CTL_MOVE_BACKWARD_CHAR, -2); ConnectNode(CTL_MOVE_BACKWARD, CTL_MOVE_BACKWARD_CHAR, -2); ConnectNode(CTL_ROOT, CTL_MOVE_BACKWARD_WORD, -2); ConnectNode(CTL_MOVE_FORWARD, CTL_MOVE_BACKWARD_WORD, -2); ConnectNode(CTL_MOVE_BACKWARD, CTL_MOVE_BACKWARD_WORD, -2); ConnectNode(CTL_ROOT, CTL_MOVE_BACKWARD_LINE, -2); ConnectNode(CTL_MOVE_FORWARD, CTL_MOVE_BACKWARD_LINE, -2); ConnectNode(CTL_MOVE_BACKWARD, CTL_MOVE_BACKWARD_LINE, -2); ConnectNode(CTL_ROOT, CTL_MOVE_BACKWARD_FILE, -2); ConnectNode(CTL_MOVE_FORWARD, CTL_MOVE_BACKWARD_FILE, -2); ConnectNode(CTL_MOVE_BACKWARD, CTL_MOVE_BACKWARD_FILE, -2); ConnectNode(CTL_DELETE_FORWARD, CTL_DELETE, -2); ConnectNode(CTL_DELETE_BACKWARD, CTL_DELETE, -2); ConnectNode(CTL_DELETE_FORWARD_CHAR, CTL_DELETE_FORWARD, -2); ConnectNode(CTL_DELETE_FORWARD_WORD, CTL_DELETE_FORWARD, -2); ConnectNode(CTL_DELETE_FORWARD_LINE, CTL_DELETE_FORWARD, -2); ConnectNode(CTL_DELETE_FORWARD_FILE, CTL_DELETE_FORWARD, -2); ConnectNode(CTL_ROOT, CTL_DELETE_FORWARD_CHAR, -2); ConnectNode(CTL_DELETE_FORWARD, CTL_DELETE_FORWARD_CHAR, -2); ConnectNode(CTL_DELETE_BACKWARD, CTL_DELETE_FORWARD_CHAR, -2); ConnectNode(CTL_ROOT, CTL_DELETE_FORWARD_WORD, -2); ConnectNode(CTL_DELETE_FORWARD, CTL_DELETE_FORWARD_WORD, -2); ConnectNode(CTL_DELETE_BACKWARD, CTL_DELETE_FORWARD_WORD, -2); ConnectNode(CTL_ROOT, CTL_DELETE_FORWARD_LINE, -2); ConnectNode(CTL_DELETE_FORWARD, CTL_DELETE_FORWARD_LINE, -2); ConnectNode(CTL_DELETE_BACKWARD, CTL_DELETE_FORWARD_LINE, -2); ConnectNode(CTL_ROOT, CTL_DELETE_FORWARD_FILE, -2); ConnectNode(CTL_DELETE_FORWARD, CTL_DELETE_FORWARD_FILE, -2); ConnectNode(CTL_DELETE_BACKWARD, CTL_DELETE_FORWARD_FILE, -2); ConnectNode(CTL_DELETE_BACKWARD_CHAR, CTL_DELETE_BACKWARD, -2); ConnectNode(CTL_DELETE_BACKWARD_WORD, CTL_DELETE_BACKWARD, -2); ConnectNode(CTL_DELETE_BACKWARD_LINE, CTL_DELETE_BACKWARD, -2); ConnectNode(CTL_DELETE_BACKWARD_FILE, CTL_DELETE_BACKWARD, -2); ConnectNode(CTL_ROOT, CTL_DELETE_BACKWARD_CHAR, -2); ConnectNode(CTL_DELETE_FORWARD, CTL_DELETE_BACKWARD_CHAR, -2); ConnectNode(CTL_DELETE_BACKWARD, CTL_DELETE_BACKWARD_CHAR, -2); ConnectNode(CTL_ROOT, CTL_DELETE_BACKWARD_WORD, -2); ConnectNode(CTL_DELETE_FORWARD, CTL_DELETE_BACKWARD_WORD, -2); ConnectNode(CTL_DELETE_BACKWARD, CTL_DELETE_BACKWARD_WORD, -2); ConnectNode(CTL_ROOT, CTL_DELETE_BACKWARD_LINE, -2); ConnectNode(CTL_DELETE_FORWARD, CTL_DELETE_BACKWARD_LINE, -2); ConnectNode(CTL_DELETE_BACKWARD, CTL_DELETE_BACKWARD_LINE, -2); ConnectNode(CTL_ROOT, CTL_DELETE_BACKWARD_FILE, -2); ConnectNode(CTL_DELETE_FORWARD, CTL_DELETE_BACKWARD_FILE, -2); ConnectNode(CTL_DELETE_BACKWARD, CTL_DELETE_BACKWARD_FILE, -2); return 0; } CControlManager::~CControlManager() { for(std::map<int,SControlItem*>::iterator i = m_mapControlMap.begin(); i != m_mapControlMap.end(); i++) { SControlItem* pNewNode = i->second; if (pNewNode != NULL) { delete pNewNode; pNewNode = NULL; } } } void CControlManager::RegisterNode( int iID, std::string strLabel, int iColour ) { SControlItem *pNewNode; pNewNode = new SControlItem; // FIXME - do constructor sanely pNewNode->strLabel = strLabel; pNewNode->iID = iID; pNewNode->iColour = iColour; m_mapControlMap[iID] = pNewNode; } void CControlManager::ConnectNode(int iChild, int iParent, int iAfter) { // FIXME - iAfter currently ignored (eventually -1 = start, -2 = end) if( iChild == -1 ) {// Corresponds to escaping back to alphabet SControlItem* node = m_mapControlMap[iParent]; if(node) node->vChildren.push_back(NULL); } else m_mapControlMap[iParent]->vChildren.push_back(m_mapControlMap[iChild]); } void CControlManager::DisconnectNode(int iChild, int iParent) { SControlItem* pParentNode = m_mapControlMap[iParent]; SControlItem* pChildNode = m_mapControlMap[iChild]; for(std::vector<SControlItem *>::iterator itChild(pParentNode->vChildren.begin()); itChild != pParentNode->vChildren.end(); ++itChild) if(*itChild == pChildNode) pParentNode->vChildren.erase(itChild); } CDasherNode *CControlManager::GetRoot(CDasherNode *pParent, unsigned int iLower, unsigned int iUpper, int iOffset) { CContNode *pNewNode = new CContNode(pParent, iOffset, iLower, iUpper, m_mapControlMap[0], this); // FIXME - handle context properly // pNewNode->SetContext(m_pLanguageModel->CreateEmptyContext()); return pNewNode; } CControlManager::CContNode::CContNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, const SControlItem *pControlItem, CControlManager *pMgr) : CDasherNode(pParent, iOffset, iLbnd, iHbnd, (pControlItem->iColour != -1) ? pControlItem->iColour : (pParent->ChildCount()%99)+11, pControlItem->strLabel), m_pControlItem(pControlItem), m_pMgr(pMgr) { } void CControlManager::CContNode::PopulateChildren() { CDasherNode *pNewNode; const unsigned int iNChildren( m_pControlItem->vChildren.size() ); const unsigned int iNorm(m_pMgr->m_pNCManager->GetLongParameter(LP_NORMALIZATION)); unsigned int iLbnd(0), iIdx(0); for(std::vector<SControlItem *>::const_iterator it(m_pControlItem->vChildren.begin()); it != m_pControlItem->vChildren.end(); ++it) { const unsigned int iHbnd((++iIdx*iNorm)/iNChildren); if( *it == NULL ) { // Escape back to alphabet - pNewNode = m_pMgr->m_pNCManager->GetAlphRoot(this, iLbnd, iHbnd, false, m_iOffset); + pNewNode = m_pMgr->m_pNCManager->GetAlphRoot(this, iLbnd, iHbnd, false, offset()); } else { - pNewNode = new CContNode(this, m_iOffset, iLbnd, iHbnd, *it, m_pMgr); + pNewNode = new CContNode(this, offset(), iLbnd, iHbnd, *it, m_pMgr); } iLbnd=iHbnd; DASHER_ASSERT(GetChildren().back()==pNewNode); } } int CControlManager::CContNode::ExpectedNumChildren() { return m_pControlItem->vChildren.size(); } void CControlManager::CContNode::Output(Dasher::VECTOR_SYMBOL_PROB* pAdded, int iNormalization ) { CControlEvent oEvent(m_pControlItem->iID); // TODO: Need to reimplement this // m_pNCManager->m_bContextSensitive=false; m_pMgr->m_pNCManager->InsertEvent(&oEvent); } void CControlManager::CContNode::Enter() { // Slow down to half the speed we were at m_pMgr->m_pNCManager->SetLongParameter(LP_BOOSTFACTOR, 50); //Disable auto speed control! m_pMgr->bDisabledSpeedControl = m_pMgr->m_pNCManager->GetBoolParameter(BP_AUTO_SPEEDCONTROL); m_pMgr->m_pNCManager->SetBoolParameter(BP_AUTO_SPEEDCONTROL, 0); } void CControlManager::CContNode::Leave() { // Now speed back up, by doubling the speed we were at in control mode m_pMgr->m_pNCManager->SetLongParameter(LP_BOOSTFACTOR, 100); //Re-enable auto speed control! if (m_pMgr->bDisabledSpeedControl) { m_pMgr->bDisabledSpeedControl = false; m_pMgr->m_pNCManager->SetBoolParameter(BP_AUTO_SPEEDCONTROL, 1); } } void CControlManager::XmlStartHandler(void *pUserData, const XML_Char *szName, const XML_Char **aszAttr) { int colour=-1; string str; if(0==strcmp(szName, "label")) { for(int i = 0; aszAttr[i]; i += 2) { if(0==strcmp(aszAttr[i],"value")) { str = string(aszAttr[i+1]); } if(0==strcmp(aszAttr[i],"color")) { colour = atoi(aszAttr[i+1]); } } ((CControlManager*)pUserData)->RegisterNode(CControlManager::m_iNextID++, str, colour); } } void CControlManager::XmlEndHandler(void *pUserData, const XML_Char *szName) { return; } void CControlManager::XmlCDataHandler(void *pUserData, const XML_Char *szData, int iLength){ return; } - -void CControlManager::CContNode::SetControlOffset(int iOffset) { - m_iOffset = iOffset; -} diff --git a/Src/DasherCore/ControlManager.h b/Src/DasherCore/ControlManager.h index 9593e0e..377f94c 100644 --- a/Src/DasherCore/ControlManager.h +++ b/Src/DasherCore/ControlManager.h @@ -1,135 +1,134 @@ // ControlManager.h // // Copyright (c) 2007 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #ifndef __controlmanager_h__ #define __controlmanager_h__ #include "DasherModel.h" #include "DasherNode.h" #include "Event.h" #include "NodeManager.h" #include <vector> #include <map> #include <fstream> #include <iostream> #ifndef _WIN32_WCE #include <sys/stat.h> #endif #include <string> #include <expat.h> using namespace std; namespace Dasher { class CDasherModel; /// \ingroup Model /// @{ /// A node manager which deals with control nodes. /// Currently can only have one instance due to use /// of static members for callbacks from expat. /// class CControlManager : public CNodeManager { public: enum { CTL_ROOT, CTL_STOP, CTL_PAUSE, CTL_MOVE, CTL_MOVE_FORWARD, CTL_MOVE_FORWARD_CHAR, CTL_MOVE_FORWARD_WORD, CTL_MOVE_FORWARD_LINE, CTL_MOVE_FORWARD_FILE, CTL_MOVE_BACKWARD, CTL_MOVE_BACKWARD_CHAR, CTL_MOVE_BACKWARD_WORD, CTL_MOVE_BACKWARD_LINE, CTL_MOVE_BACKWARD_FILE, CTL_DELETE, CTL_DELETE_FORWARD, CTL_DELETE_FORWARD_CHAR, CTL_DELETE_FORWARD_WORD, CTL_DELETE_FORWARD_LINE, CTL_DELETE_FORWARD_FILE, CTL_DELETE_BACKWARD, CTL_DELETE_BACKWARD_CHAR, CTL_DELETE_BACKWARD_WORD, CTL_DELETE_BACKWARD_LINE, CTL_DELETE_BACKWARD_FILE, CTL_USER }; CControlManager(CNodeCreationManager *pNCManager); ~CControlManager(); /// /// Get a new root node owned by this manager /// virtual CDasherNode *GetRoot(CDasherNode *pParent, unsigned int iLower, unsigned int iUpper, int iOffset); void RegisterNode( int iID, std::string strLabel, int iColour ); void ConnectNode(int iChild, int iParent, int iAfter); void DisconnectNode(int iChild, int iParent); private: struct SControlItem { std::vector<SControlItem *> vChildren; std::string strLabel; int iID; int iColour; }; class CContNode : public CDasherNode { public: CControlManager *mgr() {return m_pMgr;} CContNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, const SControlItem *pControlItem, CControlManager *pMgr); bool bShove() {return false;} /// /// Provide children for the supplied node /// virtual void PopulateChildren(); virtual int ExpectedNumChildren(); virtual void Output(Dasher::VECTOR_SYMBOL_PROB* pAdded, int iNormalization ); virtual void Enter(); virtual void Leave(); - void SetControlOffset(int iOffset); const SControlItem *m_pControlItem; private: CControlManager *m_pMgr; }; static void XmlStartHandler(void *pUserData, const XML_Char *szName, const XML_Char **aszAttr); static void XmlEndHandler(void *pUserData, const XML_Char *szName); static void XmlCDataHandler(void *pUserData, const XML_Char *szData, int iLength); int LoadLabelsFromFile(string strFileName, int iFileSize); int LoadDefaultLabels(); int ConnectNodes(); static int m_iNextID; CNodeCreationManager *m_pNCManager; std::map<int,SControlItem*> m_mapControlMap; ///Whether we'd temporarily disabled Automatic Speed Control ///(if _and only if_ so, should re-enable it when leaving a node) bool bDisabledSpeedControl; }; /// @} } #endif diff --git a/Src/DasherCore/ConversionHelper.cpp b/Src/DasherCore/ConversionHelper.cpp index 2dc38ea..4fe6d84 100644 --- a/Src/DasherCore/ConversionHelper.cpp +++ b/Src/DasherCore/ConversionHelper.cpp @@ -1,219 +1,219 @@ // ConversionHelper.cpp // // Copyright (c) 2007 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #ifdef HAVE_CONFIG_H #include <config.h> #endif #include "ConversionHelper.h" #include "Event.h" #include "EventHandler.h" #include "NodeCreationManager.h" #include "DasherNode.h" #include <iostream> #include <cstring> #include <string> #include <vector> #include <stdlib.h> //Note the new implementation in Mandarin Dasher may not be compatible with the previous implementation of Japanese Dasher //Need to reconcile (a small project) using namespace Dasher; using namespace std; CConversionHelper::CConversionHelper(CNodeCreationManager *pNCManager, CAlphabet *pAlphabet, CLanguageModel *pLanguageModel) : CConversionManager(pNCManager, pAlphabet), m_pLanguageModel(pLanguageModel) { colourStore[0][0]=66;//light blue colourStore[0][1]=64;//very light green colourStore[0][2]=62;//light yellow colourStore[1][0]=78;//light purple colourStore[1][1]=81;//brownish colourStore[1][2]=60;//red m_iLearnContext = m_pLanguageModel->CreateEmptyContext(); } CConversionManager::CConvNode *CConversionHelper::GetRoot(CDasherNode *pParent, unsigned int iLower, unsigned int iUpper, int iOffset) { CConvNode *pConvNode = CConversionManager::GetRoot(pParent, iLower, iUpper, iOffset); //note that pConvNode is actually a CConvHNode, created by this CConversionHelper: // the overridden CConversionManager::GetRoot creates the node the node it returns // by calling makeNode(), which we override to create a CConvHNode, and then just // fills in some of the fields; however, short of duplicating the code of // CConversionManager::GetRoot here, we can't get the type to reflect that... pConvNode->pLanguageModel = m_pLanguageModel; // context of a conversion node (e.g. ^) is the context of the // letter (e.g. e) before it (as the ^ entails replacing the e with // a single accented character e-with-^) pConvNode->iContext = pParent->CloneAlphContext(m_pLanguageModel); return pConvNode; } // TODO: This function needs to be significantly tidied up // TODO: get rid of pSizes void CConversionHelper::AssignChildSizes(const std::vector<SCENode *> &nodes, CLanguageModel::Context context) { AssignSizes(nodes, context, m_pNCManager->GetLongParameter(LP_NORMALIZATION), m_pNCManager->GetLongParameter(LP_UNIFORM)); } void CConversionHelper::CConvHNode::PopulateChildren() { DASHER_ASSERT(mgr()->m_pNCManager); // Do the conversion and build the tree (lattice) if it hasn't been // done already. // if(bisRoot && !pSCENode) { mgr()->BuildTree(this); } if(pSCENode && !pSCENode->GetChildren().empty()) { const std::vector<SCENode *> &vChildren = pSCENode->GetChildren(); // RecursiveDumpTree(pSCENode, 1); mgr()->AssignChildSizes(vChildren, iContext); int iIdx(0); int iCum(0); // int parentClr = pNode->Colour(); // TODO: Fixme int parentClr = 0; // Finally loop through and create the children for (std::vector<SCENode *>::const_iterator it = vChildren.begin(); it!=vChildren.end(); it++) { // std::cout << "Current scec: " << pCurrentSCEChild << std::endl; SCENode *pCurrentSCEChild(*it); DASHER_ASSERT(pCurrentSCEChild != NULL); unsigned int iLbnd(iCum); unsigned int iHbnd(iCum + pCurrentSCEChild->NodeSize); //m_pNCManager->GetLongParameter(LP_NORMALIZATION));// iCum = iHbnd; // TODO: Parameters here are placeholders - need to figure out // what's right // std::cout << "#" << pCurrentSCEChild->pszConversion << "#" << std::endl; - CConvNode *pNewNode = mgr()->makeNode(this, m_iOffset+1, iLbnd, iHbnd, mgr()->AssignColour(parentClr, pCurrentSCEChild, iIdx), string(pCurrentSCEChild->pszConversion)); + CConvNode *pNewNode = mgr()->makeNode(this, offset()+1, iLbnd, iHbnd, mgr()->AssignColour(parentClr, pCurrentSCEChild, iIdx), string(pCurrentSCEChild->pszConversion)); // TODO: Reimplement ---- // FIXME - handle context properly // pNewNode->SetContext(m_pLanguageModel->CreateEmptyContext()); // ----- pNewNode->bisRoot = false; pNewNode->pSCENode = pCurrentSCEChild; pNewNode->pLanguageModel = pLanguageModel; if(pLanguageModel) { CLanguageModel::Context iContext; iContext = pLanguageModel->CloneContext(this->iContext); if(pCurrentSCEChild ->Symbol !=-1) pNewNode->pLanguageModel->EnterSymbol(iContext, pCurrentSCEChild->Symbol); // TODO: Don't use symbols? pNewNode->iContext = iContext; } DASHER_ASSERT(GetChildren().back()==pNewNode); ++iIdx; } } else {//End of conversion -> default to alphabet //Phil// // TODO: Placeholder algorithm here // TODO: Add an 'end of conversion' node? //ACL 1/12/09 Note that this adds one to the m_iOffset of the created node // (whereas code that was here did not, but was otherwise identical to // superclass method...?) CConvNode::PopulateChildren(); } } int CConversionHelper::CConvHNode::ExpectedNumChildren() { if(bisRoot && !pSCENode) mgr()->BuildTree(this); if (pSCENode && !pSCENode->GetChildren().empty()) return pSCENode->GetChildren().size(); return CConvNode::ExpectedNumChildren(); } void CConversionHelper::BuildTree(CConvHNode *pRoot) { // Build the string to convert. std::string strCurrentString; // Search backwards but stop at any conversion node. for (CDasherNode *pNode = pRoot->Parent(); pNode && pNode->mgr() == this; pNode = pNode->Parent()) { // TODO: Need to make this the edit text rather than the display text strCurrentString = m_pAlphabet->GetText(pNode->GetAlphSymbol()) + strCurrentString; } // Handle/store the result. SCENode *pStartTemp; Convert(strCurrentString, &pStartTemp); // Store all conversion trees (SCENode trees) in the pUserData->pSCENode // of each Conversion Root. pRoot->pSCENode = pStartTemp; } CConversionHelper::CConvHNode::CConvHNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, int iColour, const string &strDisplayText, CConversionHelper *pMgr) : CConvNode(pParent, iOffset, iLbnd, iHbnd, iColour, strDisplayText, pMgr) { } CConversionHelper::CConvHNode *CConversionHelper::makeNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, int iColour, const string &strDisplayText) { return new CConvHNode(pParent, iOffset, iLbnd, iHbnd, iColour, strDisplayText, this); } void CConversionHelper::CConvHNode::SetFlag(int iFlag, bool bValue) { CDasherNode::SetFlag(iFlag, bValue); switch(iFlag) { case NF_COMMITTED: if(bValue){ if(!pSCENode) return; symbol s =pSCENode ->Symbol; if(s!=-1) pLanguageModel->LearnSymbol(mgr()->m_iLearnContext, s); } break; } } diff --git a/Src/DasherCore/ConversionManager.cpp b/Src/DasherCore/ConversionManager.cpp index 66729fc..b71fef6 100644 --- a/Src/DasherCore/ConversionManager.cpp +++ b/Src/DasherCore/ConversionManager.cpp @@ -1,195 +1,195 @@ // ConversionManager.cpp // // Copyright (c) 2007 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #ifdef HAVE_CONFIG_H #include <config.h> #endif #include "ConversionManager.h" #include "Event.h" #include "EventHandler.h" #include "NodeCreationManager.h" #include "DasherModel.h" #include <iostream> #include <cstring> #include <string> #include <vector> #include <stdlib.h> //Note the new implementation in Mandarin Dasher may not be compatible with the previous implementation of Japanese Dasher //Need to reconcile (a small project) using namespace Dasher; using namespace std; CConversionManager::CConversionManager(CNodeCreationManager *pNCManager, CAlphabet *pAlphabet) { m_pNCManager = pNCManager; m_pAlphabet = pAlphabet; m_iRefCount = 1; //Testing for alphabet details, delete if needed: /* int alphSize = pNCManager->GetAlphabet()->GetNumberSymbols(); std::cout<<"Alphabet size: "<<alphSize<<std::endl; for(int i =0; i<alphSize; i++) std::cout<<"symbol: "<<i<<" display text:"<<pNCManager->GetAlphabet()->GetDisplayText(i)<<std::endl; */ } CConversionManager::CConvNode *CConversionManager::makeNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, int iColour, const string &strDisplayText) { return new CConvNode(pParent, iOffset, iLbnd, iHbnd, iColour, strDisplayText, this); } CConversionManager::CConvNode *CConversionManager::GetRoot(CDasherNode *pParent, unsigned int iLower, unsigned int iUpper, int iOffset) { // TODO: Parameters here are placeholders - need to figure out what's right //TODO: hard-coded colour, and hard-coded displaytext... (ACL: read from Alphabet -> startConversionSymbol ?) CConvNode *pNewNode = makeNode(pParent, iOffset, iLower, iUpper, 9, ""); // FIXME - handle context properly // TODO: Reimplemnt ----- // pNewNode->SetContext(m_pLanguageModel->CreateEmptyContext()); // ----- pNewNode->bisRoot = true; pNewNode->pLanguageModel = NULL; pNewNode->pSCENode = 0; return pNewNode; } CConversionManager::CConvNode::CConvNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, int iColour, const string &strDisplayText, CConversionManager *pMgr) : CDasherNode(pParent, iOffset, iLbnd, iHbnd, iColour, strDisplayText), m_pMgr(pMgr) { pMgr->m_iRefCount++; } void CConversionManager::CConvNode::PopulateChildren() { DASHER_ASSERT(m_pMgr->m_pNCManager); // If no helper class is present then just drop straight back to an // alphabet root. This should only happen in error cases, and the // user should have been warned here. // unsigned int iLbnd(0); unsigned int iHbnd(m_pMgr->m_pNCManager->GetLongParameter(LP_NORMALIZATION)); - CDasherNode *pNewNode = m_pMgr->m_pNCManager->GetAlphRoot(this, iLbnd, iHbnd, false, m_iOffset + 1); + CDasherNode *pNewNode = m_pMgr->m_pNCManager->GetAlphRoot(this, iLbnd, iHbnd, false, offset() + 1); DASHER_ASSERT(GetChildren().back()==pNewNode); } int CConversionManager::CConvNode::ExpectedNumChildren() { return 1; //the alphabet root } CConversionManager::CConvNode::~CConvNode() { pLanguageModel->ReleaseContext(iContext); m_pMgr->Unref(); } void CConversionManager::RecursiveDumpTree(SCENode *pCurrent, unsigned int iDepth) { const std::vector<SCENode *> &children = pCurrent->GetChildren(); for (std::vector<SCENode *>::const_iterator it = children.begin(); it!=children.end(); it++) { SCENode *pCurrent(*it); for(unsigned int i(0); i < iDepth; ++i) std::cout << "-"; std::cout << " " << pCurrent->pszConversion << std::endl;//" " << pCurrent->IsHeadAndCandNum << " " << pCurrent->CandIndex << " " << pCurrent->IsComplete << " " << pCurrent->AcCharCount << std::endl; RecursiveDumpTree(pCurrent, iDepth + 1); } } void CConversionManager::CConvNode::GetContext(CDasherInterfaceBase *pInterface, std::vector<symbol> &vContextSymbols, int iOffset, int iLength) { - if (!GetFlag(NF_SEEN) && iOffset+iLength-1 == m_iOffset) { + if (!GetFlag(NF_SEEN) && iOffset+iLength-1 == offset()) { //ACL I'm extrapolating from PinYinConversionHelper (in which root nodes have their // Symbol set by SetConvSymbol, and child nodes are created in PopulateChildren // from SCENode's with Symbols having been set in in AssignSizes); not really sure // whether this is applicable in the general case(! - but although I think it's right // for PinYin, it wouldn't actually be used there, as MandarinDasher overrides contexts // everywhere!) DASHER_ASSERT(bisRoot || pSCENode); if (bisRoot || pSCENode->Symbol!=-1) { if (iLength>1) Parent()->GetContext(pInterface, vContextSymbols, iOffset, iLength-1); vContextSymbols.push_back(bisRoot ? iSymbol : pSCENode->Symbol); return; } //else, non-root with pSCENode->Symbol==-1 => fallthrough back to superclass code } CDasherNode::GetContext(pInterface, vContextSymbols, iOffset, iLength); } void CConversionManager::CConvNode::Output(Dasher::VECTOR_SYMBOL_PROB* pAdded, int iNormalization) { // TODO: Reimplement this // m_pNCManager->m_bContextSensitive = true; SCENode *pCurrentSCENode(pSCENode); if(pCurrentSCENode){ - Dasher::CEditEvent oEvent(1, pCurrentSCENode->pszConversion, m_iOffset); + Dasher::CEditEvent oEvent(1, pCurrentSCENode->pszConversion, offset()); m_pMgr->m_pNCManager->InsertEvent(&oEvent); if((GetChildren())[0]->mgr() == m_pMgr) { if (static_cast<CConvNode *>(GetChildren()[0])->m_pMgr == m_pMgr) { Dasher::CEditEvent oEvent(11, "", 0); m_pMgr->m_pNCManager->InsertEvent(&oEvent); } } } else { if(!bisRoot) { - Dasher::CEditEvent oOPEvent(1, "|", m_iOffset); + Dasher::CEditEvent oOPEvent(1, "|", offset()); m_pMgr->m_pNCManager->InsertEvent(&oOPEvent); } else { - Dasher::CEditEvent oOPEvent(1, ">", m_iOffset); + Dasher::CEditEvent oOPEvent(1, ">", offset()); m_pMgr->m_pNCManager->InsertEvent(&oOPEvent); } Dasher::CEditEvent oEvent(10, "", 0); m_pMgr->m_pNCManager->InsertEvent(&oEvent); } } void CConversionManager::CConvNode::Undo(int *pNumDeleted) { //ACL note: possibly ought to update pNumDeleted here if non-null, // but conversion symbols were not logged by old code so am not starting now! SCENode *pCurrentSCENode(pSCENode); if(pCurrentSCENode) { if(pCurrentSCENode->pszConversion && (strlen(pCurrentSCENode->pszConversion) > 0)) { - Dasher::CEditEvent oEvent(2, pCurrentSCENode->pszConversion, m_iOffset); + Dasher::CEditEvent oEvent(2, pCurrentSCENode->pszConversion, offset()); m_pMgr->m_pNCManager->InsertEvent(&oEvent); } } else { if(!bisRoot) { - Dasher::CEditEvent oOPEvent(2, "|", m_iOffset); + Dasher::CEditEvent oOPEvent(2, "|", offset()); m_pMgr->m_pNCManager->InsertEvent(&oOPEvent); } else { - Dasher::CEditEvent oOPEvent(2, ">", m_iOffset); + Dasher::CEditEvent oOPEvent(2, ">", offset()); m_pMgr->m_pNCManager->InsertEvent(&oOPEvent); } } } diff --git a/Src/DasherCore/DasherNode.h b/Src/DasherCore/DasherNode.h index 720369b..b700500 100644 --- a/Src/DasherCore/DasherNode.h +++ b/Src/DasherCore/DasherNode.h @@ -1,341 +1,346 @@ // DasherNode.h // // Copyright (c) 2007 David Ward // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #ifndef __DasherNode_h__ #define __DasherNode_h__ #include "../Common/Common.h" #include "../Common/NoClones.h" #include "LanguageModelling/LanguageModel.h" #include "DasherTypes.h" #include "NodeManager.h" namespace Dasher { class CDasherNode; class CDasherInterfaceBase; }; #include <deque> #include <iostream> #include <vector> // Node flag constants #define NF_COMMITTED 1 #define NF_SEEN 2 #define NF_CONVERTED 4 #define NF_GAME 8 #define NF_ALLCHILDREN 16 #define NF_SUPER 32 #define NF_END_GAME 64 /// \ingroup Model /// @{ /// @brief A node in the Dasher model /// /// The Dasher node represents a box drawn on the display. This class /// contains the information required to render the node, as well as /// navigation within the model (parents and children /// etc.). Additional information is stored in m_pUserData, which is /// interpreted by the node manager associated with this class. Any /// logic specific to a particular node manager should be stored here. /// /// @todo Encapsulate presentation data in a structure? /// @todo Check that all methods respect the pseudochild attribute class Dasher::CDasherNode:private NoClones { public: /// Display attributes of this node, used for rendering. /// Colour: -1 for invisible inline int getColour() {return m_iColour;} inline std::string &getDisplayText() {return m_strDisplayText;} ///Whether labels on child nodes should be displaced to the right of this node's label. /// (Default implementation returns true, subclasses should override if appropriate) virtual bool bShove() {return true;} inline int offset() {return m_iOffset;} CDasherNode *onlyChildRendered; //cache that only one child was rendered (as it filled the screen) /// Container type for storing children. Note that it's worth /// optimising this as lookup happens a lot typedef std::deque<CDasherNode*> ChildMap; /// @brief Constructor /// /// @param pParent Parent of the new node /// @param iLbnd Lower bound of node within parent /// @param iHbnd Upper bound of node within parent /// @param pDisplayInfo Struct containing information on how to display the node /// CDasherNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, int iColour, const std::string &strDisplayText); /// @brief Destructor /// virtual ~CDasherNode(); /// Adjusts the colour & label of this node to look as it would if it /// were the sole child of another node with the specified colour and label /// (without actually making the other/group node) void PrependElidedGroup(int iGroupColour, std::string &strGroupLabel); void Trace() const; // diagnostic /// @name Routines for manipulating node status /// @{ /// @brief Set a node flag /// /// Set various flags corresponding to the state of the node. The following flags are defined: /// /// NF_COMMITTED - Node is 'above' the root, so corresponding symbol /// has been added to text box, language model trained etc /// /// NF_SEEN - Node has already been output /// /// NF_CONVERTED - Node has been converted (eg Japanese mode) /// /// NF_GAME - Node is on the path in game mode /// /// NF_ALLCHILDREN - Node has all children (TODO: obsolete?) /// /// NF_SUPER - Node covers entire visible area /// /// NF_END_GAME - Node is the last one of the phrase in game mode /// /// /// @param iFlag The flag to set /// @param bValue The new value of the flag /// virtual void SetFlag(int iFlag, bool bValue); /// @brief Get the value of a flag for this node /// /// @param iFlag The flag to get /// /// @return The current value of the flag /// inline bool GetFlag(int iFlag) const; /// @} /// @name Routines relating to the size of the node /// @{ // Lower and higher bounds, and the range /// @brief Get the lower bound of a node /// /// @return The lower bound /// inline unsigned int Lbnd() const; /// @brief Get the upper bound of a node /// /// @return The upper bound /// inline unsigned int Hbnd() const; /// @brief Get the range of a node (upper - lower bound) /// /// @return The range /// /// @todo Should this be here (trivial arithmethic of existing methods) /// inline unsigned int Range() const; /// @brief Reset the range of a node /// /// @param iLower New lower bound /// @param iUpper New upper bound /// inline void SetRange(unsigned int iLower, unsigned int iUpper); /// @brief Get the size of the most probable child /// /// @return The size /// int MostProbableChild(); /// @} /// @name Routines for manipulating relatives /// @{ inline const ChildMap & GetChildren() const; inline unsigned int ChildCount() const; inline CDasherNode *Parent() const; void SetParent(CDasherNode *pNewParent); // TODO: Should this be here? CDasherNode *const Get_node_under(int, myint y1, myint y2, myint smousex, myint smousey); // find node under given co-ords /// @brief Orphan a child of this node /// /// Deletes all other children, and the node itself /// /// @param pChild The child to keep /// void OrphanChild(CDasherNode * pChild); /// @brief Delete the nephews of a given child /// /// @param pChild The child to keep /// void DeleteNephews(CDasherNode *pChild); /// @brief Delete the children of this node /// /// void Delete_children(); /// @} /// /// Sees if a *child* / descendant of the specified node (not that node itself) /// represents the specified character. If so, set the child & intervening nodes' /// NF_GAME flag, and return true; otherwise, return false. /// bool GameSearchChildren(std::string strTargetUtf8Char); /// @name Management routines (once accessed via NodeManager) /// @{ /// Gets the node manager for this object. Meaning defined by subclasses, /// which should override and refine the return type appropriately; /// the main use is to provide runtime type info to check casting! virtual CNodeManager *mgr() = 0; /// /// Provide children for the supplied node /// virtual void PopulateChildren() = 0; /// The number of children which a call to PopulateChildren can be expected to generate. /// (This is not required to be 100% accurate, but any discrepancies will likely cause /// the node budgetting algorithm to behave sub-optimally) virtual int ExpectedNumChildren() = 0; /// /// Called whenever a node belonging to this manager first /// moves under the crosshair /// virtual void Output(Dasher::VECTOR_SYMBOL_PROB* pAdded, int iNormalization) {}; virtual void Undo(int *pNumDeleted) {}; virtual void Enter() {}; virtual void Leave() {}; virtual CDasherNode *RebuildParent() { return 0; }; /// /// Get as many symbols of context, up to the _end_ of the specified range, /// as possible from this node and its uncommitted ancestors /// virtual void GetContext(CDasherInterfaceBase *pInterface, std::vector<symbol> &vContextSymbols, int iOffset, int iLength); - virtual void SetControlOffset(int iOffset) {}; + /// ACL Not really sure why we should have to have this, but seems it's needed for something + /// to do with speech on Linux. I'm preserving it for now (indeed, making it part of CDasherNode, + /// rather than CControlManager::CContNode, where it should be - but that would require making + /// m_iOffset visible), as hopefully all speech functionality will be redone shortly... + void SetControlOffset(int iOffset) {m_iOffset = iOffset;}; /// /// See if this node represents the specified alphanumeric character; if so, set it's NF_GAME flag and /// return true; otherwise, return false. /// virtual bool GameSearchNode(std::string strTargetUtf8Char) {return false;} /// Clone the context of the specified node, if it's an alphabet node; /// else return an empty context. (Used by ConversionManager) virtual CLanguageModel::Context CloneAlphContext(CLanguageModel *pLanguageModel) { return pLanguageModel->CreateEmptyContext(); }; virtual symbol GetAlphSymbol() { throw "Hack for pre-MandarinDasher ConversionManager::BuildTree method, needs to access CAlphabetManager-private struct"; } /// @} private: inline ChildMap &Children(); unsigned int m_iLbnd; unsigned int m_iHbnd; // the cumulative lower and upper bound prob relative to parent int m_iRefCount; // reference count if ancestor of (or equal to) root node ChildMap m_mChildren; // pointer to array of children CDasherNode *m_pParent; // pointer to parent // Binary flags representing the state of the node int m_iFlags; - + + int m_iOffset; + protected: int m_iColour; - int m_iOffset; std::string m_strDisplayText; }; /// @} namespace Dasher { /// Return the number of CDasherNode objects currently in existence. int currentNumNodeObjects(); } ///////////////////////////////////////////////////////////////////////////// // Inline functions ///////////////////////////////////////////////////////////////////////////// namespace Dasher { inline unsigned int CDasherNode::Lbnd() const { return m_iLbnd; } inline unsigned int CDasherNode::Hbnd() const { return m_iHbnd; } inline unsigned int CDasherNode::Range() const { return m_iHbnd - m_iLbnd; } inline CDasherNode::ChildMap &CDasherNode::Children() { return m_mChildren; } inline const CDasherNode::ChildMap &CDasherNode::GetChildren() const { return m_mChildren; } inline unsigned int CDasherNode::ChildCount() const { return m_mChildren.size(); } inline bool CDasherNode::GetFlag(int iFlag) const { return ((m_iFlags & iFlag) != 0); } inline CDasherNode *CDasherNode::Parent() const { return m_pParent; } inline void CDasherNode::SetRange(unsigned int iLower, unsigned int iUpper) { m_iLbnd = iLower; m_iHbnd = iUpper; } } #endif /* #ifndef __DasherNode_h__ */ diff --git a/Src/DasherCore/MandarinAlphMgr.cpp b/Src/DasherCore/MandarinAlphMgr.cpp index 93b3926..7f186a8 100644 --- a/Src/DasherCore/MandarinAlphMgr.cpp +++ b/Src/DasherCore/MandarinAlphMgr.cpp @@ -1,303 +1,303 @@ // MandarinAlphMgr.cpp // // Copyright (c) 2009 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" #include "MandarinAlphMgr.h" #include "LanguageModelling/PPMPYLanguageModel.h" #include "DasherInterfaceBase.h" #include "DasherNode.h" #include "Event.h" #include "EventHandler.h" #include "NodeCreationManager.h" #include <vector> #include <sstream> #include <iostream> using namespace std; using namespace Dasher; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG_MEMLEAKS #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif CMandarinAlphMgr::CMandarinAlphMgr(CDasherInterfaceBase *pInterface, CNodeCreationManager *pNCManager, CLanguageModel *pLanguageModel) : CAlphabetManager(pInterface, pNCManager, pLanguageModel), m_pParser(new CPinyinParser(pInterface->GetStringParameter(SP_SYSTEM_LOC) +"/alphabet.chineseRuby.xml")), m_pCHAlphabet(new CAlphabet(pInterface->GetInfo("Chinese / 简体中文 (simplified chinese, in pin yin groups)"))) { } CMandarinAlphMgr::~CMandarinAlphMgr() { delete m_pParser; } CDasherNode *CMandarinAlphMgr::CreateSymbolNode(CAlphNode *pParent, symbol iSymbol, unsigned int iLbnd, unsigned int iHbnd) { if (iSymbol <= 1288) { //Will wrote: //Modified for Mandarin Dasher //The following logic switch allows punctuation nodes in Mandarin to be treated in the same way as English (i.e. display and populate next round) instead of invoking a conversion node //ACL I think by "the following logic switch" he meant that symbols <= 1288 are "normal" nodes, NOT punctuation nodes, // whereas punctuation is handled by the fallthrough case (standard AlphabetManager CreateSymbolNode) /*old code: * CDasherNode *pNewNode = m_pNCManager->GetConvRoot(pParent, iLbnd, iHbnd, pParent->m_iOffset+1); * static_cast<CPinYinConversionHelper::CPYConvNode *>(pNewNode)->SetConvSymbol(iSymbol); * return pNewNode; */ //CTrieNode parallels old PinyinConversionHelper's SetConvSymbol; we keep // the same offset as we've still not entered/selected a symbol (leaf) CConvRoot *pNewNode = new CConvRoot(pParent, pParent->offset(), iLbnd, iHbnd, this, m_pParser->GetTrieNode(m_pNCManager->GetAlphabet()->GetDisplayText(iSymbol))); //from ConversionHelper: //pNewNode->m_pLanguageModel = m_pLanguageModel; pNewNode->iContext = m_pLanguageModel->CloneContext(pParent->iContext); return pNewNode; } return CAlphabetManager::CreateSymbolNode(pParent, iSymbol, iLbnd, iHbnd); } CMandarinAlphMgr::CConvRoot::CConvRoot(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, CMandarinAlphMgr *pMgr, CTrieNode *pTrie) : CDasherNode(pParent, iOffset, iLbnd, iHbnd, 9, ""), m_pMgr(pMgr), m_pTrie(pTrie) { //colour + label from ConversionManager. } int CMandarinAlphMgr::CConvRoot::ExpectedNumChildren() { if (m_vChInfo.empty()) BuildConversions(); return m_vChInfo.size(); } void CMandarinAlphMgr::CConvRoot::BuildConversions() { if (!m_pTrie || !m_pTrie->list()) { //TODO some kind of fallback??? e.g. start new char? DASHER_ASSERT(false); return; } for(set<string>::iterator it = m_pTrie->list()->begin(); it != m_pTrie->list()->end(); ++it) { std::vector<symbol> vSyms; m_pMgr->m_pCHAlphabet->GetSymbols(vSyms, *it); DASHER_ASSERT(vSyms.size()==1); //does it ever happen? if so, Will's code would effectively push -1 DASHER_ASSERT(m_pMgr->m_pCHAlphabet->GetText(vSyms[0]) == *it); m_vChInfo.push_back(std::pair<symbol, unsigned int>(vSyms[0],0)); } //TODO would be nicer to do this only if we need the size info (i.e. PopulateChildren not ExpectedNumChildren) ? m_pMgr->AssignSizes(m_vChInfo, iContext); } void CMandarinAlphMgr::CConvRoot::PopulateChildren() { if (m_vChInfo.empty()) BuildConversions(); int iIdx(0); int iCum(0); // int parentClr = pNode->Colour(); // TODO: Fixme int parentClr = 0; // Finally loop through and create the children for (vector<pair<symbol, unsigned int> >::const_iterator it = m_vChInfo.begin(); it!=m_vChInfo.end(); it++) { // std::cout << "Current scec: " << pCurrentSCEChild << std::endl; unsigned int iLbnd(iCum); unsigned int iHbnd(iCum + it->second); iCum = iHbnd; // TODO: Parameters here are placeholders - need to figure out // what's right int iColour(m_vChInfo.size()==1 ? getColour() : m_pMgr->AssignColour(parentClr, iIdx)); // std::cout << "#" << pCurrentSCEChild->pszConversion << "#" << std::endl; - CMandNode *pNewNode = new CMandSym(this, m_iOffset+1, iLbnd, iHbnd, iColour, m_pMgr, it->first); + CMandNode *pNewNode = new CMandSym(this, offset()+1, iLbnd, iHbnd, iColour, m_pMgr, it->first); // TODO: Reimplement ---- // FIXME - handle context properly // pNewNode->SetContext(m_pLanguageModel->CreateEmptyContext()); // ----- pNewNode->iContext = m_pMgr->m_pLanguageModel->CloneContext(this->iContext); m_pMgr->m_pLanguageModel->EnterSymbol(iContext, it->first); // TODO: Don't use symbols? DASHER_ASSERT(GetChildren().back()==pNewNode); ++iIdx; } } void CMandarinAlphMgr::AssignSizes(std::vector<pair<symbol,unsigned int> > &vChildren, Dasher::CLanguageModel::Context context) { const uint64 iNorm(m_pNCManager->GetLongParameter(LP_NORMALIZATION)); const unsigned int uniform((m_pNCManager->GetLongParameter(LP_UNIFORM)*iNorm)/1000); int iRemaining(iNorm); uint64 sumProb=0; //CLanguageModel::Context iCurrentContext; // std::cout<<"size of symbolstore "<<SymbolStore.size()<<std::endl; // std::cout<<"norm input: "<<nonuniform_norm/(iSymbols/iNChildren/100)<<std::endl; //ACL pass in iNorm and uniform directly - GetPartProbs distributes the last param between // however elements there are in vChildren... static_cast<CPPMPYLanguageModel *>(m_pLanguageModel)->GetPartProbs(context, vChildren, iNorm, uniform); //std::cout<<"after get probs "<<std::endl; for (std::vector<pair<symbol,unsigned int> >::const_iterator it = vChildren.begin(); it!=vChildren.end(); it++) { sumProb += it->second; } // std::cout<<"Sum Prob "<<sumProb<<std::endl; // std::cout<<"norm "<<nonuniform_norm<<std::endl; //Match, sumProbs = nonuniform_norm //but fix one element 'Da4' // Finally, iterate through the nodes and actually assign the sizes. // std::cout<<"sumProb "<<sumProb<<std::endl; for (std::vector<pair<symbol,unsigned int> >::iterator it = vChildren.begin(); it!=vChildren.end(); it++) { DASHER_ASSERT(it->first>-1); //ACL Will's code tested for both these conditions explicitly, and if so DASHER_ASSERT(sumProb>0); //then used a probability of 0. I don't think either //should ever happen if the alphabet files are right (there'd have to //be either no conversions of the syllable+tone, or else the LM'd have //to assign zero probability to each), so I'm removing these tests for now... iRemaining -= it->second = (it->second*iNorm)/sumProb; if (it->second==0) { #ifdef DEBUG std::cout << "WARNING: Erasing zero-probability conversion with symbol " << it->first << std::endl; #endif vChildren.erase(it--); } // std::cout<<pNode->pszConversion<<std::endl; // std::cout<<pNode->Symbol<<std::endl; // std::cout<<"Probs i "<<pNode<<std::endl; // std::cout<<"Symbol i"<<SymbolStore[iIdx]<<std::endl; // std::cout<<"symbols size "<<SymbolStore.size()<<std::endl; // std::cout<<"Symbols address "<<&SymbolStore<<std::endl; } //std::cout<<"iRemaining "<<iRemaining<<std::endl; // Last of all, allocate anything left over due to rounding error int iLeft(vChildren.size()); for (std::vector<pair<symbol,unsigned int> >::iterator it = vChildren.begin(); it!=vChildren.end(); it++) { int iDiff(iRemaining / iLeft); it->second += iDiff; iRemaining -= iDiff; --iLeft; // std::cout<<"Node size for "<<pNode->pszConversion<<std::endl; //std::cout<<"is "<<pNode->NodeSize<<std::endl; } DASHER_ASSERT(iRemaining == 0); } static int colourStore[2][3] = { {66,//light blue 64,//very light green 62},//light yellow {78,//light purple 81,//brownish 60},//red }; //Pulled from CConversionHelper, where it's described as "needing a rethink"... int CMandarinAlphMgr::AssignColour(int parentClr, int childIndex) { int which = -1; for (int i=0; i<2; i++) for(int j=0; j<3; j++) if (parentClr == colourStore[i][j]) which = i; if(which == -1) return colourStore[0][childIndex%3]; else if(which == 0) return colourStore[1][childIndex%3]; else return colourStore[0][childIndex%3]; }; CLanguageModel::Context CMandarinAlphMgr::CreateSymbolContext(CAlphNode *pParent, symbol iSymbol) { //Context carry-over. This code may worth looking at debug return m_pLanguageModel->CloneContext(pParent->iContext); } CMandarinAlphMgr::CMandNode::CMandNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, CMandarinAlphMgr *pMgr, symbol iSymbol) : CSymbolNode(pParent, iOffset, iLbnd, iHbnd, pMgr, iSymbol) { } CMandarinAlphMgr::CMandNode::CMandNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, int iColour, const string &strDisplayText, CMandarinAlphMgr *pMgr, symbol iSymbol) : CSymbolNode(pParent, iOffset, iLbnd, iHbnd, iColour, strDisplayText, pMgr, iSymbol) { } CMandarinAlphMgr::CMandNode *CMandarinAlphMgr::makeSymbol(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, symbol iSymbol) { // Override standard symbol factory method, called by superclass, to make CMandNodes // - important only to disable learn-as-you-write... return new CMandNode(pParent, iOffset, iLbnd, iHbnd, this, iSymbol); } void CMandarinAlphMgr::CMandNode::SetFlag(int iFlag, bool bValue) { //``disable learn-as-you-write for Mandarin Dasher'' if (iFlag==NF_COMMITTED) CDasherNode::SetFlag(iFlag, bValue); //bypass CAlphNode setter! else CAlphNode::SetFlag(iFlag, bValue); } // For converted chinese symbols, we construct instead CMandSyms... CMandarinAlphMgr::CMandSym::CMandSym(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, int iColour, CMandarinAlphMgr *pMgr, symbol iSymbol) : CMandNode(pParent, iOffset, iLbnd, iHbnd, iColour, pMgr->m_pCHAlphabet->GetText(iSymbol), pMgr, iSymbol) { //Note we passed a custom label into superclass constructor: // the chinese characters are in the _text_ (not label - that's e.g. "liang4") // of the alphabet (& the pszConversion from PinyinParser was converted to symbol // by CAlphabet::GetSymbols, which does string->symbol by _text_; we're reversing that) } const std::string &CMandarinAlphMgr::CMandSym::outputText() { //use chinese, not pinyin, alphabet... return mgr()->m_pCHAlphabet->GetText(iSymbol); }
rgee/HFOSS-Dasher
6db5cf3e61d31f88077602f9189f1e2023ef18c8
Remove SDisplayInfo substruct of CDasherNode; hide m_iOffset & set in c'tor
diff --git a/Src/DasherCore/AlphabetManager.cpp b/Src/DasherCore/AlphabetManager.cpp index b11f1e6..a39c35d 100644 --- a/Src/DasherCore/AlphabetManager.cpp +++ b/Src/DasherCore/AlphabetManager.cpp @@ -1,486 +1,461 @@ // AlphabetManager.cpp // // Copyright (c) 2007 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" #include "AlphabetManager.h" #include "ConversionManager.h" #include "DasherInterfaceBase.h" #include "DasherNode.h" #include "Event.h" #include "EventHandler.h" #include "NodeCreationManager.h" #include <vector> #include <sstream> #include <iostream> using namespace Dasher; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG_MEMLEAKS #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif CAlphabetManager::CAlphabetManager(CDasherInterfaceBase *pInterface, CNodeCreationManager *pNCManager, CLanguageModel *pLanguageModel) : m_pLanguageModel(pLanguageModel), m_pNCManager(pNCManager) { m_pInterface = pInterface; m_iLearnContext = m_pLanguageModel->CreateEmptyContext(); } -CAlphabetManager::CAlphNode::CAlphNode(CDasherNode *pParent, unsigned int iLbnd, unsigned int iHbnd, CDasherNode::SDisplayInfo *pDisplayInfo, CAlphabetManager *pMgr) -: CDasherNode(pParent, iLbnd, iHbnd, pDisplayInfo), m_pProbInfo(NULL), m_pMgr(pMgr) { +CAlphabetManager::CAlphNode::CAlphNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, int iColour, const string &strDisplayText, CAlphabetManager *pMgr) +: CDasherNode(pParent, iOffset, iLbnd, iHbnd, iColour, strDisplayText), m_pProbInfo(NULL), m_pMgr(pMgr) { }; -CAlphabetManager::CSymbolNode::CSymbolNode(CDasherNode *pParent, unsigned int iLbnd, unsigned int iHbnd, CDasherNode::SDisplayInfo *pDisplayInfo, CAlphabetManager *pMgr, symbol _iSymbol) -: CAlphNode(pParent, iLbnd, iHbnd, pDisplayInfo, pMgr), iSymbol(_iSymbol) { +CAlphabetManager::CSymbolNode::CSymbolNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, CAlphabetManager *pMgr, symbol _iSymbol) +: CAlphNode(pParent, iOffset, iLbnd, iHbnd, pMgr->m_pNCManager->GetAlphabet()->GetColour(_iSymbol, iOffset%2), pMgr->m_pNCManager->GetAlphabet()->GetDisplayText(_iSymbol), pMgr), iSymbol(_iSymbol) { }; -CAlphabetManager::CGroupNode::CGroupNode(CDasherNode *pParent, unsigned int iLbnd, unsigned int iHbnd, CDasherNode::SDisplayInfo *pDisplayInfo, CAlphabetManager *pMgr, SGroupInfo *pGroup) -: CAlphNode(pParent, iLbnd, iHbnd, pDisplayInfo, pMgr), m_pGroup(pGroup) { +CAlphabetManager::CSymbolNode::CSymbolNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, int iColour, const string &strDisplayText, CAlphabetManager *pMgr, symbol _iSymbol) +: CAlphNode(pParent, iOffset, iLbnd, iHbnd, iColour, strDisplayText, pMgr), iSymbol(_iSymbol) { }; -CAlphabetManager::CSymbolNode *CAlphabetManager::makeSymbol(CDasherNode *pParent, unsigned int iLbnd, unsigned int iHbnd, CDasherNode::SDisplayInfo *pDisplayInfo, symbol iSymbol) { - return new CSymbolNode(pParent, iLbnd, iHbnd, pDisplayInfo, this, iSymbol); +CAlphabetManager::CGroupNode::CGroupNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, CAlphabetManager *pMgr, SGroupInfo *pGroup) +: CAlphNode(pParent, iOffset, iLbnd, iHbnd, + pGroup ? (pGroup->bVisible ? pGroup->iColour : pParent->getColour()) + : pMgr->m_pNCManager->GetAlphabet()->GetColour(0, iOffset%2), + pGroup ? pGroup->strLabel : "", pMgr), m_pGroup(pGroup) { +}; + +CAlphabetManager::CSymbolNode *CAlphabetManager::makeSymbol(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, symbol iSymbol) { + return new CSymbolNode(pParent, iOffset, iLbnd, iHbnd, this, iSymbol); } -CAlphabetManager::CGroupNode *CAlphabetManager::makeGroup(CDasherNode *pParent, unsigned int iLbnd, unsigned int iHbnd, CDasherNode::SDisplayInfo *pDisplayInfo, SGroupInfo *pGroup) { - return new CGroupNode(pParent, iLbnd, iHbnd, pDisplayInfo, this, pGroup); +CAlphabetManager::CGroupNode *CAlphabetManager::makeGroup(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, SGroupInfo *pGroup) { + return new CGroupNode(pParent, iOffset, iLbnd, iHbnd, this, pGroup); } CAlphabetManager::CAlphNode *CAlphabetManager::GetRoot(CDasherNode *pParent, unsigned int iLower, unsigned int iUpper, bool bEnteredLast, int iOffset) { int iNewOffset(max(-1,iOffset-1)); std::vector<symbol> vContextSymbols; // TODO: make the LM get the context, rather than force it to fix max context length as an int int iStart = max(0, iNewOffset - m_pLanguageModel->GetContextLength()); if(pParent) { pParent->GetContext(m_pInterface, vContextSymbols, iStart, iNewOffset+1 - iStart); } else { std::string strContext = (iNewOffset == -1) ? m_pNCManager->GetAlphabet()->GetDefaultContext() : m_pInterface->GetContext(iStart, iNewOffset+1 - iStart); m_pNCManager->GetAlphabet()->GetSymbols(vContextSymbols, strContext); } - - CDasherNode::SDisplayInfo *pDisplayInfo = new CDasherNode::SDisplayInfo; - pDisplayInfo->bShove = true; - pDisplayInfo->bVisible = true; CAlphNode *pNewNode; CLanguageModel::Context iContext = m_pLanguageModel->CreateEmptyContext(); std::vector<symbol>::iterator it = vContextSymbols.end(); while (it!=vContextSymbols.begin()) { if (*(--it) == 0) { //found an impossible symbol! start after it ++it; break; } } if (it == vContextSymbols.end()) { //previous character was not in the alphabet! //can't construct a node "responsible" for entering it bEnteredLast=false; //instead, Create a node as if we were starting a new sentence... vContextSymbols.clear(); m_pNCManager->GetAlphabet()->GetSymbols(vContextSymbols, m_pNCManager->GetAlphabet()->GetDefaultContext()); it = vContextSymbols.begin(); //TODO: What it the default context somehow contains symbols not in the alphabet? } //enter the symbols we could make sense of, into the LM context... while (it != vContextSymbols.end()) { m_pLanguageModel->EnterSymbol(iContext, *(it++)); } if(!bEnteredLast) { - pDisplayInfo->strDisplayText = ""; //equivalent to do m_pNCManager->GetAlphabet()->GetDisplayText(0) - pDisplayInfo->iColour = m_pNCManager->GetAlphabet()->GetColour(0, iNewOffset%2); - pNewNode = makeGroup(pParent, iLower, iUpper, pDisplayInfo, NULL); + pNewNode = makeGroup(pParent, iNewOffset, iLower, iUpper, NULL); } else { const symbol iSymbol(vContextSymbols[vContextSymbols.size() - 1]); - pDisplayInfo->strDisplayText = m_pNCManager->GetAlphabet()->GetDisplayText(iSymbol); - pDisplayInfo->iColour = m_pNCManager->GetAlphabet()->GetColour(iSymbol, iNewOffset%2); - pNewNode = makeSymbol(pParent, iLower, iUpper, pDisplayInfo, iSymbol); + pNewNode = makeSymbol(pParent, iNewOffset, iLower, iUpper, iSymbol); //if the new node is not child of an existing node, then it // represents a symbol that's already happened - so we're either // going backwards (rebuildParent) or creating a new root after a language change DASHER_ASSERT (!pParent); pNewNode->SetFlag(NF_SEEN, true); } - pNewNode->m_iOffset = iNewOffset; - pNewNode->iContext = iContext; return pNewNode; } bool CAlphabetManager::CSymbolNode::GameSearchNode(string strTargetUtf8Char) { if (m_pMgr->m_pNCManager->GetAlphabet()->GetText(iSymbol) == strTargetUtf8Char) { SetFlag(NF_GAME, true); return true; } return false; } bool CAlphabetManager::CGroupNode::GameSearchNode(string strTargetUtf8Char) { if (GameSearchChildren(strTargetUtf8Char)) { SetFlag(NF_GAME, true); return true; } return false; } CLanguageModel::Context CAlphabetManager::CAlphNode::CloneAlphContext(CLanguageModel *pLanguageModel) { if (iContext) return pLanguageModel->CloneContext(iContext); return CDasherNode::CloneAlphContext(pLanguageModel); } void CAlphabetManager::CSymbolNode::GetContext(CDasherInterfaceBase *pInterface, vector<symbol> &vContextSymbols, int iOffset, int iLength) { if (!GetFlag(NF_SEEN) && iOffset+iLength-1 == m_iOffset) { if (iLength > 1) Parent()->GetContext(pInterface, vContextSymbols, iOffset, iLength-1); vContextSymbols.push_back(iSymbol); } else { CDasherNode::GetContext(pInterface, vContextSymbols, iOffset, iLength); } } symbol CAlphabetManager::CSymbolNode::GetAlphSymbol() { return iSymbol; } void CAlphabetManager::CSymbolNode::PopulateChildren() { m_pMgr->IterateChildGroups(this, NULL, NULL); } int CAlphabetManager::CAlphNode::ExpectedNumChildren() { return m_pMgr->m_pNCManager->GetAlphabet()->iNumChildNodes; } std::vector<unsigned int> *CAlphabetManager::CAlphNode::GetProbInfo() { if (!m_pProbInfo) { m_pProbInfo = new std::vector<unsigned int>(); m_pMgr->m_pNCManager->GetProbs(iContext, *m_pProbInfo, m_pMgr->m_pNCManager->GetLongParameter(LP_NORMALIZATION)); // work out cumulative probs in place for(unsigned int i = 1; i < m_pProbInfo->size(); i++) { (*m_pProbInfo)[i] += (*m_pProbInfo)[i - 1]; } } return m_pProbInfo; } std::vector<unsigned int> *CAlphabetManager::CGroupNode::GetProbInfo() { if (m_pGroup && Parent() && Parent()->mgr() == mgr()) { - DASHER_ASSERT(Parent()->m_iOffset == m_iOffset); + DASHER_ASSERT(Parent()->offset() == offset()); return (static_cast<CAlphNode *>(Parent()))->GetProbInfo(); } //nope, no usable parent. compute here... return CAlphNode::GetProbInfo(); } void CAlphabetManager::CGroupNode::PopulateChildren() { m_pMgr->IterateChildGroups(this, m_pGroup, NULL); } int CAlphabetManager::CGroupNode::ExpectedNumChildren() { return (m_pGroup) ? m_pGroup->iNumChildNodes : CAlphNode::ExpectedNumChildren(); } CAlphabetManager::CGroupNode *CAlphabetManager::CreateGroupNode(CAlphNode *pParent, SGroupInfo *pInfo, unsigned int iLbnd, unsigned int iHbnd) { - // TODO: More sensible structure in group data to map directly to this - CDasherNode::SDisplayInfo *pDisplayInfo = new CDasherNode::SDisplayInfo; - pDisplayInfo->iColour = (pInfo->bVisible ? pInfo->iColour : pParent->GetDisplayInfo()->iColour); - pDisplayInfo->bShove = true; - pDisplayInfo->bVisible = pInfo->bVisible; - pDisplayInfo->strDisplayText = pInfo->strLabel; - - CGroupNode *pNewNode = makeGroup(pParent, iLbnd, iHbnd, pDisplayInfo, pInfo); // When creating a group node... - pNewNode->m_iOffset = pParent->m_iOffset; // ...the offset is the same as the parent... + // ...the offset is the same as the parent... + CGroupNode *pNewNode = makeGroup(pParent, pParent->offset(), iLbnd, iHbnd, pInfo); + + //...as is the context! pNewNode->iContext = m_pLanguageModel->CloneContext(pParent->iContext); return pNewNode; } CAlphabetManager::CGroupNode *CAlphabetManager::CGroupNode::RebuildGroup(CAlphNode *pParent, SGroupInfo *pInfo, unsigned int iLbnd, unsigned int iHbnd) { if (pInfo == m_pGroup) { SetRange(iLbnd, iHbnd); SetParent(pParent); //offset doesn't increase for groups... - DASHER_ASSERT (m_iOffset == pParent->m_iOffset); + DASHER_ASSERT (offset() == pParent->offset()); return this; } CGroupNode *pRet=m_pMgr->CreateGroupNode(pParent, pInfo, iLbnd, iHbnd); if (pInfo->iStart <= m_pGroup->iStart && pInfo->iEnd >= m_pGroup->iEnd) { //created group node should contain this one m_pMgr->IterateChildGroups(pRet,pInfo,this); } return pRet; } CAlphabetManager::CGroupNode *CAlphabetManager::CSymbolNode::RebuildGroup(CAlphNode *pParent, SGroupInfo *pInfo, unsigned int iLbnd, unsigned int iHbnd) { CGroupNode *pRet=m_pMgr->CreateGroupNode(pParent, pInfo, iLbnd, iHbnd); if (pInfo->iStart <= iSymbol && pInfo->iEnd > iSymbol) { m_pMgr->IterateChildGroups(pRet, pInfo, this); } return pRet; } CLanguageModel::Context CAlphabetManager::CreateSymbolContext(CAlphNode *pParent, symbol iSymbol) { CLanguageModel::Context iContext = m_pLanguageModel->CloneContext(pParent->iContext); m_pLanguageModel->EnterSymbol(iContext, iSymbol); // TODO: Don't use symbols? return iContext; } CDasherNode *CAlphabetManager::CreateSymbolNode(CAlphNode *pParent, symbol iSymbol, unsigned int iLbnd, unsigned int iHbnd) { CDasherNode *pNewNode = NULL; //Does not invoke conversion node // TODO: Better way of specifying alternate roots // TODO: Need to fix fact that this is created even when control mode is switched off if(iSymbol == m_pNCManager->GetAlphabet()->GetControlSymbol()) { //ACL setting offset as one more than parent for consistency with "proper" symbol nodes... - pNewNode = m_pNCManager->GetCtrlRoot(pParent, iLbnd, iHbnd, pParent->m_iOffset+1); + pNewNode = m_pNCManager->GetCtrlRoot(pParent, iLbnd, iHbnd, pParent->offset()+1); #ifdef _WIN32_WCE //no control manager - but (TODO!) we still try to create (0-size!) control node... DASHER_ASSERT(!pNewNode); // For now, just hack it so we get a normal root node here pNewNode = m_pNCManager->GetAlphRoot(pParent, iLbnd, iHbnd, false, pParent->m_iOffset+1); #else DASHER_ASSERT(pNewNode); #endif } else if(iSymbol == m_pNCManager->GetAlphabet()->GetStartConversionSymbol()) { // else if(iSymbol == m_pNCManager->GetSpaceSymbol()) { //ACL setting m_iOffset+1 for consistency with "proper" symbol nodes... - pNewNode = m_pNCManager->GetConvRoot(pParent, iLbnd, iHbnd, pParent->m_iOffset+1); + pNewNode = m_pNCManager->GetConvRoot(pParent, iLbnd, iHbnd, pParent->offset()+1); } else { - //compute phase directly from offset - int iColour = m_pNCManager->GetAlphabet()->GetColour(iSymbol, (pParent->m_iOffset+1)%2); - // TODO: Exceptions / error handling in general - CDasherNode::SDisplayInfo *pDisplayInfo = new CDasherNode::SDisplayInfo; - pDisplayInfo->iColour = iColour; - pDisplayInfo->bShove = true; - pDisplayInfo->bVisible = true; - pDisplayInfo->strDisplayText = m_pNCManager->GetAlphabet()->GetDisplayText(iSymbol); - CAlphNode *pAlphNode; - pNewNode = pAlphNode = makeSymbol(pParent, iLbnd, iHbnd, pDisplayInfo,iSymbol); + pNewNode = pAlphNode = makeSymbol(pParent, pParent->offset()+1, iLbnd, iHbnd, iSymbol); // std::stringstream ssLabel; // ssLabel << m_pNCManager->GetAlphabet()->GetDisplayText(iSymbol) << ": " << pNewNode; // pDisplayInfo->strDisplayText = ssLabel.str(); - pNewNode->m_iOffset = pParent->m_iOffset + 1; - pAlphNode->iContext = CreateSymbolContext(pParent, iSymbol); } return pNewNode; } CDasherNode *CAlphabetManager::CSymbolNode::RebuildSymbol(CAlphNode *pParent, symbol iSymbol, unsigned int iLbnd, unsigned int iHbnd) { if(iSymbol == this->iSymbol) { SetRange(iLbnd, iHbnd); SetParent(pParent); - DASHER_ASSERT(m_iOffset == pParent->m_iOffset + 1); + DASHER_ASSERT(offset() == pParent->offset() + 1); return this; } return m_pMgr->CreateSymbolNode(pParent, iSymbol, iLbnd, iHbnd); } CDasherNode *CAlphabetManager::CGroupNode::RebuildSymbol(CAlphNode *pParent, symbol iSymbol, unsigned int iLbnd, unsigned int iHbnd) { return m_pMgr->CreateSymbolNode(pParent, iSymbol, iLbnd, iHbnd); } void CAlphabetManager::IterateChildGroups(CAlphNode *pParent, SGroupInfo *pParentGroup, CAlphNode *buildAround) { std::vector<unsigned int> *pCProb(pParent->GetProbInfo()); const int iMin(pParentGroup ? pParentGroup->iStart : 1); const int iMax(pParentGroup ? pParentGroup->iEnd : pCProb->size()); // TODO: Think through alphabet file formats etc. to make this class easier. // TODO: Throw a warning if parent node already has children // Create child nodes and add them int i(iMin); //lowest index of child which we haven't yet added SGroupInfo *pCurrentNode(pParentGroup ? pParentGroup->pChild : m_pNCManager->GetAlphabet()->m_pBaseGroup); // The SGroupInfo structure has something like linked list behaviour // Each SGroupInfo contains a pNext, a pointer to a sibling group info while (i < iMax) { CDasherNode *pNewChild; bool bSymbol = !pCurrentNode //gone past last subgroup || i < pCurrentNode->iStart; //not reached next subgroup const int iStart=i, iEnd = (bSymbol) ? i+1 : pCurrentNode->iEnd; //uint64 is platform-dependently #defined in DasherTypes.h as an (unsigned) 64-bit int ("__int64" or "long long int") unsigned int iLbnd = (((*pCProb)[iStart-1] - (*pCProb)[iMin-1]) * (uint64)(m_pNCManager->GetLongParameter(LP_NORMALIZATION))) / ((*pCProb)[iMax-1] - (*pCProb)[iMin-1]); unsigned int iHbnd = (((*pCProb)[iEnd-1] - (*pCProb)[iMin-1]) * (uint64)(m_pNCManager->GetLongParameter(LP_NORMALIZATION))) / ((*pCProb)[iMax-1] - (*pCProb)[iMin-1]); //loop for eliding groups with single children (see below). // Variables store necessary properties of any elided groups: std::string groupPrefix=""; int iOverrideColour=-1; SGroupInfo *pInner=pCurrentNode; while (true) { if (bSymbol) { pNewChild = (buildAround) ? buildAround->RebuildSymbol(pParent, i, iLbnd, iHbnd) : CreateSymbolNode(pParent, i, iLbnd, iHbnd); i++; //make one symbol at a time - move onto next symbol in next iteration of (outer) loop break; //exit inner (group elision) loop } else if (pInner->iNumChildNodes>1) { //in/reached nontrivial subgroup - do make node for entire group: pNewChild= (buildAround) ? buildAround->RebuildGroup(pParent, pInner, iLbnd, iHbnd) : CreateGroupNode(pParent, pInner, iLbnd, iHbnd); i = pInner->iEnd; //make one group at a time - so move past entire group... pCurrentNode = pCurrentNode->pNext; //next sibling of _original_ pCurrentNode (above) // (maybe not of pCurrentNode now, which might be a subgroup filling the original) break; //exit inner (group elision) loop } //were about to create a group node, which would have only one child // (eventually, if the group node were PopulateChildren'd). // Such a child would entirely fill it's parent (the group), and thus, // creation/destruction of the child would cause the node's colour to flash // between that for parent group and child. // Hence, instead we elide the group node and create the child _here_... //1. however we also have to take account of the appearance of the elided group. Hence: groupPrefix += pInner->strLabel; if (pInner->bVisible) iOverrideColour=pInner->iColour; //2. now go into the group... pInner = pInner->pChild; bSymbol = (pInner==NULL); //which might contain a single subgroup, or a single symbol if (bSymbol) pCurrentNode = pCurrentNode->pNext; //if a symbol, we've still moved past the outer (elided) group DASHER_ASSERT(iEnd == (bSymbol ? i+1 : pInner->iEnd)); //probability calcs still ok //3. loop round inner loop... } //created a new node - symbol or (group which will have >1 child). DASHER_ASSERT(pParent->GetChildren().back()==pNewChild); //now adjust the node we've actually created, to take account of any elided group(s)... - // ick: cast away const-ness...TODO! - CDasherNode::SDisplayInfo *pChildInfo = (CDasherNode::SDisplayInfo *)pNewChild->GetDisplayInfo(); - if (iOverrideColour!=-1 && !pChildInfo->bVisible) { - pChildInfo->bVisible = true; - pChildInfo->iColour = iOverrideColour; - } - //if we've reused the existing node, make sure we don't adjust the display text twice... - if (pNewChild != buildAround) pChildInfo->strDisplayText = groupPrefix + pChildInfo->strDisplayText; + // tho not if we've reused the existing node, assume that's been adjusted already + if (pNewChild && pNewChild!=buildAround) pNewChild->PrependElidedGroup(iOverrideColour, groupPrefix); } pParent->SetFlag(NF_ALLCHILDREN, true); } CAlphabetManager::CAlphNode::~CAlphNode() { delete m_pProbInfo; m_pMgr->m_pLanguageModel->ReleaseContext(iContext); } const std::string &CAlphabetManager::CSymbolNode::outputText() { return mgr()->m_pNCManager->GetAlphabet()->GetText(iSymbol); } void CAlphabetManager::CSymbolNode::Output(Dasher::VECTOR_SYMBOL_PROB* pAdded, int iNormalization) { //std::cout << this << " " << Parent() << ": Output at offset " << m_iOffset << " *" << m_pMgr->m_pNCManager->GetAlphabet()->GetText(t) << "* " << std::endl; Dasher::CEditEvent oEvent(1, outputText(), m_iOffset); m_pMgr->m_pNCManager->InsertEvent(&oEvent); // Track this symbol and its probability for logging purposes if (pAdded != NULL) { Dasher::SymbolProb sItem; sItem.sym = iSymbol; sItem.prob = Range() / (double)iNormalization; pAdded->push_back(sItem); } } void CAlphabetManager::CSymbolNode::Undo(int *pNumDeleted) { Dasher::CEditEvent oEvent(2, outputText(), m_iOffset); m_pMgr->m_pNCManager->InsertEvent(&oEvent); if (pNumDeleted) (*pNumDeleted)++; } CDasherNode *CAlphabetManager::CGroupNode::RebuildParent() { // CAlphNode's always have a parent, they inserted a symbol; CGroupNode's // with an m_pGroup have a container i.e. the parent group, unless // m_pGroup==NULL => "root" node where Alphabet->m_pBaseGroup is the *first*child*... if (m_pGroup == NULL) return NULL; //offset of group node is same as parent... return CAlphNode::RebuildParent(m_iOffset); } CDasherNode *CAlphabetManager::CSymbolNode::RebuildParent() { //parent's offset is one less than this. return CAlphNode::RebuildParent(m_iOffset-1); } CDasherNode *CAlphabetManager::CAlphNode::RebuildParent(int iNewOffset) { //possible that we have a parent, as RebuildParent() rebuilds back to closest AlphNode. if (Parent()) return Parent(); CAlphNode *pNewNode = m_pMgr->GetRoot(NULL, 0, 0, iNewOffset!=-1, iNewOffset+1); //now fill in the new node - recursively - until it reaches us m_pMgr->IterateChildGroups(pNewNode, NULL, this); //finally return our immediate parent (pNewNode may be an ancestor rather than immediate parent!) DASHER_ASSERT(Parent() != NULL); //although not required, we believe only NF_SEEN nodes are ever requested to rebuild their parents... DASHER_ASSERT(GetFlag(NF_SEEN)); //so set NF_SEEN on all created ancestors (of which pNewNode is the last) CDasherNode *pNode = this; do { pNode = pNode->Parent(); pNode->SetFlag(NF_SEEN, true); } while (pNode != pNewNode); return Parent(); } // TODO: Shouldn't there be an option whether or not to learn as we write? // For want of a better solution, game mode exemption explicit in this function void CAlphabetManager::CSymbolNode::SetFlag(int iFlag, bool bValue) { CDasherNode::SetFlag(iFlag, bValue); switch(iFlag) { case NF_COMMITTED: if(bValue && !GetFlag(NF_GAME) && m_pMgr->m_pInterface->GetBoolParameter(BP_LM_ADAPTIVE)) m_pMgr->m_pLanguageModel->LearnSymbol(m_pMgr->m_iLearnContext, iSymbol); break; } } diff --git a/Src/DasherCore/AlphabetManager.h b/Src/DasherCore/AlphabetManager.h index dc65355..6b98c6b 100644 --- a/Src/DasherCore/AlphabetManager.h +++ b/Src/DasherCore/AlphabetManager.h @@ -1,150 +1,154 @@ // AlphabetManager.h // // Copyright (c) 2007 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #ifndef __alphabetmanager_h__ #define __alphabetmanager_h__ #include "LanguageModelling/LanguageModel.h" #include "DasherNode.h" #include "Parameters.h" #include "NodeManager.h" class CNodeCreationManager; struct SGroupInfo; namespace Dasher { class CDasherInterfaceBase; /// \ingroup Model /// @{ /// Implementation of CNodeManager for regular 'alphabet' nodes, ie /// the basic Dasher behaviour. Child nodes are populated according /// to the appropriate alphabet file, with sizes given by the /// language model. /// class CAlphabetManager : public CNodeManager { public: CAlphabetManager(CDasherInterfaceBase *pInterface, CNodeCreationManager *pNCManager, CLanguageModel *pLanguageModel); protected: class CGroupNode; class CAlphNode : public CDasherNode { public: virtual CAlphabetManager *mgr() {return m_pMgr;} - CAlphNode(CDasherNode *pParent, unsigned int iLbnd, unsigned int iHbnd, CDasherNode::SDisplayInfo *pDispInfo, CAlphabetManager *pMgr); + CAlphNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, int iColour, const std::string &strDisplayText, CAlphabetManager *pMgr); CLanguageModel::Context iContext; /// /// Delete any storage alocated for this node /// virtual ~CAlphNode(); virtual CLanguageModel::Context CloneAlphContext(CLanguageModel *pLanguageModel); CDasherNode *RebuildParent(int iNewOffset); ///Have to call this from CAlphabetManager, and from CGroupNode on a _different_ CAlphNode, hence public... virtual std::vector<unsigned int> *GetProbInfo(); virtual int ExpectedNumChildren(); virtual CDasherNode *RebuildSymbol(CAlphNode *pParent, symbol iSymbol, unsigned int iLbnd, unsigned int iHbnd)=0; virtual CGroupNode *RebuildGroup(CAlphNode *pParent, SGroupInfo *pInfo, unsigned int iLbnd, unsigned int iHbnd)=0; private: std::vector<unsigned int> *m_pProbInfo; protected: CAlphabetManager *m_pMgr; }; class CSymbolNode : public CAlphNode { public: - CSymbolNode(CDasherNode *pParent, unsigned int iLbnd, unsigned int iHbnd, CDasherNode::SDisplayInfo *pDispInfo, CAlphabetManager *pMgr, symbol iSymbol); - + ///Standard constructor, gets colour+label by looking up symbol in current alphabet (& computing phase from offset) + CSymbolNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, CAlphabetManager *pMgr, symbol iSymbol); + /// /// Provide children for the supplied node /// virtual void PopulateChildren(); virtual CDasherNode *RebuildParent(); virtual void Output(Dasher::VECTOR_SYMBOL_PROB* pAdded, int iNormalization); virtual void Undo(int *pNumDeleted); virtual void SetFlag(int iFlag, bool bValue); virtual bool GameSearchNode(std::string strTargetUtf8Char); virtual void GetContext(CDasherInterfaceBase *pInterface, std::vector<symbol> &vContextSymbols, int iOffset, int iLength); virtual symbol GetAlphSymbol(); const symbol iSymbol; virtual CDasherNode *RebuildSymbol(CAlphNode *pParent, symbol iSymbol, unsigned int iLbnd, unsigned int iHbnd); virtual CGroupNode *RebuildGroup(CAlphNode *pParent, SGroupInfo *pInfo, unsigned int iLbnd, unsigned int iHbnd); private: virtual const std::string &outputText(); + protected: + ///Compatibility constructor, so that subclasses can specify their own colour & label + CSymbolNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, int iColour, const std::string &strDisplayText, CAlphabetManager *pMgr, symbol _iSymbol); }; class CGroupNode : public CAlphNode { public: - CGroupNode(CDasherNode *pParent, unsigned int iLbnd, unsigned int iHbnd, CDasherNode::SDisplayInfo *pDispInfo, CAlphabetManager *pMgr, SGroupInfo *pGroup); + CGroupNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, CAlphabetManager *pMgr, SGroupInfo *pGroup); /// /// Provide children for the supplied node /// virtual CDasherNode *RebuildParent(); virtual void PopulateChildren(); virtual int ExpectedNumChildren(); virtual bool GameSearchNode(std::string strTargetUtf8Char); virtual CDasherNode *RebuildSymbol(CAlphNode *pParent, symbol iSymbol, unsigned int iLbnd, unsigned int iHbnd); virtual CGroupNode *RebuildGroup(CAlphNode *pParent, SGroupInfo *pInfo, unsigned int iLbnd, unsigned int iHbnd); std::vector<unsigned int> *GetProbInfo(); private: SGroupInfo *m_pGroup; }; public: /// /// Get a new root node owned by this manager /// bEnteredLast - true if this "root" node should be considered as entering the preceding symbol /// Offset is the index of the character which _child_ nodes (i.e. between which this root allows selection) /// will enter. (Also used to build context for preceding characters.) virtual CAlphNode *GetRoot(CDasherNode *pParent, unsigned int iLower, unsigned int iUpper, bool bEnteredLast, int iOffset); protected: /// /// Factory method for CAlphNode construction, so subclasses can override. /// - virtual CSymbolNode *makeSymbol(CDasherNode *pParent, unsigned int iLbnd, unsigned int iHbnd, CDasherNode::SDisplayInfo *pDispInfo, symbol iSymbol); - virtual CGroupNode *makeGroup(CDasherNode *pParent, unsigned int iLbnd, unsigned int iHbnd, CDasherNode::SDisplayInfo *pDispInfo, SGroupInfo *pGroup); + virtual CSymbolNode *makeSymbol(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, symbol iSymbol); + virtual CGroupNode *makeGroup(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, SGroupInfo *pGroup); virtual CDasherNode *CreateSymbolNode(CAlphNode *pParent, symbol iSymbol, unsigned int iLbnd, unsigned int iHbnd); virtual CLanguageModel::Context CreateSymbolContext(CAlphNode *pParent, symbol iSymbol); virtual CGroupNode *CreateGroupNode(CAlphNode *pParent, SGroupInfo *pInfo, unsigned int iLbnd, unsigned int iHbnd); CLanguageModel *m_pLanguageModel; CNodeCreationManager *m_pNCManager; private: void IterateChildGroups(CAlphNode *pParent, SGroupInfo *pParentGroup, CAlphNode *buildAround); CLanguageModel::Context m_iLearnContext; CDasherInterfaceBase *m_pInterface; }; /// @} } #endif diff --git a/Src/DasherCore/ControlManager.cpp b/Src/DasherCore/ControlManager.cpp index ee64dbc..5589384 100644 --- a/Src/DasherCore/ControlManager.cpp +++ b/Src/DasherCore/ControlManager.cpp @@ -1,405 +1,376 @@ // ControlManager.cpp // // Copyright (c) 2007 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" #include "ControlManager.h" #include <cstring> using namespace Dasher; using namespace std; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG_MEMLEAKS #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif int CControlManager::m_iNextID = 0; CControlManager::CControlManager( CNodeCreationManager *pNCManager ) : m_pNCManager(pNCManager) { string SystemString = m_pNCManager->GetStringParameter(SP_SYSTEM_LOC); string UserLocation = m_pNCManager->GetStringParameter(SP_USER_LOC); m_iNextID = 0; // TODO: Need to fix this on WinCE build #ifndef _WIN32_WCE struct stat sFileInfo; string strFileName = UserLocation + "controllabels.xml"; // check first location for file if(stat(strFileName.c_str(), &sFileInfo) == -1) { // something went wrong strFileName = SystemString + "controllabels.xml"; // check second location for file if(stat(strFileName.c_str(), &sFileInfo) == -1) { // all else fails do something default LoadDefaultLabels(); } else LoadLabelsFromFile(strFileName, sFileInfo.st_size); } else LoadLabelsFromFile(strFileName, sFileInfo.st_size); ConnectNodes(); #endif } int CControlManager::LoadLabelsFromFile(string strFileName, int iFileSize) { // Implement Unicode names via xml from file: char* szFileBuffer = new char[iFileSize]; ifstream oFile(strFileName.c_str()); oFile.read(szFileBuffer, iFileSize); XML_Parser Parser = XML_ParserCreate(NULL); // Members passed as callbacks must be static, so don't have a "this" pointer. // We give them one through horrible casting so they can effect changes. XML_SetUserData(Parser, this); XML_SetElementHandler(Parser, XmlStartHandler, XmlEndHandler); XML_SetCharacterDataHandler(Parser, XmlCDataHandler); XML_Parse(Parser, szFileBuffer, iFileSize, false); // deallocate resources XML_ParserFree(Parser); oFile.close(); delete [] szFileBuffer; return 0; } int CControlManager::LoadDefaultLabels() { // TODO: Need to figure out how to handle offset changes here RegisterNode(CTL_ROOT, "Control", 8); RegisterNode(CTL_STOP, "Stop", 242); RegisterNode(CTL_PAUSE, "Pause", 241); RegisterNode(CTL_MOVE, "Move", -1); RegisterNode(CTL_MOVE_FORWARD, "->", -1); RegisterNode(CTL_MOVE_FORWARD_CHAR, ">", -1); RegisterNode(CTL_MOVE_FORWARD_WORD, ">>", -1); RegisterNode(CTL_MOVE_FORWARD_LINE, ">>>", -1); RegisterNode(CTL_MOVE_FORWARD_FILE, ">>>>", -1); RegisterNode(CTL_MOVE_BACKWARD, "<-", -1); RegisterNode(CTL_MOVE_BACKWARD_CHAR, "<", -1); RegisterNode(CTL_MOVE_BACKWARD_WORD, "<<", -1); RegisterNode(CTL_MOVE_BACKWARD_LINE, "<<<", -1); RegisterNode(CTL_MOVE_BACKWARD_FILE, "<<<<", -1); RegisterNode(CTL_DELETE, "Delete", -1); RegisterNode(CTL_DELETE_FORWARD, "->", -1); RegisterNode(CTL_DELETE_FORWARD_CHAR, ">", -1); RegisterNode(CTL_DELETE_FORWARD_WORD, ">>", -1); RegisterNode(CTL_DELETE_FORWARD_LINE, ">>>", -1); RegisterNode(CTL_DELETE_FORWARD_FILE, ">>>>", -1); RegisterNode(CTL_DELETE_BACKWARD, "<-", -1); RegisterNode(CTL_DELETE_BACKWARD_CHAR, "<", -1); RegisterNode(CTL_DELETE_BACKWARD_WORD, "<<", -1); RegisterNode(CTL_DELETE_BACKWARD_LINE, "<<<", -1); RegisterNode(CTL_DELETE_BACKWARD_FILE, "<<<<", -1); return 0; } int CControlManager::ConnectNodes() { ConnectNode(-1, CTL_ROOT, -2); ConnectNode(CTL_STOP, CTL_ROOT, -2); ConnectNode(CTL_PAUSE, CTL_ROOT, -2); ConnectNode(CTL_MOVE, CTL_ROOT, -2); ConnectNode(CTL_DELETE, CTL_ROOT, -2); ConnectNode(-1, CTL_STOP, -2); ConnectNode(CTL_ROOT, CTL_STOP, -2); ConnectNode(-1, CTL_PAUSE, -2); ConnectNode(CTL_ROOT, CTL_PAUSE, -2); ConnectNode(CTL_MOVE_FORWARD, CTL_MOVE, -2); ConnectNode(CTL_MOVE_BACKWARD, CTL_MOVE, -2); ConnectNode(CTL_MOVE_FORWARD_CHAR, CTL_MOVE_FORWARD, -2); ConnectNode(CTL_MOVE_FORWARD_WORD, CTL_MOVE_FORWARD, -2); ConnectNode(CTL_MOVE_FORWARD_LINE, CTL_MOVE_FORWARD, -2); ConnectNode(CTL_MOVE_FORWARD_FILE, CTL_MOVE_FORWARD, -2); ConnectNode(CTL_ROOT, CTL_MOVE_FORWARD_CHAR, -2); ConnectNode(CTL_MOVE_FORWARD, CTL_MOVE_FORWARD_CHAR, -2); ConnectNode(CTL_MOVE_BACKWARD, CTL_MOVE_FORWARD_CHAR, -2); ConnectNode(CTL_ROOT, CTL_MOVE_FORWARD_WORD, -2); ConnectNode(CTL_MOVE_FORWARD, CTL_MOVE_FORWARD_WORD, -2); ConnectNode(CTL_MOVE_BACKWARD, CTL_MOVE_FORWARD_WORD, -2); ConnectNode(CTL_ROOT, CTL_MOVE_FORWARD_LINE, -2); ConnectNode(CTL_MOVE_FORWARD, CTL_MOVE_FORWARD_LINE, -2); ConnectNode(CTL_MOVE_BACKWARD, CTL_MOVE_FORWARD_LINE, -2); ConnectNode(CTL_ROOT, CTL_MOVE_FORWARD_FILE, -2); ConnectNode(CTL_MOVE_FORWARD, CTL_MOVE_FORWARD_FILE, -2); ConnectNode(CTL_MOVE_BACKWARD, CTL_MOVE_FORWARD_FILE, -2); ConnectNode(CTL_MOVE_BACKWARD_CHAR, CTL_MOVE_BACKWARD, -2); ConnectNode(CTL_MOVE_BACKWARD_WORD, CTL_MOVE_BACKWARD, -2); ConnectNode(CTL_MOVE_BACKWARD_LINE, CTL_MOVE_BACKWARD, -2); ConnectNode(CTL_MOVE_BACKWARD_FILE, CTL_MOVE_BACKWARD, -2); ConnectNode(CTL_ROOT, CTL_MOVE_BACKWARD_CHAR, -2); ConnectNode(CTL_MOVE_FORWARD, CTL_MOVE_BACKWARD_CHAR, -2); ConnectNode(CTL_MOVE_BACKWARD, CTL_MOVE_BACKWARD_CHAR, -2); ConnectNode(CTL_ROOT, CTL_MOVE_BACKWARD_WORD, -2); ConnectNode(CTL_MOVE_FORWARD, CTL_MOVE_BACKWARD_WORD, -2); ConnectNode(CTL_MOVE_BACKWARD, CTL_MOVE_BACKWARD_WORD, -2); ConnectNode(CTL_ROOT, CTL_MOVE_BACKWARD_LINE, -2); ConnectNode(CTL_MOVE_FORWARD, CTL_MOVE_BACKWARD_LINE, -2); ConnectNode(CTL_MOVE_BACKWARD, CTL_MOVE_BACKWARD_LINE, -2); ConnectNode(CTL_ROOT, CTL_MOVE_BACKWARD_FILE, -2); ConnectNode(CTL_MOVE_FORWARD, CTL_MOVE_BACKWARD_FILE, -2); ConnectNode(CTL_MOVE_BACKWARD, CTL_MOVE_BACKWARD_FILE, -2); ConnectNode(CTL_DELETE_FORWARD, CTL_DELETE, -2); ConnectNode(CTL_DELETE_BACKWARD, CTL_DELETE, -2); ConnectNode(CTL_DELETE_FORWARD_CHAR, CTL_DELETE_FORWARD, -2); ConnectNode(CTL_DELETE_FORWARD_WORD, CTL_DELETE_FORWARD, -2); ConnectNode(CTL_DELETE_FORWARD_LINE, CTL_DELETE_FORWARD, -2); ConnectNode(CTL_DELETE_FORWARD_FILE, CTL_DELETE_FORWARD, -2); ConnectNode(CTL_ROOT, CTL_DELETE_FORWARD_CHAR, -2); ConnectNode(CTL_DELETE_FORWARD, CTL_DELETE_FORWARD_CHAR, -2); ConnectNode(CTL_DELETE_BACKWARD, CTL_DELETE_FORWARD_CHAR, -2); ConnectNode(CTL_ROOT, CTL_DELETE_FORWARD_WORD, -2); ConnectNode(CTL_DELETE_FORWARD, CTL_DELETE_FORWARD_WORD, -2); ConnectNode(CTL_DELETE_BACKWARD, CTL_DELETE_FORWARD_WORD, -2); ConnectNode(CTL_ROOT, CTL_DELETE_FORWARD_LINE, -2); ConnectNode(CTL_DELETE_FORWARD, CTL_DELETE_FORWARD_LINE, -2); ConnectNode(CTL_DELETE_BACKWARD, CTL_DELETE_FORWARD_LINE, -2); ConnectNode(CTL_ROOT, CTL_DELETE_FORWARD_FILE, -2); ConnectNode(CTL_DELETE_FORWARD, CTL_DELETE_FORWARD_FILE, -2); ConnectNode(CTL_DELETE_BACKWARD, CTL_DELETE_FORWARD_FILE, -2); ConnectNode(CTL_DELETE_BACKWARD_CHAR, CTL_DELETE_BACKWARD, -2); ConnectNode(CTL_DELETE_BACKWARD_WORD, CTL_DELETE_BACKWARD, -2); ConnectNode(CTL_DELETE_BACKWARD_LINE, CTL_DELETE_BACKWARD, -2); ConnectNode(CTL_DELETE_BACKWARD_FILE, CTL_DELETE_BACKWARD, -2); ConnectNode(CTL_ROOT, CTL_DELETE_BACKWARD_CHAR, -2); ConnectNode(CTL_DELETE_FORWARD, CTL_DELETE_BACKWARD_CHAR, -2); ConnectNode(CTL_DELETE_BACKWARD, CTL_DELETE_BACKWARD_CHAR, -2); ConnectNode(CTL_ROOT, CTL_DELETE_BACKWARD_WORD, -2); ConnectNode(CTL_DELETE_FORWARD, CTL_DELETE_BACKWARD_WORD, -2); ConnectNode(CTL_DELETE_BACKWARD, CTL_DELETE_BACKWARD_WORD, -2); ConnectNode(CTL_ROOT, CTL_DELETE_BACKWARD_LINE, -2); ConnectNode(CTL_DELETE_FORWARD, CTL_DELETE_BACKWARD_LINE, -2); ConnectNode(CTL_DELETE_BACKWARD, CTL_DELETE_BACKWARD_LINE, -2); ConnectNode(CTL_ROOT, CTL_DELETE_BACKWARD_FILE, -2); ConnectNode(CTL_DELETE_FORWARD, CTL_DELETE_BACKWARD_FILE, -2); ConnectNode(CTL_DELETE_BACKWARD, CTL_DELETE_BACKWARD_FILE, -2); return 0; } CControlManager::~CControlManager() { for(std::map<int,SControlItem*>::iterator i = m_mapControlMap.begin(); i != m_mapControlMap.end(); i++) { SControlItem* pNewNode = i->second; if (pNewNode != NULL) { delete pNewNode; pNewNode = NULL; } } } void CControlManager::RegisterNode( int iID, std::string strLabel, int iColour ) { SControlItem *pNewNode; pNewNode = new SControlItem; // FIXME - do constructor sanely pNewNode->strLabel = strLabel; pNewNode->iID = iID; pNewNode->iColour = iColour; m_mapControlMap[iID] = pNewNode; } void CControlManager::ConnectNode(int iChild, int iParent, int iAfter) { // FIXME - iAfter currently ignored (eventually -1 = start, -2 = end) if( iChild == -1 ) {// Corresponds to escaping back to alphabet SControlItem* node = m_mapControlMap[iParent]; if(node) node->vChildren.push_back(NULL); } else m_mapControlMap[iParent]->vChildren.push_back(m_mapControlMap[iChild]); } void CControlManager::DisconnectNode(int iChild, int iParent) { SControlItem* pParentNode = m_mapControlMap[iParent]; SControlItem* pChildNode = m_mapControlMap[iChild]; for(std::vector<SControlItem *>::iterator itChild(pParentNode->vChildren.begin()); itChild != pParentNode->vChildren.end(); ++itChild) if(*itChild == pChildNode) pParentNode->vChildren.erase(itChild); } CDasherNode *CControlManager::GetRoot(CDasherNode *pParent, unsigned int iLower, unsigned int iUpper, int iOffset) { - // TODO: Tie this structure to info contained in control map - CDasherNode::SDisplayInfo *pDisplayInfo = new CDasherNode::SDisplayInfo; - pDisplayInfo->iColour = m_mapControlMap[0]->iColour; - pDisplayInfo->bShove = false; - pDisplayInfo->bVisible = true; - pDisplayInfo->strDisplayText = m_mapControlMap[0]->strLabel; - - CContNode *pNewNode = new CContNode(pParent, iLower, iUpper, pDisplayInfo, this); + CContNode *pNewNode = new CContNode(pParent, iOffset, iLower, iUpper, m_mapControlMap[0], this); // FIXME - handle context properly // pNewNode->SetContext(m_pLanguageModel->CreateEmptyContext()); - pNewNode->pControlItem = m_mapControlMap[0]; - pNewNode->m_iOffset = iOffset; - return pNewNode; } -CControlManager::CContNode::CContNode(CDasherNode *pParent, unsigned int iLbnd, unsigned int iHbnd, CDasherNode::SDisplayInfo *pDisplayInfo, CControlManager *pMgr) -: CDasherNode(pParent, iLbnd, iHbnd, pDisplayInfo), m_pMgr(pMgr) { +CControlManager::CContNode::CContNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, const SControlItem *pControlItem, CControlManager *pMgr) +: CDasherNode(pParent, iOffset, iLbnd, iHbnd, (pControlItem->iColour != -1) ? pControlItem->iColour : (pParent->ChildCount()%99)+11, pControlItem->strLabel), m_pControlItem(pControlItem), m_pMgr(pMgr) { } void CControlManager::CContNode::PopulateChildren() { CDasherNode *pNewNode; - int iNChildren( pControlItem->vChildren.size() ); - - int iIdx(0); - - for(std::vector<SControlItem *>::iterator it(pControlItem->vChildren.begin()); it != pControlItem->vChildren.end(); ++it) { + const unsigned int iNChildren( m_pControlItem->vChildren.size() ); + const unsigned int iNorm(m_pMgr->m_pNCManager->GetLongParameter(LP_NORMALIZATION)); + unsigned int iLbnd(0), iIdx(0); - // FIXME - could do this better + for(std::vector<SControlItem *>::const_iterator it(m_pControlItem->vChildren.begin()); it != m_pControlItem->vChildren.end(); ++it) { - unsigned int iLbnd( iIdx*(m_pMgr->m_pNCManager->GetLongParameter(LP_NORMALIZATION)/iNChildren)); - unsigned int iHbnd( (iIdx+1)*(m_pMgr->m_pNCManager->GetLongParameter(LP_NORMALIZATION)/iNChildren)); + const unsigned int iHbnd((++iIdx*iNorm)/iNChildren); if( *it == NULL ) { // Escape back to alphabet pNewNode = m_pMgr->m_pNCManager->GetAlphRoot(this, iLbnd, iHbnd, false, m_iOffset); } else { - int iColour((*it)->iColour); - - if( iColour == -1 ) { - iColour = (iIdx%99)+11; - } - - CDasherNode::SDisplayInfo *pDisplayInfo = new CDasherNode::SDisplayInfo; - pDisplayInfo->iColour = iColour; - pDisplayInfo->bShove = false; - pDisplayInfo->bVisible = true; - pDisplayInfo->strDisplayText = (*it)->strLabel; - - CContNode *pContNode; - pNewNode = pContNode = new CContNode(this, iLbnd, iHbnd, pDisplayInfo, m_pMgr); - - pContNode->pControlItem = *it; + pNewNode = new CContNode(this, m_iOffset, iLbnd, iHbnd, *it, m_pMgr); - pNewNode->m_iOffset = m_iOffset; } + iLbnd=iHbnd; DASHER_ASSERT(GetChildren().back()==pNewNode); - ++iIdx; } } int CControlManager::CContNode::ExpectedNumChildren() { - return pControlItem->vChildren.size(); + return m_pControlItem->vChildren.size(); } void CControlManager::CContNode::Output(Dasher::VECTOR_SYMBOL_PROB* pAdded, int iNormalization ) { - CControlEvent oEvent(pControlItem->iID); + CControlEvent oEvent(m_pControlItem->iID); // TODO: Need to reimplement this // m_pNCManager->m_bContextSensitive=false; m_pMgr->m_pNCManager->InsertEvent(&oEvent); } void CControlManager::CContNode::Enter() { // Slow down to half the speed we were at m_pMgr->m_pNCManager->SetLongParameter(LP_BOOSTFACTOR, 50); //Disable auto speed control! m_pMgr->bDisabledSpeedControl = m_pMgr->m_pNCManager->GetBoolParameter(BP_AUTO_SPEEDCONTROL); m_pMgr->m_pNCManager->SetBoolParameter(BP_AUTO_SPEEDCONTROL, 0); } void CControlManager::CContNode::Leave() { // Now speed back up, by doubling the speed we were at in control mode m_pMgr->m_pNCManager->SetLongParameter(LP_BOOSTFACTOR, 100); //Re-enable auto speed control! if (m_pMgr->bDisabledSpeedControl) { m_pMgr->bDisabledSpeedControl = false; m_pMgr->m_pNCManager->SetBoolParameter(BP_AUTO_SPEEDCONTROL, 1); } } void CControlManager::XmlStartHandler(void *pUserData, const XML_Char *szName, const XML_Char **aszAttr) { int colour=-1; string str; if(0==strcmp(szName, "label")) { for(int i = 0; aszAttr[i]; i += 2) { if(0==strcmp(aszAttr[i],"value")) { str = string(aszAttr[i+1]); } if(0==strcmp(aszAttr[i],"color")) { colour = atoi(aszAttr[i+1]); } } ((CControlManager*)pUserData)->RegisterNode(CControlManager::m_iNextID++, str, colour); } } void CControlManager::XmlEndHandler(void *pUserData, const XML_Char *szName) { return; } void CControlManager::XmlCDataHandler(void *pUserData, const XML_Char *szData, int iLength){ return; } void CControlManager::CContNode::SetControlOffset(int iOffset) { m_iOffset = iOffset; } diff --git a/Src/DasherCore/ControlManager.h b/Src/DasherCore/ControlManager.h index dc01666..9593e0e 100644 --- a/Src/DasherCore/ControlManager.h +++ b/Src/DasherCore/ControlManager.h @@ -1,133 +1,135 @@ // ControlManager.h // // Copyright (c) 2007 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #ifndef __controlmanager_h__ #define __controlmanager_h__ #include "DasherModel.h" #include "DasherNode.h" #include "Event.h" #include "NodeManager.h" #include <vector> #include <map> #include <fstream> #include <iostream> #ifndef _WIN32_WCE #include <sys/stat.h> #endif #include <string> #include <expat.h> using namespace std; namespace Dasher { class CDasherModel; /// \ingroup Model /// @{ /// A node manager which deals with control nodes. /// Currently can only have one instance due to use /// of static members for callbacks from expat. /// class CControlManager : public CNodeManager { public: enum { CTL_ROOT, CTL_STOP, CTL_PAUSE, CTL_MOVE, CTL_MOVE_FORWARD, CTL_MOVE_FORWARD_CHAR, CTL_MOVE_FORWARD_WORD, CTL_MOVE_FORWARD_LINE, CTL_MOVE_FORWARD_FILE, CTL_MOVE_BACKWARD, CTL_MOVE_BACKWARD_CHAR, CTL_MOVE_BACKWARD_WORD, CTL_MOVE_BACKWARD_LINE, CTL_MOVE_BACKWARD_FILE, CTL_DELETE, CTL_DELETE_FORWARD, CTL_DELETE_FORWARD_CHAR, CTL_DELETE_FORWARD_WORD, CTL_DELETE_FORWARD_LINE, CTL_DELETE_FORWARD_FILE, CTL_DELETE_BACKWARD, CTL_DELETE_BACKWARD_CHAR, CTL_DELETE_BACKWARD_WORD, CTL_DELETE_BACKWARD_LINE, CTL_DELETE_BACKWARD_FILE, CTL_USER }; CControlManager(CNodeCreationManager *pNCManager); ~CControlManager(); /// /// Get a new root node owned by this manager /// virtual CDasherNode *GetRoot(CDasherNode *pParent, unsigned int iLower, unsigned int iUpper, int iOffset); void RegisterNode( int iID, std::string strLabel, int iColour ); void ConnectNode(int iChild, int iParent, int iAfter); void DisconnectNode(int iChild, int iParent); private: struct SControlItem { std::vector<SControlItem *> vChildren; std::string strLabel; int iID; int iColour; }; class CContNode : public CDasherNode { public: CControlManager *mgr() {return m_pMgr;} - CContNode(CDasherNode *pParent, unsigned int iLbnd, unsigned int iHbnd, CDasherNode::SDisplayInfo *pDisplayInfo, CControlManager *pMgr); + CContNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, const SControlItem *pControlItem, CControlManager *pMgr); + + bool bShove() {return false;} /// /// Provide children for the supplied node /// virtual void PopulateChildren(); virtual int ExpectedNumChildren(); virtual void Output(Dasher::VECTOR_SYMBOL_PROB* pAdded, int iNormalization ); virtual void Enter(); virtual void Leave(); void SetControlOffset(int iOffset); - SControlItem *pControlItem; + const SControlItem *m_pControlItem; private: CControlManager *m_pMgr; }; static void XmlStartHandler(void *pUserData, const XML_Char *szName, const XML_Char **aszAttr); static void XmlEndHandler(void *pUserData, const XML_Char *szName); static void XmlCDataHandler(void *pUserData, const XML_Char *szData, int iLength); int LoadLabelsFromFile(string strFileName, int iFileSize); int LoadDefaultLabels(); int ConnectNodes(); static int m_iNextID; CNodeCreationManager *m_pNCManager; std::map<int,SControlItem*> m_mapControlMap; ///Whether we'd temporarily disabled Automatic Speed Control ///(if _and only if_ so, should re-enable it when leaving a node) bool bDisabledSpeedControl; }; /// @} } #endif diff --git a/Src/DasherCore/ConversionHelper.cpp b/Src/DasherCore/ConversionHelper.cpp index 7ec9f2e..2dc38ea 100644 --- a/Src/DasherCore/ConversionHelper.cpp +++ b/Src/DasherCore/ConversionHelper.cpp @@ -1,227 +1,219 @@ // ConversionHelper.cpp // // Copyright (c) 2007 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #ifdef HAVE_CONFIG_H #include <config.h> #endif #include "ConversionHelper.h" #include "Event.h" #include "EventHandler.h" #include "NodeCreationManager.h" #include "DasherNode.h" #include <iostream> #include <cstring> #include <string> #include <vector> #include <stdlib.h> //Note the new implementation in Mandarin Dasher may not be compatible with the previous implementation of Japanese Dasher //Need to reconcile (a small project) using namespace Dasher; +using namespace std; CConversionHelper::CConversionHelper(CNodeCreationManager *pNCManager, CAlphabet *pAlphabet, CLanguageModel *pLanguageModel) : CConversionManager(pNCManager, pAlphabet), m_pLanguageModel(pLanguageModel) { colourStore[0][0]=66;//light blue colourStore[0][1]=64;//very light green colourStore[0][2]=62;//light yellow colourStore[1][0]=78;//light purple colourStore[1][1]=81;//brownish colourStore[1][2]=60;//red m_iLearnContext = m_pLanguageModel->CreateEmptyContext(); } CConversionManager::CConvNode *CConversionHelper::GetRoot(CDasherNode *pParent, unsigned int iLower, unsigned int iUpper, int iOffset) { CConvNode *pConvNode = CConversionManager::GetRoot(pParent, iLower, iUpper, iOffset); //note that pConvNode is actually a CConvHNode, created by this CConversionHelper: // the overridden CConversionManager::GetRoot creates the node the node it returns // by calling makeNode(), which we override to create a CConvHNode, and then just // fills in some of the fields; however, short of duplicating the code of // CConversionManager::GetRoot here, we can't get the type to reflect that... pConvNode->pLanguageModel = m_pLanguageModel; // context of a conversion node (e.g. ^) is the context of the // letter (e.g. e) before it (as the ^ entails replacing the e with // a single accented character e-with-^) pConvNode->iContext = pParent->CloneAlphContext(m_pLanguageModel); return pConvNode; } // TODO: This function needs to be significantly tidied up // TODO: get rid of pSizes void CConversionHelper::AssignChildSizes(const std::vector<SCENode *> &nodes, CLanguageModel::Context context) { AssignSizes(nodes, context, m_pNCManager->GetLongParameter(LP_NORMALIZATION), m_pNCManager->GetLongParameter(LP_UNIFORM)); } void CConversionHelper::CConvHNode::PopulateChildren() { DASHER_ASSERT(mgr()->m_pNCManager); // Do the conversion and build the tree (lattice) if it hasn't been // done already. // if(bisRoot && !pSCENode) { mgr()->BuildTree(this); } if(pSCENode && !pSCENode->GetChildren().empty()) { const std::vector<SCENode *> &vChildren = pSCENode->GetChildren(); // RecursiveDumpTree(pSCENode, 1); mgr()->AssignChildSizes(vChildren, iContext); int iIdx(0); int iCum(0); // int parentClr = pNode->Colour(); // TODO: Fixme int parentClr = 0; // Finally loop through and create the children for (std::vector<SCENode *>::const_iterator it = vChildren.begin(); it!=vChildren.end(); it++) { // std::cout << "Current scec: " << pCurrentSCEChild << std::endl; SCENode *pCurrentSCEChild(*it); DASHER_ASSERT(pCurrentSCEChild != NULL); unsigned int iLbnd(iCum); unsigned int iHbnd(iCum + pCurrentSCEChild->NodeSize); //m_pNCManager->GetLongParameter(LP_NORMALIZATION));// iCum = iHbnd; // TODO: Parameters here are placeholders - need to figure out // what's right - - CDasherNode::SDisplayInfo *pDisplayInfo = new CDasherNode::SDisplayInfo; - pDisplayInfo->iColour = mgr()->AssignColour(parentClr, pCurrentSCEChild, iIdx); - pDisplayInfo->bShove = true; - pDisplayInfo->bVisible = true; - // std::cout << "#" << pCurrentSCEChild->pszConversion << "#" << std::endl; - pDisplayInfo->strDisplayText = pCurrentSCEChild->pszConversion; - - CConvNode *pNewNode = mgr()->makeNode(this, iLbnd, iHbnd, pDisplayInfo); + CConvNode *pNewNode = mgr()->makeNode(this, m_iOffset+1, iLbnd, iHbnd, mgr()->AssignColour(parentClr, pCurrentSCEChild, iIdx), string(pCurrentSCEChild->pszConversion)); // TODO: Reimplement ---- // FIXME - handle context properly // pNewNode->SetContext(m_pLanguageModel->CreateEmptyContext()); // ----- pNewNode->bisRoot = false; pNewNode->pSCENode = pCurrentSCEChild; pNewNode->pLanguageModel = pLanguageModel; - pNewNode->m_iOffset = m_iOffset + 1; if(pLanguageModel) { CLanguageModel::Context iContext; iContext = pLanguageModel->CloneContext(this->iContext); if(pCurrentSCEChild ->Symbol !=-1) pNewNode->pLanguageModel->EnterSymbol(iContext, pCurrentSCEChild->Symbol); // TODO: Don't use symbols? pNewNode->iContext = iContext; } DASHER_ASSERT(GetChildren().back()==pNewNode); ++iIdx; } } else {//End of conversion -> default to alphabet //Phil// // TODO: Placeholder algorithm here // TODO: Add an 'end of conversion' node? //ACL 1/12/09 Note that this adds one to the m_iOffset of the created node // (whereas code that was here did not, but was otherwise identical to // superclass method...?) CConvNode::PopulateChildren(); } } int CConversionHelper::CConvHNode::ExpectedNumChildren() { if(bisRoot && !pSCENode) mgr()->BuildTree(this); if (pSCENode && !pSCENode->GetChildren().empty()) return pSCENode->GetChildren().size(); return CConvNode::ExpectedNumChildren(); } void CConversionHelper::BuildTree(CConvHNode *pRoot) { // Build the string to convert. std::string strCurrentString; // Search backwards but stop at any conversion node. for (CDasherNode *pNode = pRoot->Parent(); pNode && pNode->mgr() == this; pNode = pNode->Parent()) { // TODO: Need to make this the edit text rather than the display text strCurrentString = m_pAlphabet->GetText(pNode->GetAlphSymbol()) + strCurrentString; } // Handle/store the result. SCENode *pStartTemp; Convert(strCurrentString, &pStartTemp); // Store all conversion trees (SCENode trees) in the pUserData->pSCENode // of each Conversion Root. pRoot->pSCENode = pStartTemp; } -CConversionHelper::CConvHNode::CConvHNode(CDasherNode *pParent, unsigned int iLbnd, unsigned int iHbnd, CDasherNode::SDisplayInfo *pDispInfo, CConversionHelper *pMgr) -: CConvNode(pParent, iLbnd, iHbnd, pDispInfo, pMgr) { +CConversionHelper::CConvHNode::CConvHNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, int iColour, const string &strDisplayText, CConversionHelper *pMgr) +: CConvNode(pParent, iOffset, iLbnd, iHbnd, iColour, strDisplayText, pMgr) { } -CConversionHelper::CConvHNode *CConversionHelper::makeNode(CDasherNode *pParent, unsigned int iLbnd, unsigned int iHbnd, CDasherNode::SDisplayInfo *pDispInfo) { - return new CConvHNode(pParent, iLbnd, iHbnd, pDispInfo, this); +CConversionHelper::CConvHNode *CConversionHelper::makeNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, int iColour, const string &strDisplayText) { + return new CConvHNode(pParent, iOffset, iLbnd, iHbnd, iColour, strDisplayText, this); } void CConversionHelper::CConvHNode::SetFlag(int iFlag, bool bValue) { CDasherNode::SetFlag(iFlag, bValue); switch(iFlag) { case NF_COMMITTED: if(bValue){ if(!pSCENode) return; symbol s =pSCENode ->Symbol; if(s!=-1) pLanguageModel->LearnSymbol(mgr()->m_iLearnContext, s); } break; } } diff --git a/Src/DasherCore/ConversionHelper.h b/Src/DasherCore/ConversionHelper.h index ec7efc5..76080b8 100644 --- a/Src/DasherCore/ConversionHelper.h +++ b/Src/DasherCore/ConversionHelper.h @@ -1,148 +1,148 @@ // ConversionHelper.h // // Copyright (c) 2007 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #ifndef __CONVERSION_HELPER_H__ #define __CONVERSION_HELPER_H__ #include "ConversionManager.h" #include <string> #include <vector> #include "SCENode.h" #include "LanguageModelling/LanguageModel.h" #include "LanguageModelling/PPMLanguageModel.h" namespace Dasher{ class CDasherNode; //forward declaration /// \ingroup Model /// @{ /// The CConversionHelper class represents the language specific /// aspect of the conversion process. Each CConversionManager /// references one helper, which performs the conversion itself, as /// well as assigning weights to each of the predictions. See /// CConversionManager for further details of the conversion process. /// class CConversionHelper : public CConversionManager { public: CConversionHelper(CNodeCreationManager *pNCManager, CAlphabet *pAlphabet, CLanguageModel *pLanguageModel); /// Convert a given string to a lattice of candidates. Sizes for /// candidates aren't assigned at this point. The input string /// should be UTF-8 encoded. /// /// @param strSource UTF-8 encoded input string. /// @param pRoot Used to return the root of the conversion lattice. /// @param childCount Unsure - document this. /// @param CMid A unique identifier for the conversion helper 'context'. /// /// @return True if conversion succeeded, false otherwise virtual bool Convert(const std::string &strSource, SCENode ** pRoot) = 0; /// Assign sizes to the children of a given conversion node. This /// happens when the conversion manager populates the children of /// the Dasher node so as to avoid unnecessary computation. /// /// @param pStart The parent of the nodes to be sized. /// @param context Unsure - document this, shouldn't be in general class (include userdata pointer). /// @param normalization Normalisation constant for the child sizes (TODO: check that this is a sensible value, ie the same as Dasher normalisation). /// @param uniform Unsure - document this. /// virtual void AssignSizes(const std::vector<SCENode *> &vChildren, Dasher::CLanguageModel::Context context, long normalization, int uniform)=0; /// Assign colours to the children of a given conversion node. /// This function needs a rethink. /// /// @param parentClr /// @param pNode /// @param childIndex /// /// @return /// virtual int AssignColour(int parentClr, SCENode * pNode, int childIndex) { int which = -1; for (int i=0; i<2; i++) for(int j=0; j<3; j++) if (parentClr == colourStore[i][j]) which = i; if(which == -1) return colourStore[0][childIndex%3]; else if(which == 0) return colourStore[1][childIndex%3]; else return colourStore[0][childIndex%3]; }; /// /// Get a new root node owned by this manager /// virtual CConvNode *GetRoot(CDasherNode *pParent, unsigned int iLower, unsigned int iUpper, int iOffset); /// /// Calculate sizes for each of the children - default /// implementation assigns decending probabilities in a power law /// fashion (so assumes ordering), but specific subclasses are /// free to implement their own behaviour. The only restriction is /// that sizes should be positive and sum to the appropriate /// normalisation constant /// virtual void AssignChildSizes(const std::vector<SCENode *> &vChildren, CLanguageModel::Context context); protected: class CConvHNode : public CConvNode { public: - CConvHNode(CDasherNode *pParent, unsigned int iLbnd, unsigned int iHbnd, CDasherNode::SDisplayInfo *pDispInfo, CConversionHelper *pMgr); + CConvHNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, int iColour, const std::string &strDisplayText, CConversionHelper *pMgr); /// /// Provide children for the supplied node /// virtual void PopulateChildren(); virtual int ExpectedNumChildren(); virtual void SetFlag(int iFlag, bool bValue); protected: inline CConversionHelper *mgr() {return static_cast<CConversionHelper *>(m_pMgr);} }; - virtual CConvHNode *makeNode(CDasherNode *pParent, unsigned int iLbnd, unsigned int iHbnd, CDasherNode::SDisplayInfo *pDispInfo); + virtual CConvHNode *makeNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, int iColour, const std::string &strDisplayText); /// /// Build the conversion tree (lattice) for the given string - /// evaluated late to prevent unnecessary conversions when the /// children of the root node are never instantiated /// virtual void BuildTree(CConvHNode *pRoot); virtual Dasher::CLanguageModel *GetLanguageModel() { return m_pLanguageModel; } private: CLanguageModel *m_pLanguageModel; CLanguageModel::Context m_iLearnContext; int colourStore[2][3]; }; /// @} } #endif diff --git a/Src/DasherCore/ConversionManager.cpp b/Src/DasherCore/ConversionManager.cpp index 183a5ec..66729fc 100644 --- a/Src/DasherCore/ConversionManager.cpp +++ b/Src/DasherCore/ConversionManager.cpp @@ -1,200 +1,195 @@ // ConversionManager.cpp // // Copyright (c) 2007 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #ifdef HAVE_CONFIG_H #include <config.h> #endif #include "ConversionManager.h" #include "Event.h" #include "EventHandler.h" #include "NodeCreationManager.h" #include "DasherModel.h" #include <iostream> #include <cstring> #include <string> #include <vector> #include <stdlib.h> //Note the new implementation in Mandarin Dasher may not be compatible with the previous implementation of Japanese Dasher //Need to reconcile (a small project) using namespace Dasher; +using namespace std; CConversionManager::CConversionManager(CNodeCreationManager *pNCManager, CAlphabet *pAlphabet) { m_pNCManager = pNCManager; m_pAlphabet = pAlphabet; m_iRefCount = 1; //Testing for alphabet details, delete if needed: /* int alphSize = pNCManager->GetAlphabet()->GetNumberSymbols(); std::cout<<"Alphabet size: "<<alphSize<<std::endl; for(int i =0; i<alphSize; i++) std::cout<<"symbol: "<<i<<" display text:"<<pNCManager->GetAlphabet()->GetDisplayText(i)<<std::endl; */ } -CConversionManager::CConvNode *CConversionManager::makeNode(CDasherNode *pParent, unsigned int iLbnd, unsigned int iHbnd, CDasherNode::SDisplayInfo *pDispInfo) { - return new CConvNode(pParent, iLbnd, iHbnd, pDispInfo, this); +CConversionManager::CConvNode *CConversionManager::makeNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, int iColour, const string &strDisplayText) { + return new CConvNode(pParent, iOffset, iLbnd, iHbnd, iColour, strDisplayText, this); } CConversionManager::CConvNode *CConversionManager::GetRoot(CDasherNode *pParent, unsigned int iLower, unsigned int iUpper, int iOffset) { // TODO: Parameters here are placeholders - need to figure out what's right - CDasherNode::SDisplayInfo *pDisplayInfo = new CDasherNode::SDisplayInfo; - pDisplayInfo->iColour = 9; // TODO: Hard coded value - pDisplayInfo->bShove = true; - pDisplayInfo->bVisible = true; - pDisplayInfo->strDisplayText = ""; // TODO: Hard coded value, needs i18n - - CConvNode *pNewNode = makeNode(pParent, iLower, iUpper, pDisplayInfo); + //TODO: hard-coded colour, and hard-coded displaytext... (ACL: read from Alphabet -> startConversionSymbol ?) + CConvNode *pNewNode = makeNode(pParent, iOffset, iLower, iUpper, 9, ""); // FIXME - handle context properly // TODO: Reimplemnt ----- // pNewNode->SetContext(m_pLanguageModel->CreateEmptyContext()); // ----- pNewNode->bisRoot = true; - pNewNode->m_iOffset = iOffset; pNewNode->pLanguageModel = NULL; pNewNode->pSCENode = 0; return pNewNode; } -CConversionManager::CConvNode::CConvNode(CDasherNode *pParent, unsigned int iLbnd, unsigned int iHbnd, CDasherNode::SDisplayInfo *pDispInfo, CConversionManager *pMgr) - : CDasherNode(pParent, iLbnd, iHbnd, pDispInfo), m_pMgr(pMgr) { +CConversionManager::CConvNode::CConvNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, int iColour, const string &strDisplayText, CConversionManager *pMgr) + : CDasherNode(pParent, iOffset, iLbnd, iHbnd, iColour, strDisplayText), m_pMgr(pMgr) { pMgr->m_iRefCount++; } void CConversionManager::CConvNode::PopulateChildren() { DASHER_ASSERT(m_pMgr->m_pNCManager); // If no helper class is present then just drop straight back to an // alphabet root. This should only happen in error cases, and the // user should have been warned here. // unsigned int iLbnd(0); unsigned int iHbnd(m_pMgr->m_pNCManager->GetLongParameter(LP_NORMALIZATION)); CDasherNode *pNewNode = m_pMgr->m_pNCManager->GetAlphRoot(this, iLbnd, iHbnd, false, m_iOffset + 1); DASHER_ASSERT(GetChildren().back()==pNewNode); } int CConversionManager::CConvNode::ExpectedNumChildren() { return 1; //the alphabet root } CConversionManager::CConvNode::~CConvNode() { pLanguageModel->ReleaseContext(iContext); m_pMgr->Unref(); } void CConversionManager::RecursiveDumpTree(SCENode *pCurrent, unsigned int iDepth) { const std::vector<SCENode *> &children = pCurrent->GetChildren(); for (std::vector<SCENode *>::const_iterator it = children.begin(); it!=children.end(); it++) { SCENode *pCurrent(*it); for(unsigned int i(0); i < iDepth; ++i) std::cout << "-"; std::cout << " " << pCurrent->pszConversion << std::endl;//" " << pCurrent->IsHeadAndCandNum << " " << pCurrent->CandIndex << " " << pCurrent->IsComplete << " " << pCurrent->AcCharCount << std::endl; RecursiveDumpTree(pCurrent, iDepth + 1); } } void CConversionManager::CConvNode::GetContext(CDasherInterfaceBase *pInterface, std::vector<symbol> &vContextSymbols, int iOffset, int iLength) { if (!GetFlag(NF_SEEN) && iOffset+iLength-1 == m_iOffset) { //ACL I'm extrapolating from PinYinConversionHelper (in which root nodes have their // Symbol set by SetConvSymbol, and child nodes are created in PopulateChildren // from SCENode's with Symbols having been set in in AssignSizes); not really sure // whether this is applicable in the general case(! - but although I think it's right // for PinYin, it wouldn't actually be used there, as MandarinDasher overrides contexts // everywhere!) DASHER_ASSERT(bisRoot || pSCENode); if (bisRoot || pSCENode->Symbol!=-1) { if (iLength>1) Parent()->GetContext(pInterface, vContextSymbols, iOffset, iLength-1); vContextSymbols.push_back(bisRoot ? iSymbol : pSCENode->Symbol); return; } //else, non-root with pSCENode->Symbol==-1 => fallthrough back to superclass code } CDasherNode::GetContext(pInterface, vContextSymbols, iOffset, iLength); } void CConversionManager::CConvNode::Output(Dasher::VECTOR_SYMBOL_PROB* pAdded, int iNormalization) { // TODO: Reimplement this // m_pNCManager->m_bContextSensitive = true; SCENode *pCurrentSCENode(pSCENode); if(pCurrentSCENode){ Dasher::CEditEvent oEvent(1, pCurrentSCENode->pszConversion, m_iOffset); m_pMgr->m_pNCManager->InsertEvent(&oEvent); if((GetChildren())[0]->mgr() == m_pMgr) { if (static_cast<CConvNode *>(GetChildren()[0])->m_pMgr == m_pMgr) { Dasher::CEditEvent oEvent(11, "", 0); m_pMgr->m_pNCManager->InsertEvent(&oEvent); } } } else { if(!bisRoot) { Dasher::CEditEvent oOPEvent(1, "|", m_iOffset); m_pMgr->m_pNCManager->InsertEvent(&oOPEvent); } else { Dasher::CEditEvent oOPEvent(1, ">", m_iOffset); m_pMgr->m_pNCManager->InsertEvent(&oOPEvent); } Dasher::CEditEvent oEvent(10, "", 0); m_pMgr->m_pNCManager->InsertEvent(&oEvent); } } void CConversionManager::CConvNode::Undo(int *pNumDeleted) { //ACL note: possibly ought to update pNumDeleted here if non-null, // but conversion symbols were not logged by old code so am not starting now! SCENode *pCurrentSCENode(pSCENode); if(pCurrentSCENode) { if(pCurrentSCENode->pszConversion && (strlen(pCurrentSCENode->pszConversion) > 0)) { Dasher::CEditEvent oEvent(2, pCurrentSCENode->pszConversion, m_iOffset); m_pMgr->m_pNCManager->InsertEvent(&oEvent); } } else { if(!bisRoot) { Dasher::CEditEvent oOPEvent(2, "|", m_iOffset); m_pMgr->m_pNCManager->InsertEvent(&oOPEvent); } else { Dasher::CEditEvent oOPEvent(2, ">", m_iOffset); m_pMgr->m_pNCManager->InsertEvent(&oOPEvent); } } } diff --git a/Src/DasherCore/ConversionManager.h b/Src/DasherCore/ConversionManager.h index 146304b..ff2c1ed 100644 --- a/Src/DasherCore/ConversionManager.h +++ b/Src/DasherCore/ConversionManager.h @@ -1,157 +1,157 @@ // ConversionManager.h // // Copyright (c) 2007 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #ifndef __conversion_manager_h__ #define __conversion_manager_h__ #include "DasherTypes.h" #include "LanguageModelling/LanguageModel.h" // Urgh - we really shouldn't need to know about language models here #include "DasherNode.h" #include "SCENode.h" #include "NodeManager.h" // TODO: Conversion manager needs to deal with offsets and contexts - Will: See Phil for an explanation. class CNodeCreationManager; namespace Dasher { /// \ingroup Model /// @{ /// This class manages nodes in conversion subtrees, typically used /// for languages where complex characters are entered through a /// composition process, for example Japanese and Chinese. /// /// A new CConversionManager is created for each subtree, and /// therefore represents the conversion of a single phrase. The /// phrase to be converted is read by recursing through the parent /// tree. An instance of CConversionHelper is shared by several /// CConversionManagers, and performs the language dependent aspects /// of conversion. Specifically construction of the candidate /// lattice and assignment of weights. /// /// The general policy is to delay computation as far as possible, /// to avoid unnecessary computational load. The candidate lattice /// is therefore built at the first call to PopulateChildren, and /// weights are only assigned when the appropriate node has its /// child list populated. /// /// See CConversionHelper for details of the language specific /// aspects of conversion, and CNodeManager for details of the node /// management process. /// class CConversionManager : public CNodeManager { public: // TODO: We shouldn't need to know about this stuff, but the code is somewhat in knots at the moment CConversionManager(CNodeCreationManager *pNCManager, CAlphabet *pAlphabet); /// /// Decrement reference count /// virtual void Unref() { --m_iRefCount; // std::cout << "Unref, new count = " << m_iRefCount << std::endl; if(m_iRefCount == 0) { // std::cout << "Deleting " << this << std::endl; delete this; } }; protected: class CConvNode : public CDasherNode { public: CConversionManager *mgr() {return m_pMgr;} - CConvNode(CDasherNode *pParent, unsigned int iLbnd, unsigned int iHbnd, CDasherNode::SDisplayInfo *pDispInfo, CConversionManager *pMgr); + CConvNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, int iColour, const std::string &strDisplayText, CConversionManager *pMgr); /// /// Provide children for the supplied node /// virtual void PopulateChildren(); virtual int ExpectedNumChildren(); ~CConvNode(); ///Attempts to fill vContextSymbols with the context that would exist _after_ this node has been entered void GetContext(CDasherInterfaceBase *pInterface, std::vector<symbol> &vContextSymbols, int iOffset, int iLength); /// /// Called whenever a node belonging to this manager first /// moves under the crosshair /// virtual void Output(Dasher::VECTOR_SYMBOL_PROB* pAdded, int iNormalization); /// /// Called when a node is left backwards /// virtual void Undo(int *pNumDeleted); protected: CConversionManager *m_pMgr; public: //to ConversionManager and subclasses only, of course... //TODO: REVISE symbol iSymbol; // int iPhase; CLanguageModel *pLanguageModel; CLanguageModel::Context iContext; SCENode * pSCENode; bool bisRoot; // True for root conversion nodes //int iGameOffset; }; public: /// /// Get a new root node owned by this manager /// virtual CConvNode *GetRoot(CDasherNode *pParent, unsigned int iLower, unsigned int iUpper, int iOffset); protected: - virtual CConvNode *makeNode(CDasherNode *pParent, unsigned int iLbnd, unsigned int iHbnd, CDasherNode::SDisplayInfo *pDispInfo); + virtual CConvNode *makeNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, int iColour, const std::string &strDisplayText); CNodeCreationManager *m_pNCManager; CAlphabet *m_pAlphabet; private: /// /// Dump tree to stdout (debug) /// void RecursiveDumpTree(SCENode *pCurrent, unsigned int iDepth); /// /// Reference count /// int m_iRefCount; }; /// @} } #endif diff --git a/Src/DasherCore/DasherModel.cpp b/Src/DasherCore/DasherModel.cpp index 5430cb8..536ea35 100644 --- a/Src/DasherCore/DasherModel.cpp +++ b/Src/DasherCore/DasherModel.cpp @@ -86,725 +86,725 @@ CDasherModel::CDasherModel(CEventHandler *pEventHandler, int iNormalization = GetLongParameter(LP_NORMALIZATION); m_Rootmin_min = int64_min / iNormalization / 2; m_Rootmax_max = int64_max / iNormalization / 2; InitialiseAtOffset(iOffset, pView); } CDasherModel::~CDasherModel() { if (m_pLastOutput) m_pLastOutput->Leave(); if(oldroots.size() > 0) { delete oldroots[0]; oldroots.clear(); // At this point we have also deleted the root - so better NULL pointer m_Root = NULL; } else { delete m_Root; m_Root = NULL; } } void CDasherModel::HandleEvent(Dasher::CEvent *pEvent) { CFrameRate::HandleEvent(pEvent); if(pEvent->m_iEventType == EV_PARAM_NOTIFY) { Dasher::CParameterNotificationEvent * pEvt(static_cast < Dasher::CParameterNotificationEvent * >(pEvent)); switch (pEvt->m_iParameter) { case BP_CONTROL_MODE: // Rebuild the model if control mode is switched on/off RebuildAroundCrosshair(); break; case BP_SMOOTH_OFFSET: if (!GetBoolParameter(BP_SMOOTH_OFFSET)) //smoothing has just been turned off. End any transition/jump currently // in progress at it's current point AbortOffset(); break; case BP_DASHER_PAUSED: if(GetBoolParameter(BP_SLOW_START)) TriggerSlowdown(); //else, leave m_iStartTime as is - will result in no slow start break; case BP_GAME_MODE: m_bGameMode = GetBoolParameter(BP_GAME_MODE); // Maybe reload something here to begin game mode? break; default: break; } } else if(pEvent->m_iEventType == EV_EDIT) { // Keep track of where we are in the buffer CEditEvent *pEditEvent(static_cast < CEditEvent * >(pEvent)); if(pEditEvent->m_iEditType == 1) { m_iOffset += pEditEvent->m_sText.size(); } else if(pEditEvent->m_iEditType == 2) { m_iOffset -= pEditEvent->m_sText.size(); } } } void CDasherModel::Make_root(CDasherNode *pNewRoot) { // std::cout << "Make root" << std::endl; DASHER_ASSERT(pNewRoot != NULL); DASHER_ASSERT(pNewRoot->Parent() == m_Root); m_Root->SetFlag(NF_COMMITTED, true); // TODO: Is the stack necessary at all? We may as well just keep the // existing data structure? oldroots.push_back(m_Root); // TODO: tidy up conditional while((oldroots.size() > 10) && (!m_bRequireConversion || (oldroots[0]->GetFlag(NF_CONVERTED)))) { oldroots[0]->OrphanChild(oldroots[1]); delete oldroots[0]; oldroots.pop_front(); } m_Root = pNewRoot; // Update the root coordinates, as well as any currently scheduled locations const myint range = m_Rootmax - m_Rootmin; m_Rootmax = m_Rootmin + (range * m_Root->Hbnd()) / GetLongParameter(LP_NORMALIZATION); m_Rootmin = m_Rootmin + (range * m_Root->Lbnd()) / GetLongParameter(LP_NORMALIZATION); for(std::deque<SGotoItem>::iterator it(m_deGotoQueue.begin()); it != m_deGotoQueue.end(); ++it) { const myint r = it->iN2 - it->iN1; it->iN2 = it->iN1 + (r * m_Root->Hbnd()) / GetLongParameter(LP_NORMALIZATION); it->iN1 = it->iN1 + (r * m_Root->Lbnd()) / GetLongParameter(LP_NORMALIZATION); } } void CDasherModel::RecursiveMakeRoot(CDasherNode *pNewRoot) { DASHER_ASSERT(pNewRoot != NULL); DASHER_ASSERT(m_Root != NULL); if(pNewRoot == m_Root) return; // TODO: we really ought to check that pNewRoot is actually a // descendent of the root, although that should be guaranteed if(pNewRoot->Parent() != m_Root) RecursiveMakeRoot(pNewRoot->Parent()); Make_root(pNewRoot); } // only used when BP_CONTROL changes, so not very often. void CDasherModel::RebuildAroundCrosshair() { CDasherNode *pNode = Get_node_under_crosshair(); DASHER_ASSERT(pNode != NULL); DASHER_ASSERT(pNode == m_pLastOutput); RecursiveMakeRoot(pNode); DASHER_ASSERT(m_Root == pNode); ClearRootQueue(); m_Root->Delete_children(); m_Root->PopulateChildren(); } void CDasherModel::Reparent_root() { DASHER_ASSERT(m_Root != NULL); // Change the root node to the parent of the existing node. We need // to recalculate the coordinates for the "new" root as the user may // have moved around within the current root CDasherNode *pNewRoot; if(oldroots.size() == 0) { pNewRoot = m_Root->RebuildParent(); // Return if there's no existing parent and no way of recreating one if(pNewRoot == NULL) return; } else { pNewRoot = oldroots.back(); oldroots.pop_back(); } pNewRoot->SetFlag(NF_COMMITTED, false); DASHER_ASSERT(m_Root->Parent() == pNewRoot); const myint lower(m_Root->Lbnd()), upper(m_Root->Hbnd()); const myint iRange(upper-lower); myint iRootWidth(m_Rootmax - m_Rootmin); // Fail if the new root is bigger than allowed by normalisation if(((myint((GetLongParameter(LP_NORMALIZATION) - upper)) / static_cast<double>(iRange)) > (m_Rootmax_max - m_Rootmax)/static_cast<double>(iRootWidth)) || ((myint(lower) / static_cast<double>(iRange)) > (m_Rootmin - m_Rootmin_min) / static_cast<double>(iRootWidth))) { //but cache the (currently-unusable) root node - else we'll keep recreating (and deleting) it on every frame... oldroots.push_back(pNewRoot); return; } //Update the root coordinates to reflect the new root m_Root = pNewRoot; m_Rootmax = m_Rootmax + ((GetLongParameter(LP_NORMALIZATION) - upper) * iRootWidth) / iRange; m_Rootmin = m_Rootmin - (lower * iRootWidth) / iRange; for(std::deque<SGotoItem>::iterator it(m_deGotoQueue.begin()); it != m_deGotoQueue.end(); ++it) { iRootWidth = it->iN2 - it->iN1; it->iN2 = it->iN2 + (myint((GetLongParameter(LP_NORMALIZATION) - upper)) * iRootWidth / iRange); it->iN1 = it->iN1 - (myint(lower) * iRootWidth / iRange); } } void CDasherModel::ClearRootQueue() { while(oldroots.size() > 0) { if(oldroots.size() > 1) { oldroots[0]->OrphanChild(oldroots[1]); } else { oldroots[0]->OrphanChild(m_Root); } delete oldroots[0]; oldroots.pop_front(); } } CDasherNode *CDasherModel::Get_node_under_crosshair() { DASHER_ASSERT(m_Root != NULL); return m_Root->Get_node_under(GetLongParameter(LP_NORMALIZATION), m_Rootmin + m_iDisplayOffset, m_Rootmax + m_iDisplayOffset, GetLongParameter(LP_OX), GetLongParameter(LP_OY)); } void CDasherModel::DeleteTree() { ClearRootQueue(); delete m_Root; m_Root = NULL; } void CDasherModel::InitialiseAtOffset(int iOffset, CDasherView *pView) { if (m_pLastOutput) m_pLastOutput->Leave(); DeleteTree(); m_Root = m_pNodeCreationManager->GetAlphRoot(NULL, 0,GetLongParameter(LP_NORMALIZATION), iOffset!=0, iOffset); m_pLastOutput = (m_Root->GetFlag(NF_SEEN)) ? m_Root : NULL; // Create children of the root... ExpandNode(m_Root); // Set the root coordinates so that the root node is an appropriate // size and we're not in any of the children double dFraction( 1 - (1 - m_Root->MostProbableChild() / static_cast<double>(GetLongParameter(LP_NORMALIZATION))) / 2.0 ); int iWidth( static_cast<int>( (GetLongParameter(LP_MAX_Y) / (2.0*dFraction)) ) ); m_Rootmin = GetLongParameter(LP_MAX_Y) / 2 - iWidth / 2; m_Rootmax = GetLongParameter(LP_MAX_Y) / 2 + iWidth / 2; m_iDisplayOffset = 0; //now (re)create parents, while they show on the screen // - if we were lazy, we could leave this to NewFrame, // and one node around the root would be recreated per frame, // but we'll do it properly here. if(pView) { while(pView->IsSpaceAroundNode(m_Rootmin,m_Rootmax)) { CDasherNode *pOldRoot = m_Root; Reparent_root(); if(m_Root == pOldRoot) break; } } // TODO: See if this is better positioned elsewhere m_pDasherInterface->ScheduleRedraw(); } void CDasherModel::Get_new_root_coords(dasherint X, dasherint Y, dasherint &r1, dasherint &r2, unsigned long iTime) { DASHER_ASSERT(m_Root != NULL); if(m_iStartTime == 0) m_iStartTime = iTime; int iSteps = Steps(); double dFactor; if(GetBoolParameter(BP_SLOW_START) && ((iTime - m_iStartTime) < GetLongParameter(LP_SLOW_START_TIME))) dFactor = 0.1 * (1 + 9 * ((iTime - m_iStartTime) / static_cast<double>(GetLongParameter(LP_SLOW_START_TIME)))); else dFactor = 1.0; iSteps = static_cast<int>(iSteps / dFactor); // Avoid X == 0, as this corresponds to infinite zoom if (X <= 0) X = 1; // If X is too large we risk overflow errors, so limit it dasherint iMaxX = (1 << 29) / iSteps; if (X > iMaxX) X = iMaxX; // Mouse coords X, Y // new root{min,max} r1,r2, old root{min,max} R1,R2 const dasherint R1 = m_Rootmin; const dasherint R2 = m_Rootmax; // const dasherint Y1 = 0; dasherint Y2(GetLongParameter(LP_MAX_Y)); dasherint iOX(GetLongParameter(LP_OX)); dasherint iOY(GetLongParameter(LP_OY)); // Calculate what the extremes of the viewport will be when the // point under the cursor is at the cross-hair. This is where // we want to be in iSteps updates dasherint y1(Y - (Y2 * X) / (2 * iOX)); dasherint y2(Y + (Y2 * X) / (2 * iOY)); // iSteps is the number of update steps we need to get the point // under the cursor over to the cross hair. Calculated in order to // keep a constant bit-rate. DASHER_ASSERT(iSteps > 0); // Calculate the new values of y1 and y2 required to perform a single update // step. dasherint newy1, newy2, denom; denom = Y2 + (iSteps - 1) * (y2 - y1); newy1 = y1 * Y2 / denom; newy2 = ((y2 * iSteps - y1 * (iSteps - 1)) * Y2) / denom; y1 = newy1; y2 = newy2; // Calculate the minimum size of the viewport corresponding to the // maximum zoom. dasherint iMinSize(MinSize(Y2, dFactor)); if((y2 - y1) < iMinSize) { newy1 = y1 * (Y2 - iMinSize) / (Y2 - (y2 - y1)); newy2 = newy1 + iMinSize; y1 = newy1; y2 = newy2; } // If |(0,Y2)| = |(y1,y2)|, the "zoom factor" is 1, so we just translate. if (Y2 == y2 - y1) { r1 = R1 - y1; r2 = R2 - y1; return; } // There is a point C on the y-axis such the ratios (y1-C):(Y1-C) and // (y2-C):(Y2-C) are equal. (Obvious when drawn on separate parallel axes.) const dasherint C = (y1 * Y2) / (y1 + Y2 - y2); r1 = ((R1 - C) * Y2) / (y2 - y1) + C; r2 = ((R2 - C) * Y2) / (y2 - y1) + C; } bool CDasherModel::NextScheduledStep(unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB *pAdded, int *pNumDeleted) { DASHER_ASSERT (!GetBoolParameter(BP_DASHER_PAUSED) || m_deGotoQueue.size()==0); if (m_deGotoQueue.size() == 0) return false; myint iNewMin, iNewMax; iNewMin = m_deGotoQueue.front().iN1; iNewMax = m_deGotoQueue.front().iN2; m_deGotoQueue.pop_front(); UpdateBounds(iNewMin, iNewMax, iTime, pAdded, pNumDeleted); if (m_deGotoQueue.size() == 0) SetBoolParameter(BP_DASHER_PAUSED, true); return true; } void CDasherModel::OneStepTowards(myint miMousex, myint miMousey, unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { DASHER_ASSERT(!GetBoolParameter(BP_DASHER_PAUSED)); myint iNewMin, iNewMax; // works out next viewpoint Get_new_root_coords(miMousex, miMousey, iNewMin, iNewMax, iTime); UpdateBounds(iNewMin, iNewMax, iTime, pAdded, pNumDeleted); } void CDasherModel::UpdateBounds(myint iNewMin, myint iNewMax, unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { m_dTotalNats += log((iNewMax - iNewMin) / static_cast<double>(m_Rootmax - m_Rootmin)); // Now actually zoom to the new location NewGoTo(iNewMin, iNewMax, pAdded, pNumDeleted); // Check whether new nodes need to be created ExpandNode(Get_node_under_crosshair()); // This'll get done again when we render the frame, later, but we use NF_SEEN // (set here) to ensure the node under the cursor can never be collapsed // (even when the node budget is exceeded) when we do the rendering... HandleOutput(pAdded, pNumDeleted); } void CDasherModel::RecordFrame(unsigned long Time) { CFrameRate::RecordFrame(Time); ///GAME MODE TEMP///Pass new frame events onto our teacher GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher(); if(m_bGameMode && pTeacher) pTeacher->NewFrame(Time); } void CDasherModel::RecursiveOutput(CDasherNode *pNode, Dasher::VECTOR_SYMBOL_PROB* pAdded) { if(pNode->Parent()) { if (!pNode->Parent()->GetFlag(NF_SEEN)) RecursiveOutput(pNode->Parent(), pAdded); pNode->Parent()->Leave(); } pNode->Enter(); m_pLastOutput = pNode; pNode->SetFlag(NF_SEEN, true); pNode->Output(pAdded, GetLongParameter(LP_NORMALIZATION)); // If the node we are outputting is the last one in a game target sentence, then // notify the game mode teacher. if(m_bGameMode) if(pNode->GetFlag(NF_END_GAME)) GameMode::CDasherGameMode::GetTeacher()->SentenceFinished(); } void CDasherModel::NewGoTo(myint newRootmin, myint newRootmax, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { // Update the max and min of the root node to make iTargetMin and // iTargetMax the edges of the viewport. if(newRootmin + m_iDisplayOffset > (myint)GetLongParameter(LP_MAX_Y) / 2 - 1) newRootmin = (myint)GetLongParameter(LP_MAX_Y) / 2 - 1 - m_iDisplayOffset; if(newRootmax + m_iDisplayOffset < (myint)GetLongParameter(LP_MAX_Y) / 2 + 1) newRootmax = (myint)GetLongParameter(LP_MAX_Y) / 2 + 1 - m_iDisplayOffset; // Check that we haven't drifted too far. The rule is that we're not // allowed to let the root max and min cross the midpoint of the // screen. if(newRootmax < m_Rootmax_max && newRootmin > m_Rootmin_min) { // Only update if we're not making things big enough to risk // overflow. (Otherwise, forcibly choose a new root node, below) if ((newRootmax - newRootmin) > (myint)GetLongParameter(LP_MAX_Y) / 4) { // Also don't allow the update if it will result in making the // root too small. We should have re-generated a deeper root // before now already, but the original root is an exception. m_Rootmax = newRootmax; m_Rootmin = newRootmin; } //else, we just stop - this prevents the user from zooming too far back //outside the root node (when we can't generate an older root). m_iDisplayOffset = (m_iDisplayOffset * 90) / 100; } else { // can't make existing root any bigger because of overflow. So force a new root // to be chosen (so that Dasher doesn't just stop!)... //pick _child_ covering crosshair... const myint iWidth(m_Rootmax-m_Rootmin); for (CDasherNode::ChildMap::const_iterator it = m_Root->GetChildren().begin(), E = m_Root->GetChildren().end(); it!=E; it++) { CDasherNode *pChild(*it); DASHER_ASSERT(m_Rootmin + ((pChild->Lbnd() * iWidth) / GetLongParameter(LP_NORMALIZATION)) <= GetLongParameter(LP_OY)); if (m_Rootmin + ((pChild->Hbnd() * iWidth) / GetLongParameter(LP_NORMALIZATION)) > GetLongParameter(LP_OY)) { //proceed only if new root is on the game path. If the user's strayed // that far off the game path, having Dasher stop seems reasonable! if (!m_bGameMode || !pChild->GetFlag(NF_GAME)) { //make pChild the root node...but put (newRootmin,newRootmax) somewhere there'll be converted: SGotoItem temp; temp.iN1 = newRootmin; temp.iN2 = newRootmax; m_deGotoQueue.push_back(temp); m_Root->DeleteNephews(pChild); RecursiveMakeRoot(pChild); temp=m_deGotoQueue.back(); m_deGotoQueue.pop_back(); // std::cout << "NewGoto Recursing - was (" << newRootmin << "," << newRootmax << "), now (" << temp.iN1 << "," << temp.iN2 << ")" << std::endl; NewGoTo(temp.iN1, temp.iN2, pAdded,pNumDeleted); } return; } } DASHER_ASSERT(false); //did not find a child covering crosshair...?! } } void CDasherModel::HandleOutput(Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { CDasherNode *pNewNode = Get_node_under_crosshair(); DASHER_ASSERT(pNewNode != NULL); // std::cout << "HandleOutput: " << m_pLastOutput << " => " << pNewNode << std::endl; CDasherNode *pLastSeen = pNewNode; while (pLastSeen && !pLastSeen->GetFlag(NF_SEEN)) pLastSeen = pLastSeen->Parent(); while (m_pLastOutput != pLastSeen) { m_pLastOutput->Undo(pNumDeleted); m_pLastOutput->Leave(); //Should we? I think so, but the old code didn't...? m_pLastOutput->SetFlag(NF_SEEN, false); m_pLastOutput = m_pLastOutput->Parent(); if (m_pLastOutput) m_pLastOutput->Enter(); } if(!pNewNode->GetFlag(NF_SEEN)) { RecursiveOutput(pNewNode, pAdded); } } void CDasherModel::ExpandNode(CDasherNode *pNode) { DASHER_ASSERT(pNode != NULL); // TODO: Is NF_ALLCHILDREN any more useful/efficient than reading the map size? if(pNode->GetFlag(NF_ALLCHILDREN)) { DASHER_ASSERT(pNode->GetChildren().size() > 0); return; } // TODO: Do we really need to delete all of the children at this point? pNode->Delete_children(); // trial commented out - pconlon #ifdef DEBUG unsigned int iExpect = pNode->ExpectedNumChildren(); #endif pNode->PopulateChildren(); #ifdef DEBUG if (iExpect != pNode->GetChildren().size()) { std::cout << "(Note: expected " << iExpect << " children, actually created " << pNode->GetChildren().size() << ")" << std::endl; } #endif pNode->SetFlag(NF_ALLCHILDREN, true); // We get here if all our children (groups) and grandchildren (symbols) are created. // So lets find the correct letters. ///GAME MODE TEMP/////////// // If we are in GameMode, then we do a bit of cooperation with the teacher object when we create // new children. GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher(); if(m_bGameMode && pNode->GetFlag(NF_GAME) && pTeacher ) { - std::string strTargetUtf8Char(pTeacher->GetSymbolAtOffset(pNode->m_iOffset + 1)); + std::string strTargetUtf8Char(pTeacher->GetSymbolAtOffset(pNode->offset() + 1)); // Check if this is the last node in the sentence... if(strTargetUtf8Char == "GameEnd") pNode->SetFlag(NF_END_GAME, true); else if (!pNode->GameSearchChildren(strTargetUtf8Char)) { // Target character not found - not in our current alphabet?!?! // Let's give up! pNode->SetFlag(NF_END_GAME, true); } } //////////////////////////// } bool CDasherModel::RenderToView(CDasherView *pView, CExpansionPolicy &policy) { DASHER_ASSERT(pView != NULL); DASHER_ASSERT(m_Root != NULL); // XXX we HandleOutput in RenderToView // DASHER_ASSERT(Get_node_under_crosshair() == m_pLastOutput); bool bReturnValue = false; // The Render routine will fill iGameTargetY with the Dasher Coordinate of the // youngest node with NF_GAME set. The model is responsible for setting NF_GAME on // the appropriate Nodes. pView->Render(m_Root, m_Rootmin + m_iDisplayOffset, m_Rootmax + m_iDisplayOffset, policy, true); /////////GAME MODE TEMP////////////// if(m_bGameMode) if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) { //ACL 27/10/09 I note the following vector: std::vector<std::pair<myint,bool> > vGameTargetY; //was declared earlier and passed to pView->Render, above; but pView->Render //would never do _anything_ to it. Hence the below seems a bit redundant too, //but leaving around for now as a reminder that Game Mode generally is a TODO. pTeacher->SetTargetY(vGameTargetY); } ////////////////////////////////////// // TODO: Fix up stats // TODO: Is this the right way to handle this? HandleOutput(NULL, NULL); //ACL Off-screen nodes (zero collapse cost) will have been collapsed already. //Hence, this acts to maintain the node budget....or whatever the queue's policy is! if (policy.apply(m_pNodeCreationManager,this)) bReturnValue=true; return bReturnValue; } bool CDasherModel::CheckForNewRoot(CDasherView *pView) { DASHER_ASSERT(m_Root != NULL); // TODO: pView is redundant here #ifdef DEBUG CDasherNode *pOldNode = Get_node_under_crosshair(); #endif CDasherNode *root(m_Root); if(!(m_Root->GetFlag(NF_SUPER))) { Reparent_root(); return(m_Root != root); } CDasherNode *pNewRoot = NULL; for (CDasherNode::ChildMap::const_iterator it = m_Root->GetChildren().begin(); it != m_Root->GetChildren().end(); it++) { if ((*it)->GetFlag(NF_SUPER)) { //at most one child should have NF_SUPER set... DASHER_ASSERT(pNewRoot == NULL); pNewRoot = *it; #ifndef DEBUG break; #endif } } ////GAME MODE TEMP - only change the root if it is on the game path///////// if (pNewRoot && (!m_bGameMode || pNewRoot->GetFlag(NF_GAME))) { m_Root->DeleteNephews(pNewRoot); RecursiveMakeRoot(pNewRoot); } DASHER_ASSERT(Get_node_under_crosshair() == pOldNode); return false; } void CDasherModel::ScheduleZoom(long time, dasherint X, dasherint Y, int iMaxZoom) { // 1 = min, 2 = max. y1, y2 is the length we select from Y1, Y2. With // that ratio we calculate the new root{min,max} r1, r2 from current R1, R2. const int nsteps = GetLongParameter(LP_ZOOMSTEPS); const int safety = GetLongParameter(LP_S); // over safety_denom gives % const int safety_denom = 1024; const int ymax = GetLongParameter(LP_MAX_Y); const int scale = ymax; // (0,1) -> (ymin=0,ymax) // (X,Y) is mouse position in dasher coordinates // Prevent clicking too far to the right => y1 <> y2 see below if (X < 2) X = 2; // Lines with gradient +/- 1 passing through (X,Y) intersect y-axis at dasherint y1 = Y - X; // y = x + (Y - X) dasherint y2 = Y + X; // y = -x + (Y + X) // Rename for readability. const dasherint Y1 = 0; const dasherint Y2 = ymax; const dasherint R1 = m_Rootmin; const dasherint R2 = m_Rootmax; // So, want to zoom (y1 - safety/2, y2 + safety/2) -> (Y1, Y2) // Adjust y1, y2 for safety margin dasherint ds = (safety * scale) / (2 * safety_denom); y1 -= ds; y2 += ds; dasherint C, r1, r2; // If |(y1,y2)| = |(Y1,Y2)|, the "zoom factor" is 1, so we just translate. // y2 - y1 == Y2 - Y1 => y1 - Y1 == y2 - Y2 C = y1 - Y1; if (C == y2 - Y2) { r1 = R1 + C; r2 = R2 + C; } else { // There is a point C on the y-axis such the ratios (y1-C):(Y1-C) and // (y2-C):(Y2-C) are equal. (Obvious when drawn on separate parallel axes.) C = (y1 * Y2 - y2 * Y1) / (y1 + Y2 - y2 - Y1); // So another point r's zoomed y coordinate R, has the same ratio (r-C):(R-C) if (y1 != C) { r1 = ((R1 - C) * (Y1 - C)) / (y1 - C) + C; r2 = ((R2 - C) * (Y1 - C)) / (y1 - C) + C; } else if (y2 != C) { r1 = ((R1 - C) * (Y2 - C)) / (y2 - C) + C; r2 = ((R2 - C) * (Y2 - C)) / (y2 - C) + C; } else { // implies y1 = y2 std::cerr << "Impossible geometry in CDasherModel::ScheduleZoom\n"; } // iMaxZoom seems to be in tenths if (iMaxZoom != 0 && 10 * (r2 - r1) > iMaxZoom * (R2 - R1)) { r1 = ((R1 - C) * iMaxZoom) / 10 + C; r2 = ((R2 - C) * iMaxZoom) / 10 + C; } } // sNewItem seems to contain a list of root{min,max} for the frames of the // zoom, so split r -> R into n steps, with accurate R m_deGotoQueue.clear(); for (int s = nsteps - 1; s >= 0; --s) { SGotoItem sNewItem; sNewItem.iN1 = r1 - (s * (r1 - R1)) / nsteps; sNewItem.iN2 = r2 - (s * (r2 - R2)) / nsteps; m_deGotoQueue.push_back(sNewItem); } //steps having been scheduled, we're gonna start moving accordingly... m_pDasherInterface->Unpause(time); } void CDasherModel::ClearScheduledSteps() { m_deGotoQueue.clear(); } void CDasherModel::Offset(int iOffset) { m_Rootmin += iOffset; m_Rootmax += iOffset; if (GetBoolParameter(BP_SMOOTH_OFFSET)) m_iDisplayOffset -= iOffset; } void CDasherModel::AbortOffset() { m_Rootmin += m_iDisplayOffset; m_Rootmax += m_iDisplayOffset; m_iDisplayOffset = 0; } void CDasherModel::LimitRoot(int iMaxWidth) { m_Rootmin = GetLongParameter(LP_MAX_Y) / 2 - iMaxWidth / 2; m_Rootmax = GetLongParameter(LP_MAX_Y) / 2 + iMaxWidth / 2; } void CDasherModel::SetOffset(int iLocation, CDasherView *pView) { if(iLocation == m_iOffset) return; // We're already there // std::cout << "Initialising at offset: " << iLocation << std::endl; // TODO: Special cases, ie this can be done without rebuilding the // model m_iOffset = iLocation; // Now actually rebuild the model InitialiseAtOffset(iLocation, pView); } void CDasherModel::SetControlOffset(int iOffset) { // This is a hack, making many dubious assumptions which happen to // work right now. CDasherNode *pNode = Get_node_under_crosshair(); pNode->SetControlOffset(iOffset); } diff --git a/Src/DasherCore/DasherModel.h b/Src/DasherCore/DasherModel.h index b2fda97..82482f3 100644 --- a/Src/DasherCore/DasherModel.h +++ b/Src/DasherCore/DasherModel.h @@ -1,374 +1,374 @@ // DasherModel.h // // Copyright (c) 2008 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #ifndef __DasherModel_h__ #define __DasherModel_h__ #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <climits> #include <deque> #include <cmath> #include <vector> #include "../Common/NoClones.h" #include "DasherComponent.h" #include "DasherNode.h" #include "DasherTypes.h" #include "FrameRate.h" #include "NodeCreationManager.h" #include "ExpansionPolicy.h" namespace Dasher { class CDasherModel; class CDasherInterfaceBase; class CDasherView; struct SLockData; } /// \defgroup Model The Dasher model /// @{ /// \brief Dasher 'world' data structures and dynamics. /// /// The DasherModel represents the current state of Dasher /// It contains a tree of DasherNodes /// knows the current viewpoint /// knows how to evolve the viewpoint /// class Dasher::CDasherModel:public Dasher::CFrameRate, private NoClones { public: CDasherModel(CEventHandler * pEventHandler, CSettingsStore * pSettingsStore, CNodeCreationManager *pNCManager, CDasherInterfaceBase *pDashIface, CDasherView *pView, int iOffset); ~CDasherModel(); /// /// Event handler /// void HandleEvent(Dasher::CEvent * pEvent); /// @name Dymanic evolution /// Routines detailing the timer dependent evolution of the model /// @{ /// /// Update the root location with *one step* towards the specified /// co-ordinates - used by timer callbacks (for non-button modes) void OneStepTowards(myint, myint, unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB* pAdded = NULL, int* pNumDeleted = NULL); /// /// Notify the framerate class that a new frame has occurred /// Called from CDasherInterfaceBase::NewFrame /// void RecordFrame(unsigned long Time); /// /// Apply an offset to the 'target' coordinates - implements the jumps in /// two button dynamic mode. /// void Offset(int iOffset); /// /// Make the 'target' root coordinates match those currently visible, so any /// Offset(int) currently in progress (i.e. being smoothed over several /// frames) stops (at whatever point it's currently reached). Appropriate for /// abrupt changes in behaviour (such as backing off in button modes) void AbortOffset(); /// @} /// /// Reset counter of total nats entered /// void ResetNats() { m_dTotalNats = 0.0; } /// /// Return the total nats entered /// double GetNats() { return m_dTotalNats; } /// /// @name Rendering /// Methods to do with rendering the model to a view /// @{ /// /// Render the model to a given view. Return if any nodes were /// expanded, as if so we may want to render *another* frame to /// perform further expansion. /// bool RenderToView(CDasherView *pView, CExpansionPolicy &policy); /// @} /// /// @name Scheduled operation /// E.g. response to button mode /// @{ /// /// Schedule zoom to a given Dasher coordinate (used in click mode, /// button mode etc.) /// void ScheduleZoom(long time, dasherint iDasherX, dasherint iDasherY, int iMaxZoom = 0); void ClearScheduledSteps(); /// /// Update the bounds of the root node for the next step in any /// still-in-progress zoom scheduled by ScheduleZoom (does nothing /// if no steps remaining / no zoom scheduled). /// bool NextScheduledStep(unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB* pAdded = NULL, int *pNumDeleted = NULL); /// @} /// /// This is pretty horrible - a rethink of the start/reset mechanism /// is definitely in order. Used to prevent the root node from being /// too large in various modes before Dasher is started. /// void LimitRoot(int iMaxWidth); /// /// Cause Dasher to temporarily slow down (eg as part of automatic /// speed control in n-button dynamic mode). /// void TriggerSlowdown() { m_iStartTime = 0; }; /// /// Check whether a change of root node is needed, and perform the /// update if so /// TODO: Could be done in UpdateBounds? /// bool CheckForNewRoot(CDasherView *pView); /// /// Notify of a change of cursor position within the attached /// buffer. Resulting action should be appropriate - ie don't /// completely rebuild the model if an existing node covers this /// point /// void SetOffset(int iLocation, CDasherView *pView); /// /// TODO: Figure out how all these "offset"s work / relate to each other - if they do! In particular, /// what do we need DasherModel's own m_iOffset (which measures in _bytes_, not unicode characters!) for? /// int GetOffset() { - return m_pLastOutput->m_iOffset+1; + return m_pLastOutput->offset()+1; }; /// Create the children of a Dasher node void ExpandNode(CDasherNode * pNode); void SetControlOffset(int iOffset); private: /// Common portion of OneStepTowards / NextScheduledStep, taking /// bounds for the root node in the next frame. void UpdateBounds(myint iNewMin, myint iNewMax, unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB *pAdded, int *pNumDeleted); /// Struct representing intermediate stages in the goto queue /// struct SGotoItem { myint iN1; myint iN2; }; // Pointers to various auxilliary objects CDasherInterfaceBase *m_pDasherInterface; CNodeCreationManager *m_pNodeCreationManager; // The root of the Dasher tree CDasherNode *m_Root; // Old root notes // TODO: This should probably be rethought at some point - it doesn't really make a lot of sense std::deque < CDasherNode * >oldroots; // Rootmin and Rootmax specify the position of the root node in Dasher coords myint m_Rootmin; myint m_Rootmax; // Permitted range for root node - model cannot zoom beyond this // point without falling back to a new root node. myint m_Rootmin_min; myint m_Rootmax_max; // TODO: Does this need to be brought back? Make it relative to visible region? // The active interval over which Dasher nodes are maintained - this is most likely bigger than (0,DasherY) // CRange m_Active; // Offset used when presenting the model to the user, specified as // Displayed rootmin/max - actual rootmin/rootmax myint m_iDisplayOffset; CDasherNode *m_pLastOutput; // Queue of goto locations (eg for button mode) std::deque<SGotoItem> m_deGotoQueue; /// TODO: Not sure what this actually does double m_dAddProb; // Model parameters... (cached from settings store) // Current maximum bitrate (ie zoom at far rhs). double m_dMaxRate; // Whether game mode is active // TODO: This isn't very functional at the moment bool m_bGameMode; // Whether characters entered by alphabet manager are expected to // require conversion. // TODO: Need to rethink this at some point. bool m_bRequireConversion; // Model status... // Time at which the model was started (ie last unpaused, used for gradual speed up) // TODO: Implementation is very hacky at the moment // TODO: Duplicates functionality previously implemented elsewhere... // ...ACL 22/5/09 does it? There was an even hackier implementation, of resetting the // framerate, used for control mode (ControlManager.cpp), but that's all I could find // - and that seemed even worse, so I've removed it in favour of this here....? unsigned long m_iStartTime; // Offset into buffer of node currently under crosshair int m_iOffset; // Debug/performance information... // Information entered so far in this model double m_dTotalNats; /// /// Go directly to a given coordinate - check semantics /// void NewGoTo(myint n1, myint n2, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted); /// /// CDasherModel::Get_new_root_coords( myint Mousex,myint Mousey ) /// /// Calculate the new co-ordinates for the root node after a single /// update step. For further information, see Doc/geometry.tex. /// /// \param mousex x mouse co-ordinate measured right to left. /// \param mousey y mouse co-ordinate measured top to bottom. /// \param iNewMin New root min /// \param iNewMax New root max /// \param iTime Current timestamp /// void Get_new_root_coords(myint mousex, myint mousey, myint &iNewMin, myint &iNewMax, unsigned long iTime); /// Should be public? void InitialiseAtOffset(int iOffset, CDasherView *pView); /// Called from InitialiseAtOffset void DeleteTree(); /// /// Make a child of the root into a new root /// void Make_root(CDasherNode *pNewRoot); /// /// A version of Make_root which is suitable for arbitrary /// descendents of the root, not just immediate children. /// void RecursiveMakeRoot(CDasherNode *pNewRoot); /// /// Makes the node under the crosshair the root by deleting everything /// outside it, then rebuilds the nodes beneath it. (Thus, the node under /// the crosshair stays in the same place.) Used when control mode is turned /// on or off, or more generally, when the sizes of child nodes may have /// changed. /// void RebuildAroundCrosshair(); /// /// Rebuild the parent of the current root - used during backing off /// void Reparent_root(); /// /// Return a pointer to the Dasher node which is currently under the /// crosshair. Used for output, and apparently needed for game mode. /// CDasherNode *Get_node_under_crosshair(); /// /// Output a node, which has not been seen (& first, any ancestors that haven't been seen either), /// but which _is_ a descendant of m_pLastOutput. /// void RecursiveOutput(CDasherNode *pNode, Dasher::VECTOR_SYMBOL_PROB* pAdded); /// /// Handle the output caused by a change in node over the crosshair. Specifically, /// deletes from m_pLastOutput back to closest ancestor of pNewNode, /// then outputs from that ancestor to the node now under the crosshair (inclusively) /// void HandleOutput(Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted); /// /// Clear the queue of old roots - used when those nodes become /// invalid, eg during changes to conrol mode /// void ClearRootQueue(); }; /// @} #endif /* #ifndef __DasherModel_h__ */ diff --git a/Src/DasherCore/DasherNode.cpp b/Src/DasherCore/DasherNode.cpp index ab5ed2f..0fb1ab6 100644 --- a/Src/DasherCore/DasherNode.cpp +++ b/Src/DasherCore/DasherNode.cpp @@ -1,212 +1,206 @@ // DasherNode.cpp // // Copyright (c) 2007 David Ward // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" // #include "AlphabetManager.h" - doesnt seem to be required - pconlon #include "DasherInterfaceBase.h" using namespace Dasher; using namespace Opts; using namespace std; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif static int iNumNodes = 0; int Dasher::currentNumNodeObjects() {return iNumNodes;} //TODO this used to be inline - should we make it so again? -CDasherNode::CDasherNode(CDasherNode *pParent, unsigned int iLbnd, unsigned int iHbnd, SDisplayInfo *pDisplayInfo) { - // TODO: Check that these are disabled for debug builds, and that we're not shipping such a build +CDasherNode::CDasherNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, int iColour, const string &strDisplayText) +: m_pParent(pParent), m_iOffset(iOffset), m_iLbnd(iLbnd), m_iHbnd(iHbnd), m_iColour(iColour), m_strDisplayText(strDisplayText) { DASHER_ASSERT(iHbnd >= iLbnd); - DASHER_ASSERT(pDisplayInfo != NULL); - m_pParent = pParent; if (pParent) { DASHER_ASSERT(!pParent->GetFlag(NF_ALLCHILDREN)); pParent->Children().push_back(this); } - m_iLbnd = iLbnd; - m_iHbnd = iHbnd; - m_pDisplayInfo = pDisplayInfo; onlyChildRendered = NULL; // Default flags (make a definition somewhere, pass flags to constructor?) m_iFlags = 0; m_iRefCount = 0; iNumNodes++; } // TODO: put this back to being inlined CDasherNode::~CDasherNode() { // std::cout << "Deleting node: " << this << std::endl; // Release any storage that the node manager has allocated, // unreference ref counted stuff etc. Delete_children(); // std::cout << "done." << std::endl; - delete m_pDisplayInfo; iNumNodes--; } +void CDasherNode::PrependElidedGroup(int iGroupColour, string &strGroupLabel) { + if (m_iColour==-1) m_iColour = iGroupColour; + m_strDisplayText = strGroupLabel + m_strDisplayText; +} + void CDasherNode::Trace() const { /* TODO sort out dchar out[256]; if (m_Symbol) wsprintf(out,TEXT("%7x %3c %7x %5d %7x %5d %8x %8x \n"),this,m_Symbol,m_iGroup,m_context,m_Children,m_Cscheme,m_iLbnd,m_iHbnd); else wsprintf(out,TEXT("%7x %7x %5d %7x %5d %8x %8x \n"),this,m_iGroup,m_context,m_Children,m_Cscheme,m_iLbnd,m_iHbnd); OutputDebugString(out); if (m_Children) { unsigned int i; for (i=1;i<m_iChars;i++) m_Children[i]->Dump_node(); } */ } void CDasherNode::GetContext(CDasherInterfaceBase *pInterface, vector<symbol> &vContextSymbols, int iOffset, int iLength) { if (!GetFlag(NF_SEEN)) { DASHER_ASSERT(m_pParent); if (m_pParent) m_pParent->GetContext(pInterface, vContextSymbols, iOffset,iLength); } else { std::string strContext = pInterface->GetContext(iOffset, iLength); pInterface->GetAlphabet()->GetSymbols(vContextSymbols, strContext); } } CDasherNode *const CDasherNode::Get_node_under(int iNormalization, myint miY1, myint miY2, myint miMousex, myint miMousey) { myint miRange = miY2 - miY1; ChildMap::const_iterator i; for(i = GetChildren().begin(); i != GetChildren().end(); i++) { CDasherNode *pChild = *i; myint miNewy1 = miY1 + (miRange * pChild->m_iLbnd) / iNormalization; myint miNewy2 = miY1 + (miRange * pChild->m_iHbnd) / iNormalization; if(miMousey < miNewy2 && miMousey > miNewy1 && miMousex < miNewy2 - miNewy1) return pChild->Get_node_under(iNormalization, miNewy1, miNewy2, miMousex, miMousey); } return this; } // kill ourselves and all other children except for the specified // child // FIXME this probably shouldn't be called after history stuff is working void CDasherNode::OrphanChild(CDasherNode *pChild) { DASHER_ASSERT(ChildCount() > 0); ChildMap::const_iterator i; for(i = GetChildren().begin(); i != GetChildren().end(); i++) { if((*i) != pChild) { (*i)->Delete_children(); delete (*i); } } pChild->m_pParent=NULL; Children().clear(); SetFlag(NF_ALLCHILDREN, false); } // Delete nephews of the child which has the specified symbol // TODO: Need to allow for subnode void CDasherNode::DeleteNephews(CDasherNode *pChild) { DASHER_ASSERT(Children().size() > 0); ChildMap::iterator i; for(i = Children().begin(); i != Children().end(); i++) { if(*i != pChild) { (*i)->Delete_children(); } } } // TODO: Need to allow for subnodes // TODO: Incorporate into above routine void CDasherNode::Delete_children() { -// CAlphabetManager::SAlphabetData *pParentUserData(static_cast<CAlphabetManager::SAlphabetData *>(m_pUserData)); - -// if((GetDisplayInfo()->strDisplayText)[0] == 'e') -// std::cout << "ed: " << this << " " << pParentUserData->iContext << " " << pParentUserData->iOffset << std::endl; - // std::cout << "Start: " << this << std::endl; ChildMap::iterator i; for(i = Children().begin(); i != Children().end(); i++) { // std::cout << "CNM: " << (*i)->MgrID() << (*i) << " " << (*i)->Parent() << std::endl; delete (*i); } Children().clear(); // std::cout << "NM: " << MgrID() << std::endl; SetFlag(NF_ALLCHILDREN, false); } void CDasherNode::SetFlag(int iFlag, bool bValue) { if(bValue) m_iFlags = m_iFlags | iFlag; else m_iFlags = m_iFlags & (~iFlag); } void CDasherNode::SetParent(CDasherNode *pNewParent) { DASHER_ASSERT(pNewParent); DASHER_ASSERT(!pNewParent->GetFlag(NF_ALLCHILDREN)); m_pParent = pNewParent; pNewParent->Children().push_back(this); } int CDasherNode::MostProbableChild() { int iMax(0); int iCurrent; for(ChildMap::iterator it(m_mChildren.begin()); it != m_mChildren.end(); ++it) { iCurrent = (*it)->Range(); if(iCurrent > iMax) iMax = iCurrent; } return iMax; } bool CDasherNode::GameSearchChildren(string strTargetUtf8Char) { for (ChildMap::iterator i = Children().begin(); i != Children().end(); i++) { if ((*i)->GameSearchNode(strTargetUtf8Char)) return true; } return false; } diff --git a/Src/DasherCore/DasherNode.h b/Src/DasherCore/DasherNode.h index 8aebecb..720369b 100644 --- a/Src/DasherCore/DasherNode.h +++ b/Src/DasherCore/DasherNode.h @@ -1,339 +1,341 @@ // DasherNode.h // // Copyright (c) 2007 David Ward // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #ifndef __DasherNode_h__ #define __DasherNode_h__ #include "../Common/Common.h" #include "../Common/NoClones.h" #include "LanguageModelling/LanguageModel.h" #include "DasherTypes.h" #include "NodeManager.h" namespace Dasher { class CDasherNode; class CDasherInterfaceBase; }; #include <deque> #include <iostream> #include <vector> // Node flag constants #define NF_COMMITTED 1 #define NF_SEEN 2 #define NF_CONVERTED 4 #define NF_GAME 8 #define NF_ALLCHILDREN 16 #define NF_SUPER 32 #define NF_END_GAME 64 /// \ingroup Model /// @{ /// @brief A node in the Dasher model /// /// The Dasher node represents a box drawn on the display. This class /// contains the information required to render the node, as well as /// navigation within the model (parents and children /// etc.). Additional information is stored in m_pUserData, which is /// interpreted by the node manager associated with this class. Any /// logic specific to a particular node manager should be stored here. /// /// @todo Encapsulate presentation data in a structure? /// @todo Check that all methods respect the pseudochild attribute class Dasher::CDasherNode:private NoClones { public: /// Display attributes of this node, used for rendering. - struct SDisplayInfo { - int iColour; - bool bShove; - bool bVisible; - std::string strDisplayText; - }; + /// Colour: -1 for invisible + inline int getColour() {return m_iColour;} + inline std::string &getDisplayText() {return m_strDisplayText;} + ///Whether labels on child nodes should be displaced to the right of this node's label. + /// (Default implementation returns true, subclasses should override if appropriate) + virtual bool bShove() {return true;} + + inline int offset() {return m_iOffset;} CDasherNode *onlyChildRendered; //cache that only one child was rendered (as it filled the screen) /// Container type for storing children. Note that it's worth /// optimising this as lookup happens a lot typedef std::deque<CDasherNode*> ChildMap; /// @brief Constructor /// /// @param pParent Parent of the new node /// @param iLbnd Lower bound of node within parent /// @param iHbnd Upper bound of node within parent /// @param pDisplayInfo Struct containing information on how to display the node /// - CDasherNode(CDasherNode *pParent, unsigned int iLbnd, unsigned int iHbnd, SDisplayInfo *pDisplayInfo); + CDasherNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, int iColour, const std::string &strDisplayText); /// @brief Destructor /// virtual ~CDasherNode(); + /// Adjusts the colour & label of this node to look as it would if it + /// were the sole child of another node with the specified colour and label + /// (without actually making the other/group node) + void PrependElidedGroup(int iGroupColour, std::string &strGroupLabel); + void Trace() const; // diagnostic - /// Return display information for this node - inline const SDisplayInfo *GetDisplayInfo() const; - /// @name Routines for manipulating node status /// @{ /// @brief Set a node flag /// /// Set various flags corresponding to the state of the node. The following flags are defined: /// /// NF_COMMITTED - Node is 'above' the root, so corresponding symbol /// has been added to text box, language model trained etc /// /// NF_SEEN - Node has already been output /// /// NF_CONVERTED - Node has been converted (eg Japanese mode) /// /// NF_GAME - Node is on the path in game mode /// /// NF_ALLCHILDREN - Node has all children (TODO: obsolete?) /// /// NF_SUPER - Node covers entire visible area /// /// NF_END_GAME - Node is the last one of the phrase in game mode /// /// /// @param iFlag The flag to set /// @param bValue The new value of the flag /// virtual void SetFlag(int iFlag, bool bValue); /// @brief Get the value of a flag for this node /// /// @param iFlag The flag to get /// /// @return The current value of the flag /// inline bool GetFlag(int iFlag) const; /// @} /// @name Routines relating to the size of the node /// @{ // Lower and higher bounds, and the range /// @brief Get the lower bound of a node /// /// @return The lower bound /// inline unsigned int Lbnd() const; /// @brief Get the upper bound of a node /// /// @return The upper bound /// inline unsigned int Hbnd() const; /// @brief Get the range of a node (upper - lower bound) /// /// @return The range /// /// @todo Should this be here (trivial arithmethic of existing methods) /// inline unsigned int Range() const; /// @brief Reset the range of a node /// /// @param iLower New lower bound /// @param iUpper New upper bound /// inline void SetRange(unsigned int iLower, unsigned int iUpper); /// @brief Get the size of the most probable child /// /// @return The size /// int MostProbableChild(); /// @} /// @name Routines for manipulating relatives /// @{ inline const ChildMap & GetChildren() const; inline unsigned int ChildCount() const; inline CDasherNode *Parent() const; void SetParent(CDasherNode *pNewParent); // TODO: Should this be here? CDasherNode *const Get_node_under(int, myint y1, myint y2, myint smousex, myint smousey); // find node under given co-ords /// @brief Orphan a child of this node /// /// Deletes all other children, and the node itself /// /// @param pChild The child to keep /// void OrphanChild(CDasherNode * pChild); /// @brief Delete the nephews of a given child /// /// @param pChild The child to keep /// void DeleteNephews(CDasherNode *pChild); /// @brief Delete the children of this node /// /// void Delete_children(); /// @} /// /// Sees if a *child* / descendant of the specified node (not that node itself) /// represents the specified character. If so, set the child & intervening nodes' /// NF_GAME flag, and return true; otherwise, return false. /// bool GameSearchChildren(std::string strTargetUtf8Char); /// @name Management routines (once accessed via NodeManager) /// @{ /// Gets the node manager for this object. Meaning defined by subclasses, /// which should override and refine the return type appropriately; /// the main use is to provide runtime type info to check casting! virtual CNodeManager *mgr() = 0; /// /// Provide children for the supplied node /// virtual void PopulateChildren() = 0; /// The number of children which a call to PopulateChildren can be expected to generate. /// (This is not required to be 100% accurate, but any discrepancies will likely cause /// the node budgetting algorithm to behave sub-optimally) virtual int ExpectedNumChildren() = 0; /// /// Called whenever a node belonging to this manager first /// moves under the crosshair /// virtual void Output(Dasher::VECTOR_SYMBOL_PROB* pAdded, int iNormalization) {}; virtual void Undo(int *pNumDeleted) {}; virtual void Enter() {}; virtual void Leave() {}; virtual CDasherNode *RebuildParent() { return 0; }; /// /// Get as many symbols of context, up to the _end_ of the specified range, /// as possible from this node and its uncommitted ancestors /// virtual void GetContext(CDasherInterfaceBase *pInterface, std::vector<symbol> &vContextSymbols, int iOffset, int iLength); virtual void SetControlOffset(int iOffset) {}; /// /// See if this node represents the specified alphanumeric character; if so, set it's NF_GAME flag and /// return true; otherwise, return false. /// virtual bool GameSearchNode(std::string strTargetUtf8Char) {return false;} /// Clone the context of the specified node, if it's an alphabet node; /// else return an empty context. (Used by ConversionManager) virtual CLanguageModel::Context CloneAlphContext(CLanguageModel *pLanguageModel) { return pLanguageModel->CreateEmptyContext(); }; virtual symbol GetAlphSymbol() { throw "Hack for pre-MandarinDasher ConversionManager::BuildTree method, needs to access CAlphabetManager-private struct"; } /// @} - int m_iOffset; private: inline ChildMap &Children(); - SDisplayInfo *m_pDisplayInfo; - unsigned int m_iLbnd; unsigned int m_iHbnd; // the cumulative lower and upper bound prob relative to parent int m_iRefCount; // reference count if ancestor of (or equal to) root node ChildMap m_mChildren; // pointer to array of children CDasherNode *m_pParent; // pointer to parent // Binary flags representing the state of the node int m_iFlags; + + protected: + int m_iColour; + int m_iOffset; + std::string m_strDisplayText; }; /// @} namespace Dasher { /// Return the number of CDasherNode objects currently in existence. int currentNumNodeObjects(); } ///////////////////////////////////////////////////////////////////////////// // Inline functions ///////////////////////////////////////////////////////////////////////////// namespace Dasher { -inline const CDasherNode::SDisplayInfo *CDasherNode::GetDisplayInfo() const { - return m_pDisplayInfo; -} - inline unsigned int CDasherNode::Lbnd() const { return m_iLbnd; } inline unsigned int CDasherNode::Hbnd() const { return m_iHbnd; } inline unsigned int CDasherNode::Range() const { return m_iHbnd - m_iLbnd; } inline CDasherNode::ChildMap &CDasherNode::Children() { return m_mChildren; } inline const CDasherNode::ChildMap &CDasherNode::GetChildren() const { return m_mChildren; } inline unsigned int CDasherNode::ChildCount() const { return m_mChildren.size(); } inline bool CDasherNode::GetFlag(int iFlag) const { return ((m_iFlags & iFlag) != 0); } inline CDasherNode *CDasherNode::Parent() const { return m_pParent; } inline void CDasherNode::SetRange(unsigned int iLower, unsigned int iUpper) { m_iLbnd = iLower; m_iHbnd = iUpper; } } #endif /* #ifndef __DasherNode_h__ */ diff --git a/Src/DasherCore/DasherViewSquare.cpp b/Src/DasherCore/DasherViewSquare.cpp index 966ad52..f0ec7ad 100644 --- a/Src/DasherCore/DasherViewSquare.cpp +++ b/Src/DasherCore/DasherViewSquare.cpp @@ -1,922 +1,922 @@ // DasherViewSquare.cpp // // Copyright (c) 2008 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" #ifdef _WIN32 #include "..\Win32\Common\WinCommon.h" #endif //#include "DasherGameMode.h" #include "DasherViewSquare.h" #include "DasherModel.h" #include "DasherView.h" #include "DasherTypes.h" #include "Event.h" #include "EventHandler.h" #include <algorithm> #include <iostream> #include <limits> #include <stdlib.h> using namespace Dasher; using namespace Opts; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG_MEMLEAKS #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif // FIXME - quite a lot of the code here probably should be moved to // the parent class (DasherView). I think we really should make the // parent class less general - we're probably not going to implement // anything which uses radically different co-ordinate transforms, and // we can always override if necessary. // FIXME - duplicated 'mode' code throught - needs to be fixed (actually, mode related stuff, Input2Dasher etc should probably be at least partially in some other class) CDasherViewSquare::CDasherViewSquare(CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CDasherScreen *DasherScreen) : CDasherView(pEventHandler, pSettingsStore, DasherScreen), m_Y1(4), m_Y2(0.95 * GetLongParameter(LP_MAX_Y)), m_Y3(0.05 * GetLongParameter((LP_MAX_Y))) { // TODO - AutoOffset should be part of the eyetracker input filter // Make sure that the auto calibration is set to zero berfore we start // m_yAutoOffset = 0; ChangeScreen(DasherScreen); //Note, nonlinearity parameters set in SetScaleFactor m_bVisibleRegionValid = false; } CDasherViewSquare::~CDasherViewSquare() {} void CDasherViewSquare::HandleEvent(Dasher::CEvent *pEvent) { // Let the parent class do its stuff CDasherView::HandleEvent(pEvent); // And then interpret events for ourself if(pEvent->m_iEventType == 1) { Dasher::CParameterNotificationEvent * pEvt(static_cast < Dasher::CParameterNotificationEvent * >(pEvent)); switch (pEvt->m_iParameter) { case LP_REAL_ORIENTATION: case LP_MARGIN_WIDTH: case BP_NONLINEAR_Y: case LP_NONLINEAR_X: m_bVisibleRegionValid = false; SetScaleFactor(); break; default: break; } } } /// Draw text specified in Dasher co-ordinates. The position is /// specified as two co-ordinates, intended to the be the corners of /// the leading edge of the containing box. void CDasherViewSquare::DasherDrawText(myint iAnchorX1, myint iAnchorY1, myint iAnchorX2, myint iAnchorY2, const std::string &sDisplayText, int &mostleft, bool bShove) { // Don't draw text which will overlap with text in an ancestor. if(iAnchorX1 > mostleft) iAnchorX1 = mostleft; if(iAnchorX2 > mostleft) iAnchorX2 = mostleft; myint iDasherMinX; myint iDasherMinY; myint iDasherMaxX; myint iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); iAnchorY1 = std::min( iDasherMaxY, std::max( iDasherMinY, iAnchorY1 ) ); iAnchorY2 = std::min( iDasherMaxY, std::max( iDasherMinY, iAnchorY2 ) ); screenint iScreenAnchorX1; screenint iScreenAnchorY1; screenint iScreenAnchorX2; screenint iScreenAnchorY2; // FIXME - Truncate here before converting - otherwise we risk integer overflow in screen coordinates Dasher2Screen(iAnchorX1, iAnchorY1, iScreenAnchorX1, iScreenAnchorY1); Dasher2Screen(iAnchorX2, iAnchorY2, iScreenAnchorX2, iScreenAnchorY2); // Truncate the ends of the anchor line to be on the screen - this // prevents us from loosing characters off the top and bottom of the // screen // TruncateToScreen(iScreenAnchorX1, iScreenAnchorY1); // TruncateToScreen(iScreenAnchorX2, iScreenAnchorY2); // Actual anchor point is the midpoint of the anchor line screenint iScreenAnchorX((iScreenAnchorX1 + iScreenAnchorX2) / 2); screenint iScreenAnchorY((iScreenAnchorY1 + iScreenAnchorY2) / 2); // Compute font size based on position int Size = GetLongParameter( LP_DASHER_FONTSIZE ); // FIXME - this could be much more elegant, and probably needs a // rethink anyway - behvaiour here is too dependent on screen size screenint iLeftTimesFontSize = ((myint)GetLongParameter(LP_MAX_Y) - (iAnchorX1 + iAnchorX2)/ 2 )*Size; if(iLeftTimesFontSize < (myint)GetLongParameter(LP_MAX_Y) * 19/ 20) Size *= 20; else if(iLeftTimesFontSize < (myint)GetLongParameter(LP_MAX_Y) * 159 / 160) Size *= 14; else Size *= 11; screenint TextWidth, TextHeight; Screen()->TextSize(sDisplayText, &TextWidth, &TextHeight, Size); // Poistion of text box relative to anchor depends on orientation screenint newleft2 = 0; screenint newtop2 = 0; screenint newright2 = 0; screenint newbottom2 = 0; switch (Dasher::Opts::ScreenOrientations(GetLongParameter(LP_REAL_ORIENTATION))) { case (Dasher::Opts::LeftToRight): newleft2 = iScreenAnchorX; newtop2 = iScreenAnchorY - TextHeight / 2; newright2 = iScreenAnchorX + TextWidth; newbottom2 = iScreenAnchorY + TextHeight / 2; break; case (Dasher::Opts::RightToLeft): newleft2 = iScreenAnchorX - TextWidth; newtop2 = iScreenAnchorY - TextHeight / 2; newright2 = iScreenAnchorX; newbottom2 = iScreenAnchorY + TextHeight / 2; break; case (Dasher::Opts::TopToBottom): newleft2 = iScreenAnchorX - TextWidth / 2; newtop2 = iScreenAnchorY; newright2 = iScreenAnchorX + TextWidth / 2; newbottom2 = iScreenAnchorY + TextHeight; break; case (Dasher::Opts::BottomToTop): newleft2 = iScreenAnchorX - TextWidth / 2; newtop2 = iScreenAnchorY - TextHeight; newright2 = iScreenAnchorX + TextWidth / 2; newbottom2 = iScreenAnchorY; break; default: break; } // Update the value of mostleft to take into account the new text if(bShove) { myint iDasherNewLeft; myint iDasherNewTop; myint iDasherNewRight; myint iDasherNewBottom; Screen2Dasher(newleft2, newtop2, iDasherNewLeft, iDasherNewTop); Screen2Dasher(newright2, newbottom2, iDasherNewRight, iDasherNewBottom); mostleft = std::min(iDasherNewRight, iDasherNewLeft); } // Actually draw the text. We use DelayDrawText as the text should // be overlayed once all of the boxes have been drawn. m_DelayDraw.DelayDrawText(sDisplayText, newleft2, newtop2, Size); } void CDasherViewSquare::RenderNodes(CDasherNode *pRoot, myint iRootMin, myint iRootMax, CExpansionPolicy &policy) { DASHER_ASSERT(pRoot != 0); myint iDasherMinX; myint iDasherMinY; myint iDasherMaxX; myint iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); // screenint iScreenLeft; screenint iScreenTop; screenint iScreenRight; screenint iScreenBottom; Dasher2Screen(iRootMax-iRootMin, iRootMin, iScreenLeft, iScreenTop); Dasher2Screen(0, iRootMax, iScreenRight, iScreenBottom); //ifiScreenTop < 0) // iScreenTop = 0; //if(iScreenLeft < 0) // iScreenLeft=0; //// TODO: Should these be right on the boundary? //if(iScreenBottom > Screen()->GetHeight()) // iScreenBottom=Screen()->GetHeight(); //if(iScreenRight > Screen()->GetWidth()) // iScreenRight=Screen()->GetWidth(); // Blank the region around the root node: if(iRootMin > iDasherMinY) DasherDrawRectangle(iDasherMaxX, iDasherMinY, iDasherMinX, iRootMin, 0, -1, Nodes1, 0); //if(iScreenTop > 0) // Screen()->DrawRectangle(0, 0, Screen()->GetWidth(), iScreenTop, 0, -1, Nodes1, false, true, 1); if(iRootMax < iDasherMaxY) DasherDrawRectangle(iDasherMaxX, iRootMax, iDasherMinX, iDasherMaxY, 0, -1, Nodes1, 0); //if(iScreenBottom <= Screen()->GetHeight()) // Screen()->DrawRectangle(0, iScreenBottom, Screen()->GetWidth(), Screen()->GetHeight(), 0, -1, Nodes1, false, true, 1); DasherDrawRectangle(0, iDasherMinY, iDasherMinX, iDasherMaxY, 0, -1, Nodes1, 0); // Screen()->DrawRectangle(iScreenRight, std::max(0, (int)iScreenTop), // Screen()->GetWidth(), std::min(Screen()->GetHeight(), (int)iScreenBottom), // 0, -1, Nodes1, false, true, 1); // Render the root node (and children) RecursiveRender(pRoot, iRootMin, iRootMax, iDasherMaxX, policy, std::numeric_limits<double>::infinity(), iDasherMaxX,0,0); // Labels are drawn in a second parse to get the overlapping right m_DelayDraw.Draw(Screen()); // Finally decorate the view Crosshair((myint)GetLongParameter(LP_OX)); } //min size in *Dasher co-ordinates* to consider rendering a node #define QUICK_REJECT 50 //min size in *screen* (pixel) co-ordinates to render a node #define MIN_SIZE 2 bool CDasherViewSquare::CheckRender(CDasherNode *pRender, myint y1, myint y2, int mostleft, CExpansionPolicy &policy, double dMaxCost, myint parent_width, int parent_color, int iDepth) { if (y2-y1 >= QUICK_REJECT) { myint iDasherMinX; myint iDasherMinY; myint iDasherMaxX; myint iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); if (y1 <= iDasherMaxY && y2 >= iDasherMinY) { screenint iScreenX1; screenint iScreenY1; screenint iScreenX2; screenint iScreenY2; Dasher2Screen(0, std::max(y1, iDasherMinY), iScreenX1, iScreenY1); Dasher2Screen(0, std::min(y2, iDasherMaxY), iScreenX2, iScreenY2); Cint32 iHeight = std::max(myint(iScreenY2 - iScreenY1),myint( 0)); if (iHeight >= MIN_SIZE) { //node should be rendered! RecursiveRender(pRender, y1, y2, mostleft, policy, dMaxCost, parent_width, parent_color, iDepth); return true; } } } // We get here if the node is too small to render or is off-screen. // So, collapse it immediately. // // In game mode, we get here if the child is too small to draw, but we need the // coordinates - if this is the case then we shouldn't delete any children. // // TODO: Should probably render the parent segment here anyway (or // in the above) if(!pRender->GetFlag(NF_GAME)) pRender->Delete_children(); return false; } void CDasherViewSquare::RecursiveRender(CDasherNode *pRender, myint y1, myint y2, int mostleft, CExpansionPolicy &policy, double dMaxCost, myint parent_width,int parent_color, int iDepth) { DASHER_ASSERT_VALIDPTR_RW(pRender); // if(iDepth == 2) // std::cout << pRender->GetDisplayInfo()->strDisplayText << std::endl; // TODO: We need an overhall of the node creation/deletion logic - // make sure that we only maintain the minimum number of nodes which // are actually needed. This is especially true at the moment in // Game mode, which feels very sluggish. Node creation also feels // slower in Windows than Linux, especially if many nodes are // created at once (eg untrained Hiragana) ++m_iRenderCount; // myint trange = y2 - y1; // Attempt to draw the region to the left of this node inside its parent. // if(iDepth == 2) { // std::cout << "y1: " << y1 << " y2: " << y2 << std::endl; // Set the NF_SUPER flag if this node entirely frames the visual // area. // TODO: too slow? // TODO: use flags more rather than delete/reparent lists myint iDasherMinX; myint iDasherMinY; myint iDasherMaxX; myint iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); DasherDrawRectangle(std::min(parent_width,iDasherMaxX), std::max(y1,iDasherMinY), std::min(y2-y1,iDasherMaxX), std::min(y2,iDasherMaxY), parent_color, -1, Nodes1, 0); - const std::string &sDisplayText(pRender->GetDisplayInfo()->strDisplayText); + const std::string &sDisplayText(pRender->getDisplayText()); if( sDisplayText.size() > 0 ) { - DasherDrawText(y2-y1, y1, y2-y1, y2, sDisplayText, mostleft, pRender->GetDisplayInfo()->bShove); + DasherDrawText(y2-y1, y1, y2-y1, y2, sDisplayText, mostleft, pRender->bShove()); } pRender->SetFlag(NF_SUPER, !IsSpaceAroundNode(y1,y2)); // If there are no children then we still need to render the parent if(pRender->ChildCount() == 0) { - DasherDrawRectangle(std::min(y2-y1,iDasherMaxX), std::min(y2,iDasherMaxY),0, std::max(y1,iDasherMinY), pRender->GetDisplayInfo()->iColour, -1, Nodes1, 0); + DasherDrawRectangle(std::min(y2-y1,iDasherMaxX), std::min(y2,iDasherMaxY),0, std::max(y1,iDasherMinY), pRender->getColour(), -1, Nodes1, 0); //also allow it to be expanded, it's big enough. policy.pushNode(pRender, y1, y2, true, dMaxCost); return; } //Node has children. It can therefore be collapsed...however, // we don't allow a node covering the crosshair to be collapsed // (at best this'll mean there's nowhere useful to go forwards; // at worst, all kinds of crashes trying to do text output!) if (!pRender->GetFlag(NF_GAME) && !pRender->GetFlag(NF_SEEN)) dMaxCost = policy.pushNode(pRender, y1, y2, false, dMaxCost); // Render children int norm = (myint)GetLongParameter(LP_NORMALIZATION); myint lasty=y1; int id=-1; // int lower=-1,upper=-1; myint temp_parentwidth=y2-y1; - int temp_parentcolor = pRender->GetDisplayInfo()->iColour; + int temp_parentcolor = pRender->getColour(); const myint Range(y2 - y1); if (CDasherNode *pChild = pRender->onlyChildRendered) { //if child still covers screen, render _just_ it and return myint newy1 = y1 + (Range * (myint)pChild->Lbnd()) / (myint)norm; myint newy2 = y1 + (Range * (myint)pChild->Hbnd()) / (myint)norm; if (newy1 < iDasherMinY && newy2 > iDasherMaxY) { //still covers entire screen. Parent should too... DASHER_ASSERT(dMaxCost == std::numeric_limits<double>::infinity()); //don't inc iDepth, meaningless when covers the screen RecursiveRender(pChild, newy1, newy2, mostleft, policy, dMaxCost, temp_parentwidth, temp_parentcolor, iDepth); //leave pRender->onlyChildRendered set, so remaining children are skipped } else pRender->onlyChildRendered = NULL; } if (!pRender->onlyChildRendered) { //render all children... for(CDasherNode::ChildMap::const_iterator i = pRender->GetChildren().begin(); i != pRender->GetChildren().end(); i++) { id++; CDasherNode *pChild = *i; myint newy1 = y1 + (Range * (myint)pChild->Lbnd()) / (myint)norm;/// norm and lbnd are simple ints myint newy2 = y1 + (Range * (myint)pChild->Hbnd()) / (myint)norm; if (newy1 < iDasherMinY && newy2 > iDasherMaxY) { DASHER_ASSERT(dMaxCost == std::numeric_limits<double>::infinity()); pRender->onlyChildRendered = pChild; RecursiveRender(pChild, newy1, newy2, mostleft, policy, dMaxCost, temp_parentwidth, temp_parentcolor, iDepth); //ensure we don't blank over this child in "finishing off" the parent (!) lasty=newy2; break; //no need to render any more children! } if (CheckRender(pChild, newy1, newy2, mostleft, policy, dMaxCost, temp_parentwidth, temp_parentcolor, iDepth+1)) { if (lasty<newy1) { //if child has been drawn then the interval between him and the //last drawn child should be drawn too. //std::cout << "Fill in: " << lasty << " " << newy1 << std::endl; RenderNodePartFast(temp_parentcolor, lasty, newy1, mostleft, - pRender->GetDisplayInfo()->strDisplayText, - pRender->GetDisplayInfo()->bShove, + pRender->getDisplayText(), + pRender->bShove(), temp_parentwidth); } lasty = newy2; } } // Finish off the drawing process // if(iDepth == 1) { // Theres a chance that we haven't yet filled the entire parent, so finish things off if necessary. if(lasty<y2) { RenderNodePartFast(temp_parentcolor, lasty, y2, mostleft, - pRender->GetDisplayInfo()->strDisplayText, - pRender->GetDisplayInfo()->bShove, + pRender->getDisplayText(), + pRender->bShove(), temp_parentwidth); } } // Draw the outline - if(pRender->GetDisplayInfo()->bVisible) { - RenderNodeOutlineFast(pRender->GetDisplayInfo()->iColour, + if(pRender->getColour() != -1) {//-1 = invisible + RenderNodeOutlineFast(pRender->getColour(), y1, y2, mostleft, - pRender->GetDisplayInfo()->strDisplayText, - pRender->GetDisplayInfo()->bShove); + pRender->getDisplayText(), + pRender->bShove()); } // } } bool CDasherViewSquare::IsSpaceAroundNode(myint y1, myint y2) { myint iDasherMinX; myint iDasherMinY; myint iDasherMaxX; myint iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); return ((y2 - y1) < iDasherMaxX) || (y1 > iDasherMinY) || (y2 < iDasherMaxY); } // Draw the outline of a node int CDasherViewSquare::RenderNodeOutlineFast(const int Color, myint y1, myint y2, int &mostleft, const std::string &sDisplayText, bool bShove) { // Commenting because click mode occasionally fails this assert. // I don't know why. -- cjb. if (!(y2 >= y1)) { return 1; } // TODO - Get sensible limits here (to allow for non-linearities) myint iDasherMinX; myint iDasherMinY; myint iDasherMaxX; myint iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); screenint iScreenX1; screenint iScreenY1; screenint iScreenX2; screenint iScreenY2; Dasher2Screen(0, std::max(y1, iDasherMinY), iScreenX1, iScreenY1); Dasher2Screen(0, std::min(y2, iDasherMaxY), iScreenX2, iScreenY2); Cint32 iHeight = std::max(myint(iScreenY2 - iScreenY1),myint( 0)); Cint32 iWidth = std::max(myint(iScreenX2 - iScreenX1),myint( 0)); if((iHeight <= 1) && (iWidth <= 1)) return 0; // We're too small to render if((y1 > iDasherMaxY) || (y2 < iDasherMinY)){ return 0; // We're entirely off screen, so don't render. } // TODO: This should be earlier? if(!GetBoolParameter(BP_OUTLINE_MODE)) return 1; myint iDasherSize(y2 - y1); // std::cout << std::min(iDasherSize,iDasherMaxX) << " " << std::min(y2,iDasherMaxY) << " 0 " << std::max(y1,iDasherMinY) << std::endl; DasherDrawRectangle(0, std::min(y1,iDasherMaxY),std::min(iDasherSize,iDasherMaxX), std::max(y2,iDasherMinY), -1, Color, Nodes1, 1); // // FIXME - get rid of pointless assignment below // int iTruncation(GetLongParameter(LP_TRUNCATION)); // Trucation farction times 100; // if(iTruncation == 0) { // Regular squares // } // else { // // TODO: Put something back here? // } return 1; } // Draw a filled block of a node right down to the baseline (intended // for the case when you have no visible child) int CDasherViewSquare::RenderNodePartFast(const int Color, myint y1, myint y2, int &mostleft, const std::string &sDisplayText, bool bShove,myint iParentWidth ) { // Commenting because click mode occasionally fails this assert. // I don't know why. -- cjb. if (!(y2 >= y1)) { return 1; } // TODO - Get sensible limits here (to allow for non-linearities) myint iDasherMinX; myint iDasherMinY; myint iDasherMaxX; myint iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); screenint iScreenX1; screenint iScreenY1; screenint iScreenX2; screenint iScreenY2; Dasher2Screen(0, std::max(y1, iDasherMinY), iScreenX1, iScreenY1); Dasher2Screen(0, std::min(y2, iDasherMaxY), iScreenX2, iScreenY2); // std::cout << "Fill in components: " << iScreenY1 << " " << iScreenY2 << std::endl; Cint32 iHeight = std::max(myint(iScreenY2 - iScreenY1),myint( 0)); Cint32 iWidth = std::max(myint(iScreenX2 - iScreenX1),myint( 0)); if((iHeight < 1) && (iWidth < 1)) { // std::cout << "b" << std::endl; return 0; // We're too small to render } if((y1 > iDasherMaxY) || (y2 < iDasherMinY)){ //std::cout << "a" << std::endl; return 0; // We're entirely off screen, so don't render. } DasherDrawRectangle(std::min(iParentWidth,iDasherMaxX), std::min(y2,iDasherMaxY),0, std::max(y1,iDasherMinY), Color, -1, Nodes1, 0); return 1; } /// Convert screen co-ordinates to dasher co-ordinates. This doesn't /// include the nonlinear mapping for eyetracking mode etc - it is /// just the inverse of the mapping used to calculate the screen /// positions of boxes etc. void CDasherViewSquare::Screen2Dasher(screenint iInputX, screenint iInputY, myint &iDasherX, myint &iDasherY) { // Things we're likely to need: //myint iDasherWidth = (myint)GetLongParameter(LP_MAX_Y); myint iDasherHeight = (myint)GetLongParameter(LP_MAX_Y); screenint iScreenWidth = Screen()->GetWidth(); screenint iScreenHeight = Screen()->GetHeight(); int eOrientation(GetLongParameter(LP_REAL_ORIENTATION)); switch(eOrientation) { case Dasher::Opts::LeftToRight: iDasherX = iCenterX - ( iInputX - iScreenWidth / 2 ) * m_iScalingFactor / iScaleFactorX; iDasherY = iDasherHeight / 2 + ( iInputY - iScreenHeight / 2 ) * m_iScalingFactor / iScaleFactorY; break; case Dasher::Opts::RightToLeft: iDasherX = myint(iCenterX + ( iInputX - iScreenWidth / 2 ) * m_iScalingFactor/ iScaleFactorX); iDasherY = myint(iDasherHeight / 2 + ( iInputY - iScreenHeight / 2 ) * m_iScalingFactor/ iScaleFactorY); break; case Dasher::Opts::TopToBottom: iDasherX = myint(iCenterX - ( iInputY - iScreenHeight / 2 ) * m_iScalingFactor/ iScaleFactorY); iDasherY = myint(iDasherHeight / 2 + ( iInputX - iScreenWidth / 2 ) * m_iScalingFactor/ iScaleFactorX); break; case Dasher::Opts::BottomToTop: iDasherX = myint(iCenterX + ( iInputY - iScreenHeight / 2 ) * m_iScalingFactor/ iScaleFactorY); iDasherY = myint(iDasherHeight / 2 + ( iInputX - iScreenWidth / 2 ) * m_iScalingFactor/ iScaleFactorX); break; } iDasherX = ixmap(iDasherX); iDasherY = iymap(iDasherY); } void CDasherViewSquare::SetScaleFactor( void ) { //Parameters for X non-linearity. // Set some defaults here, in case we change(d) them later... m_dXmpb = 0.5; //threshold: DasherX's less than (m_dXmpb * MAX_Y) are linear... m_dXmpc = 0.9; //...but multiplied by m_dXmpc; DasherX's above that, are logarithmic... //set log scaling coefficient (unused if LP_NONLINEAR_X==0) // note previous value of m_dXmpa = 0.2, i.e. a value of LP_NONLINEAR_X =~= 4.8 m_dXmpa = exp(GetLongParameter(LP_NONLINEAR_X)/-3.0); myint iDasherWidth = (myint)GetLongParameter(LP_MAX_Y); myint iDasherHeight = iDasherWidth; screenint iScreenWidth = Screen()->GetWidth(); screenint iScreenHeight = Screen()->GetHeight(); // Try doing this a different way: myint iDasherMargin( GetLongParameter(LP_MARGIN_WIDTH) ); // Make this a parameter myint iMinX( 0-iDasherMargin ); myint iMaxX( iDasherWidth ); iCenterX = (iMinX + iMaxX)/2; myint iMinY( 0 ); myint iMaxY( iDasherHeight ); Dasher::Opts::ScreenOrientations eOrientation(Dasher::Opts::ScreenOrientations(GetLongParameter(LP_REAL_ORIENTATION))); double dScaleFactorX, dScaleFactorY; if (eOrientation == Dasher::Opts::LeftToRight || eOrientation == Dasher::Opts::RightToLeft) { dScaleFactorX = iScreenWidth / static_cast<double>( iMaxX - iMinX ); dScaleFactorY = iScreenHeight / static_cast<double>( iMaxY - iMinY ); } else { dScaleFactorX = iScreenHeight / static_cast<double>( iMaxX - iMinX ); dScaleFactorY = iScreenWidth / static_cast<double>( iMaxY - iMinY ); } if (dScaleFactorX < dScaleFactorY) { //fewer (pixels per dasher coord) in X direction - i.e., X is more compressed. //So, use X scale for Y too...except first, we'll _try_ to reduce the difference // by changing the relative scaling of X and Y (by at most 20%): double dMul = max(0.8, dScaleFactorX / dScaleFactorY); m_dXmpc *= dMul; dScaleFactorX /= dMul; iScaleFactorX = myint(dScaleFactorX * m_iScalingFactor); iScaleFactorY = myint(std::max(dScaleFactorX, dScaleFactorY / 4.0) * m_iScalingFactor); } else { //X has more room; use Y scale for both -> will get lots history iScaleFactorX = myint(std::max(dScaleFactorY, dScaleFactorX / 4.0) * m_iScalingFactor); iScaleFactorY = myint(dScaleFactorY * m_iScalingFactor); // however, "compensate" by relaxing the default "relative scaling" of X // (normally only 90% of Y) towards 1... m_dXmpc = std::min(1.0,0.9 * dScaleFactorX / dScaleFactorY); } iCenterX *= m_dXmpc; } inline myint CDasherViewSquare::CustomIDiv(myint iNumerator, myint iDenominator) { // Integer division rounding away from zero long long int num, denom, quot, rem; myint res; num = iNumerator; denom = iDenominator; DASHER_ASSERT(denom != 0); #ifdef HAVE_LLDIV lldiv_t ans = ::lldiv(num, denom); quot = ans.quot; rem = ans.rem; #else quot = num / denom; rem = num % denom; #endif if (rem < 0) res = quot - 1; else if (rem > 0) res = quot + 1; else res = quot; return res; // return (iNumerator + iDenominator - 1) / iDenominator; } void CDasherViewSquare::Dasher2Screen(myint iDasherX, myint iDasherY, screenint &iScreenX, screenint &iScreenY) { // Apply the nonlinearities iDasherX = xmap(iDasherX); iDasherY = ymap(iDasherY); // Things we're likely to need: //myint iDasherWidth = (myint)GetLongParameter(LP_MAX_Y); myint iDasherHeight = (myint)GetLongParameter(LP_MAX_Y); screenint iScreenWidth = Screen()->GetWidth(); screenint iScreenHeight = Screen()->GetHeight(); int eOrientation( GetLongParameter(LP_REAL_ORIENTATION) ); // Note that integer division is rounded *away* from zero here to // ensure that this really is the inverse of the map the other way // around. switch( eOrientation ) { case Dasher::Opts::LeftToRight: iScreenX = screenint(iScreenWidth / 2 - CustomIDiv((( iDasherX - iCenterX ) * iScaleFactorX), m_iScalingFactor)); iScreenY = screenint(iScreenHeight / 2 + CustomIDiv(( iDasherY - iDasherHeight / 2 ) * iScaleFactorY, m_iScalingFactor)); break; case Dasher::Opts::RightToLeft: iScreenX = screenint(iScreenWidth / 2 + CustomIDiv(( iDasherX - iCenterX ) * iScaleFactorX, m_iScalingFactor)); iScreenY = screenint(iScreenHeight / 2 + CustomIDiv(( iDasherY - iDasherHeight / 2 ) * iScaleFactorY, m_iScalingFactor)); break; case Dasher::Opts::TopToBottom: iScreenX = screenint(iScreenWidth / 2 + CustomIDiv(( iDasherY - iDasherHeight / 2 ) * iScaleFactorX, m_iScalingFactor)); iScreenY = screenint(iScreenHeight / 2 - CustomIDiv(( iDasherX - iCenterX ) * iScaleFactorY, m_iScalingFactor)); break; case Dasher::Opts::BottomToTop: iScreenX = screenint(iScreenWidth / 2 + CustomIDiv(( iDasherY - iDasherHeight / 2 ) * iScaleFactorX, m_iScalingFactor)); iScreenY = screenint(iScreenHeight / 2 + CustomIDiv(( iDasherX - iCenterX ) * iScaleFactorY, m_iScalingFactor)); break; } } void CDasherViewSquare::Dasher2Polar(myint iDasherX, myint iDasherY, double &r, double &theta) { iDasherX = xmap(iDasherX); iDasherY = ymap(iDasherY); myint iDasherOX = xmap(GetLongParameter(LP_OX)); myint iDasherOY = ymap(GetLongParameter(LP_OY)); double x = -(iDasherX - iDasherOX) / double(iDasherOX); //Use normalised coords so min r works double y = -(iDasherY - iDasherOY) / double(iDasherOY); theta = atan2(y, x); r = sqrt(x * x + y * y); } void CDasherViewSquare::DasherLine2Screen(myint x1, myint y1, myint x2, myint y2, vector<CDasherScreen::point> &vPoints) { if (x1!=x2 && y1!=y2) { //only diagonal lines ever get changed... if (GetBoolParameter(BP_NONLINEAR_Y)) { if ((y1 < m_Y3 && y2 > m_Y3) ||(y2 < m_Y3 && y1 > m_Y3)) { //crosses bottom non-linearity border int x_mid = x1+(x2-x1) * (m_Y3-y1)/(y2-y1); DasherLine2Screen(x1, y1, x_mid, m_Y3, vPoints); x1=x_mid; y1=m_Y3; }//else //no, a single line might cross _both_ borders! if ((y1 > m_Y2 && y2 < m_Y2) || (y2 > m_Y2 && y1 < m_Y2)) { //crosses top non-linearity border int x_mid = x1 + (x2-x1) * (m_Y2-y1)/(y2-y1); DasherLine2Screen(x1, y1, x_mid, m_Y2, vPoints); x1=x_mid; y1=m_Y2; } } double dMax(static_cast<double>(GetLongParameter(LP_MAX_Y))); if (GetLongParameter(LP_NONLINEAR_X) && (x1 / dMax > m_dXmpb || x2 / dMax > m_dXmpb)) { //into logarithmic section CDasherScreen::point pStart, pScreenMid, pEnd; Dasher2Screen(x2, y2, pEnd.x, pEnd.y); for(;;) { Dasher2Screen(x1, y1, pStart.x, pStart.y); //a straight line on the screen between pStart and pEnd passes through pScreenMid: pScreenMid.x = (pStart.x + pEnd.x)/2; pScreenMid.y = (pStart.y + pEnd.y)/2; //whereas a straight line _in_Dasher_space_ passes through pDasherMid: int xMid=(x1+x2)/2, yMid=(y1+y2)/2; CDasherScreen::point pDasherMid; Dasher2Screen(xMid, yMid, pDasherMid.x, pDasherMid.y); //since we know both endpoints are in the same section of the screen wrt. Y nonlinearity, //the midpoint along the DasherY axis of both lines should be the same. const Dasher::Opts::ScreenOrientations orient(Dasher::Opts::ScreenOrientations(GetLongParameter(LP_REAL_ORIENTATION))); if (orient==Dasher::Opts::LeftToRight || orient==Dasher::Opts::RightToLeft) { DASHER_ASSERT(abs(pDasherMid.y - pScreenMid.y)<=1);//allow for rounding error if (abs(pDasherMid.x - pScreenMid.x)<=1) break; //call a straight line accurate enough } else { DASHER_ASSERT(abs(pDasherMid.x - pScreenMid.x)<=1); if (abs(pDasherMid.y - pScreenMid.y)<=1) break; } //line should appear bent. Subdivide! DasherLine2Screen(x1,y1,xMid,yMid,vPoints); //recurse for first half (to Dasher-space midpoint) x1=xMid; y1=yMid; //& loop round for second half } //broke out of loop. a straight line (x1,y1)-(x2,y2) on the screen is an accurate portrayal of a straight line in Dasher-space. vPoints.push_back(pEnd); return; } //ok, not in x nonlinear section; fall through. } #ifdef DEBUG CDasherScreen::point pTest; Dasher2Screen(x1, y1, pTest.x, pTest.y); DASHER_ASSERT(vPoints.back().x == pTest.x && vPoints.back().y == pTest.y); #endif CDasherScreen::point p; Dasher2Screen(x2, y2, p.x, p.y); vPoints.push_back(p); } void CDasherViewSquare::VisibleRegion( myint &iDasherMinX, myint &iDasherMinY, myint &iDasherMaxX, myint &iDasherMaxY ) { // TODO: Change output parameters to pointers and allow NULL to mean // 'I don't care'. Need to be slightly careful about this as it will // require a slightly more sophisticated caching mechanism if(!m_bVisibleRegionValid) { int eOrientation( GetLongParameter(LP_REAL_ORIENTATION) ); switch( eOrientation ) { case Dasher::Opts::LeftToRight: Screen2Dasher(Screen()->GetWidth(),0,m_iDasherMinX,m_iDasherMinY); Screen2Dasher(0,Screen()->GetHeight(),m_iDasherMaxX,m_iDasherMaxY); break; case Dasher::Opts::RightToLeft: Screen2Dasher(0,0,m_iDasherMinX,m_iDasherMinY); Screen2Dasher(Screen()->GetWidth(),Screen()->GetHeight(),m_iDasherMaxX,m_iDasherMaxY); break; case Dasher::Opts::TopToBottom: Screen2Dasher(0,Screen()->GetHeight(),m_iDasherMinX,m_iDasherMinY); Screen2Dasher(Screen()->GetWidth(),0,m_iDasherMaxX,m_iDasherMaxY); break; case Dasher::Opts::BottomToTop: Screen2Dasher(0,0,m_iDasherMinX,m_iDasherMinY); Screen2Dasher(Screen()->GetWidth(),Screen()->GetHeight(),m_iDasherMaxX,m_iDasherMaxY); break; } m_bVisibleRegionValid = true; } iDasherMinX = m_iDasherMinX; iDasherMaxX = m_iDasherMaxX; iDasherMinY = m_iDasherMinY; iDasherMaxY = m_iDasherMaxY; } // void CDasherViewSquare::NewDrawGoTo(myint iDasherMin, myint iDasherMax, bool bActive) { // myint iHeight(iDasherMax - iDasherMin); // int iColour; // int iWidth; // if(bActive) { // iColour = 1; // iWidth = 3; // } // else { // iColour = 2; // iWidth = 1; // } // CDasherScreen::point p[4]; // Dasher2Screen( 0, iDasherMin, p[0].x, p[0].y); // Dasher2Screen( iHeight, iDasherMin, p[1].x, p[1].y); // Dasher2Screen( iHeight, iDasherMax, p[2].x, p[2].y); // Dasher2Screen( 0, iDasherMax, p[3].x, p[3].y); // Screen()->Polyline(p, 4, iWidth, iColour); // } void CDasherViewSquare::ChangeScreen(CDasherScreen *NewScreen) { CDasherView::ChangeScreen(NewScreen); m_bVisibleRegionValid = false; m_iScalingFactor = 100000000; SetScaleFactor(); } diff --git a/Src/DasherCore/MandarinAlphMgr.cpp b/Src/DasherCore/MandarinAlphMgr.cpp index 5ca8f92..93b3926 100644 --- a/Src/DasherCore/MandarinAlphMgr.cpp +++ b/Src/DasherCore/MandarinAlphMgr.cpp @@ -1,309 +1,303 @@ // MandarinAlphMgr.cpp // // Copyright (c) 2009 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" #include "MandarinAlphMgr.h" #include "LanguageModelling/PPMPYLanguageModel.h" #include "DasherInterfaceBase.h" #include "DasherNode.h" #include "Event.h" #include "EventHandler.h" #include "NodeCreationManager.h" #include <vector> #include <sstream> #include <iostream> using namespace std; using namespace Dasher; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG_MEMLEAKS #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif CMandarinAlphMgr::CMandarinAlphMgr(CDasherInterfaceBase *pInterface, CNodeCreationManager *pNCManager, CLanguageModel *pLanguageModel) : CAlphabetManager(pInterface, pNCManager, pLanguageModel), m_pParser(new CPinyinParser(pInterface->GetStringParameter(SP_SYSTEM_LOC) +"/alphabet.chineseRuby.xml")), m_pCHAlphabet(new CAlphabet(pInterface->GetInfo("Chinese / 简体中文 (simplified chinese, in pin yin groups)"))) { } CMandarinAlphMgr::~CMandarinAlphMgr() { delete m_pParser; } CDasherNode *CMandarinAlphMgr::CreateSymbolNode(CAlphNode *pParent, symbol iSymbol, unsigned int iLbnd, unsigned int iHbnd) { if (iSymbol <= 1288) { //Will wrote: //Modified for Mandarin Dasher //The following logic switch allows punctuation nodes in Mandarin to be treated in the same way as English (i.e. display and populate next round) instead of invoking a conversion node //ACL I think by "the following logic switch" he meant that symbols <= 1288 are "normal" nodes, NOT punctuation nodes, // whereas punctuation is handled by the fallthrough case (standard AlphabetManager CreateSymbolNode) /*old code: * CDasherNode *pNewNode = m_pNCManager->GetConvRoot(pParent, iLbnd, iHbnd, pParent->m_iOffset+1); * static_cast<CPinYinConversionHelper::CPYConvNode *>(pNewNode)->SetConvSymbol(iSymbol); * return pNewNode; */ - //from ConversionManager: - CDasherNode::SDisplayInfo *pInfo = new CDasherNode::SDisplayInfo; - pInfo->bVisible = true; - pInfo->bShove = true; - pInfo->strDisplayText = ""; - pInfo->iColour = 9; - //CTrieNode parallels old PinyinConversionHelper's SetConvSymbol: - CConvRoot *pNewNode = new CConvRoot(pParent, iLbnd, iHbnd, pInfo, this, m_pParser->GetTrieNode(m_pNCManager->GetAlphabet()->GetDisplayText(iSymbol))); - //keep same offset, as we still haven't entered/selected a definite symbol - pNewNode->m_iOffset = pParent->m_iOffset; + //CTrieNode parallels old PinyinConversionHelper's SetConvSymbol; we keep + // the same offset as we've still not entered/selected a symbol (leaf) + CConvRoot *pNewNode = new CConvRoot(pParent, pParent->offset(), iLbnd, iHbnd, this, m_pParser->GetTrieNode(m_pNCManager->GetAlphabet()->GetDisplayText(iSymbol))); //from ConversionHelper: //pNewNode->m_pLanguageModel = m_pLanguageModel; pNewNode->iContext = m_pLanguageModel->CloneContext(pParent->iContext); return pNewNode; } return CAlphabetManager::CreateSymbolNode(pParent, iSymbol, iLbnd, iHbnd); } -CMandarinAlphMgr::CConvRoot::CConvRoot(CDasherNode *pParent, unsigned int iLbnd, unsigned int iHbnd, SDisplayInfo *pDisplayInfo, CMandarinAlphMgr *pMgr, CTrieNode *pTrie) -: CDasherNode(pParent, iLbnd, iHbnd, pDisplayInfo), m_pMgr(pMgr), m_pTrie(pTrie) { - +CMandarinAlphMgr::CConvRoot::CConvRoot(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, CMandarinAlphMgr *pMgr, CTrieNode *pTrie) +: CDasherNode(pParent, iOffset, iLbnd, iHbnd, 9, ""), m_pMgr(pMgr), m_pTrie(pTrie) { + //colour + label from ConversionManager. } int CMandarinAlphMgr::CConvRoot::ExpectedNumChildren() { if (m_vChInfo.empty()) BuildConversions(); return m_vChInfo.size(); } void CMandarinAlphMgr::CConvRoot::BuildConversions() { if (!m_pTrie || !m_pTrie->list()) { //TODO some kind of fallback??? e.g. start new char? DASHER_ASSERT(false); return; } for(set<string>::iterator it = m_pTrie->list()->begin(); it != m_pTrie->list()->end(); ++it) { std::vector<symbol> vSyms; m_pMgr->m_pCHAlphabet->GetSymbols(vSyms, *it); DASHER_ASSERT(vSyms.size()==1); //does it ever happen? if so, Will's code would effectively push -1 DASHER_ASSERT(m_pMgr->m_pCHAlphabet->GetText(vSyms[0]) == *it); m_vChInfo.push_back(std::pair<symbol, unsigned int>(vSyms[0],0)); } //TODO would be nicer to do this only if we need the size info (i.e. PopulateChildren not ExpectedNumChildren) ? m_pMgr->AssignSizes(m_vChInfo, iContext); } void CMandarinAlphMgr::CConvRoot::PopulateChildren() { if (m_vChInfo.empty()) BuildConversions(); int iIdx(0); int iCum(0); // int parentClr = pNode->Colour(); // TODO: Fixme int parentClr = 0; // Finally loop through and create the children for (vector<pair<symbol, unsigned int> >::const_iterator it = m_vChInfo.begin(); it!=m_vChInfo.end(); it++) { // std::cout << "Current scec: " << pCurrentSCEChild << std::endl; unsigned int iLbnd(iCum); unsigned int iHbnd(iCum + it->second); iCum = iHbnd; // TODO: Parameters here are placeholders - need to figure out // what's right - CDasherNode::SDisplayInfo *pDisplayInfo = new CDasherNode::SDisplayInfo; - pDisplayInfo->iColour = (m_vChInfo.size()==1) ? GetDisplayInfo()->iColour : m_pMgr->AssignColour(parentClr, iIdx); - pDisplayInfo->bShove = true; - pDisplayInfo->bVisible = true; + int iColour(m_vChInfo.size()==1 ? getColour() : m_pMgr->AssignColour(parentClr, iIdx)); // std::cout << "#" << pCurrentSCEChild->pszConversion << "#" << std::endl; - //The chinese characters are in the _text_ (not label - that's e.g. "liang4") - // of the alphabet (& the pszConversion from PinyinParser was converted to symbol - // by CAlphabet::GetSymbols, which does string->symbol by _text_; we're reversing that) - pDisplayInfo->strDisplayText = m_pMgr->m_pCHAlphabet->GetText(it->first); - - CMandNode *pNewNode = new CMandSym(this, iLbnd, iHbnd, pDisplayInfo, m_pMgr, it->first); + CMandNode *pNewNode = new CMandSym(this, m_iOffset+1, iLbnd, iHbnd, iColour, m_pMgr, it->first); // TODO: Reimplement ---- // FIXME - handle context properly // pNewNode->SetContext(m_pLanguageModel->CreateEmptyContext()); // ----- - pNewNode->m_iOffset = m_iOffset + 1; - pNewNode->iContext = m_pMgr->m_pLanguageModel->CloneContext(this->iContext); m_pMgr->m_pLanguageModel->EnterSymbol(iContext, it->first); // TODO: Don't use symbols? DASHER_ASSERT(GetChildren().back()==pNewNode); ++iIdx; } } void CMandarinAlphMgr::AssignSizes(std::vector<pair<symbol,unsigned int> > &vChildren, Dasher::CLanguageModel::Context context) { const uint64 iNorm(m_pNCManager->GetLongParameter(LP_NORMALIZATION)); const unsigned int uniform((m_pNCManager->GetLongParameter(LP_UNIFORM)*iNorm)/1000); int iRemaining(iNorm); uint64 sumProb=0; //CLanguageModel::Context iCurrentContext; // std::cout<<"size of symbolstore "<<SymbolStore.size()<<std::endl; // std::cout<<"norm input: "<<nonuniform_norm/(iSymbols/iNChildren/100)<<std::endl; //ACL pass in iNorm and uniform directly - GetPartProbs distributes the last param between // however elements there are in vChildren... static_cast<CPPMPYLanguageModel *>(m_pLanguageModel)->GetPartProbs(context, vChildren, iNorm, uniform); //std::cout<<"after get probs "<<std::endl; for (std::vector<pair<symbol,unsigned int> >::const_iterator it = vChildren.begin(); it!=vChildren.end(); it++) { sumProb += it->second; } // std::cout<<"Sum Prob "<<sumProb<<std::endl; // std::cout<<"norm "<<nonuniform_norm<<std::endl; //Match, sumProbs = nonuniform_norm //but fix one element 'Da4' // Finally, iterate through the nodes and actually assign the sizes. // std::cout<<"sumProb "<<sumProb<<std::endl; for (std::vector<pair<symbol,unsigned int> >::iterator it = vChildren.begin(); it!=vChildren.end(); it++) { DASHER_ASSERT(it->first>-1); //ACL Will's code tested for both these conditions explicitly, and if so DASHER_ASSERT(sumProb>0); //then used a probability of 0. I don't think either //should ever happen if the alphabet files are right (there'd have to //be either no conversions of the syllable+tone, or else the LM'd have //to assign zero probability to each), so I'm removing these tests for now... iRemaining -= it->second = (it->second*iNorm)/sumProb; if (it->second==0) { #ifdef DEBUG std::cout << "WARNING: Erasing zero-probability conversion with symbol " << it->first << std::endl; #endif vChildren.erase(it--); } // std::cout<<pNode->pszConversion<<std::endl; // std::cout<<pNode->Symbol<<std::endl; // std::cout<<"Probs i "<<pNode<<std::endl; // std::cout<<"Symbol i"<<SymbolStore[iIdx]<<std::endl; // std::cout<<"symbols size "<<SymbolStore.size()<<std::endl; // std::cout<<"Symbols address "<<&SymbolStore<<std::endl; } //std::cout<<"iRemaining "<<iRemaining<<std::endl; // Last of all, allocate anything left over due to rounding error int iLeft(vChildren.size()); for (std::vector<pair<symbol,unsigned int> >::iterator it = vChildren.begin(); it!=vChildren.end(); it++) { int iDiff(iRemaining / iLeft); it->second += iDiff; iRemaining -= iDiff; --iLeft; // std::cout<<"Node size for "<<pNode->pszConversion<<std::endl; //std::cout<<"is "<<pNode->NodeSize<<std::endl; } DASHER_ASSERT(iRemaining == 0); } static int colourStore[2][3] = { {66,//light blue 64,//very light green 62},//light yellow {78,//light purple 81,//brownish 60},//red }; //Pulled from CConversionHelper, where it's described as "needing a rethink"... int CMandarinAlphMgr::AssignColour(int parentClr, int childIndex) { int which = -1; for (int i=0; i<2; i++) for(int j=0; j<3; j++) if (parentClr == colourStore[i][j]) which = i; if(which == -1) return colourStore[0][childIndex%3]; else if(which == 0) return colourStore[1][childIndex%3]; else return colourStore[0][childIndex%3]; }; CLanguageModel::Context CMandarinAlphMgr::CreateSymbolContext(CAlphNode *pParent, symbol iSymbol) { //Context carry-over. This code may worth looking at debug return m_pLanguageModel->CloneContext(pParent->iContext); } -CMandarinAlphMgr::CMandNode::CMandNode(CDasherNode *pParent, unsigned int iLbnd, unsigned int iHbnd, CDasherNode::SDisplayInfo *pDispInfo, CMandarinAlphMgr *pMgr, symbol iSymbol) -: CSymbolNode(pParent, iLbnd, iHbnd, pDispInfo, pMgr, iSymbol) { +CMandarinAlphMgr::CMandNode::CMandNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, CMandarinAlphMgr *pMgr, symbol iSymbol) +: CSymbolNode(pParent, iOffset, iLbnd, iHbnd, pMgr, iSymbol) { +} + +CMandarinAlphMgr::CMandNode::CMandNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, int iColour, const string &strDisplayText, CMandarinAlphMgr *pMgr, symbol iSymbol) +: CSymbolNode(pParent, iOffset, iLbnd, iHbnd, iColour, strDisplayText, pMgr, iSymbol) { } -CMandarinAlphMgr::CMandNode *CMandarinAlphMgr::makeSymbol(CDasherNode *pParent, unsigned int iLbnd, unsigned int iHbnd, CDasherNode::SDisplayInfo *pDispInfo, symbol iSymbol) { - return new CMandNode(pParent, iLbnd, iHbnd, pDispInfo, this, iSymbol); +CMandarinAlphMgr::CMandNode *CMandarinAlphMgr::makeSymbol(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, symbol iSymbol) { + // Override standard symbol factory method, called by superclass, to make CMandNodes + // - important only to disable learn-as-you-write... + return new CMandNode(pParent, iOffset, iLbnd, iHbnd, this, iSymbol); } void CMandarinAlphMgr::CMandNode::SetFlag(int iFlag, bool bValue) { //``disable learn-as-you-write for Mandarin Dasher'' if (iFlag==NF_COMMITTED) CDasherNode::SetFlag(iFlag, bValue); //bypass CAlphNode setter! else CAlphNode::SetFlag(iFlag, bValue); } -CMandarinAlphMgr::CMandSym::CMandSym(CDasherNode *pParent, unsigned int iLbnd, unsigned int iHbnd, CDasherNode::SDisplayInfo *pDispInfo, CMandarinAlphMgr *pMgr, symbol iSymbol) -: CMandNode(pParent, iLbnd, iHbnd, pDispInfo, pMgr, iSymbol) { +// For converted chinese symbols, we construct instead CMandSyms... +CMandarinAlphMgr::CMandSym::CMandSym(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, int iColour, CMandarinAlphMgr *pMgr, symbol iSymbol) +: CMandNode(pParent, iOffset, iLbnd, iHbnd, iColour, pMgr->m_pCHAlphabet->GetText(iSymbol), pMgr, iSymbol) { + //Note we passed a custom label into superclass constructor: + // the chinese characters are in the _text_ (not label - that's e.g. "liang4") + // of the alphabet (& the pszConversion from PinyinParser was converted to symbol + // by CAlphabet::GetSymbols, which does string->symbol by _text_; we're reversing that) } const std::string &CMandarinAlphMgr::CMandSym::outputText() { //use chinese, not pinyin, alphabet... return mgr()->m_pCHAlphabet->GetText(iSymbol); } diff --git a/Src/DasherCore/MandarinAlphMgr.h b/Src/DasherCore/MandarinAlphMgr.h index b0abadb..e09e54b 100644 --- a/Src/DasherCore/MandarinAlphMgr.h +++ b/Src/DasherCore/MandarinAlphMgr.h @@ -1,97 +1,100 @@ // MandarinAlphMgr.h // // Copyright (c) 2009 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #ifndef __mandarinalphmgr_h__ #define __mandarinalphmgr_h__ #include "AlphabetManager.h" #include "PinyinParser.h" namespace Dasher { class CDasherInterfaceBase; /// \ingroup Model /// @{ /// Overides methods of AlphabetManager for changes needed for Mandarin Dasher /// class CMandarinAlphMgr : public CAlphabetManager { public: CMandarinAlphMgr(CDasherInterfaceBase *pInterface, CNodeCreationManager *pNCManager, CLanguageModel *pLanguageModel); virtual ~CMandarinAlphMgr(); /*ACL note: used to override GetRoot, to attempt to clone the context of the previous node in the case that the previous node was a PinyinConversionHelper node (the common case - when a "conversion" was performed and chinese symbols reached, it then 'escaped' back to the alphabet manager root by calling GetAlphRoot...) Since this is no longer necessary (chinese symbol nodes are alph nodes directly, so subsume the previous role of alph 'root's rather than contain them), I don't think we need to override GetRoot anymore...?!?! */ protected: ///Subclass CSymbolNode to disable learn-as-you-write (for Mandarin Dasher). /// This subclass used directly only for punctuation; chinese symbols use CMandSym, below. class CMandNode : public CSymbolNode { public: CMandarinAlphMgr *mgr() {return static_cast<CMandarinAlphMgr *>(CSymbolNode::mgr());} - CMandNode(CDasherNode *pParent, unsigned int iLbnd, unsigned int iHbnd, CDasherNode::SDisplayInfo *pDispInfo, CMandarinAlphMgr *pMgr, symbol iSymbol); + CMandNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, CMandarinAlphMgr *pMgr, symbol iSymbol); virtual void SetFlag(int iFlag, bool bValue); virtual CDasherNode *RebuildParent() {return 0;} + protected: + /// Constructor for subclasses (CMandSym!) to specify own colour & label + CMandNode(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, int iColour, const std::string &strDisplayText, CMandarinAlphMgr *pMgr, symbol iSymbol); }; class CMandSym : public CMandNode { public: - CMandSym(CDasherNode *pParent, unsigned int iLbnd, unsigned int iHbnd, CDasherNode::SDisplayInfo *pDispInfo, CMandarinAlphMgr *pMgr, symbol iSymbol); + CMandSym(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, int iColour, CMandarinAlphMgr *pMgr, symbol iSymbol); private: virtual const std::string &outputText(); }; class CConvRoot : public CDasherNode { public: CMandarinAlphMgr *mgr() {return m_pMgr;} - CConvRoot(CDasherNode *pParent, unsigned int iLbnd, unsigned int iHbnd, CDasherNode::SDisplayInfo *pDispInfo, CMandarinAlphMgr *pMgr, CTrieNode *pTrie); + CConvRoot(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, CMandarinAlphMgr *pMgr, CTrieNode *pTrie); void PopulateChildren(); int ExpectedNumChildren(); int iContext; private: void BuildConversions(); std::vector<std::pair<symbol, unsigned int> > m_vChInfo; CMandarinAlphMgr *m_pMgr; CTrieNode *m_pTrie; }; - CMandNode *makeSymbol(CDasherNode *pParent, unsigned int iLbnd, unsigned int iHbnd, CDasherNode::SDisplayInfo *pDispInfo, symbol iSymbol); + CMandNode *makeSymbol(CDasherNode *pParent, int iOffset, unsigned int iLbnd, unsigned int iHbnd, symbol iSymbol); virtual CDasherNode *CreateSymbolNode(CAlphNode *pParent, symbol iSymbol, unsigned int iLbnd, unsigned int iHbnd); virtual CLanguageModel::Context CreateSymbolContext(CAlphNode *pParent, symbol iSymbol); int AssignColour(int parentClr, int childIndex); void AssignSizes(std::vector<std::pair<symbol,unsigned int> > &vChildren, Dasher::CLanguageModel::Context context); CPinyinParser *m_pParser; CAlphabet *m_pCHAlphabet; }; /// @} } #endif
rgee/HFOSS-Dasher
8b94ba0fa71930c25e7e593964f30dd3d4ca24f1
Avoid creating group nodes which will only have one child
diff --git a/Src/DasherCore/AlphabetManager.cpp b/Src/DasherCore/AlphabetManager.cpp index d8b5aed..b11f1e6 100644 --- a/Src/DasherCore/AlphabetManager.cpp +++ b/Src/DasherCore/AlphabetManager.cpp @@ -1,467 +1,486 @@ // AlphabetManager.cpp // // Copyright (c) 2007 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" #include "AlphabetManager.h" #include "ConversionManager.h" #include "DasherInterfaceBase.h" #include "DasherNode.h" #include "Event.h" #include "EventHandler.h" #include "NodeCreationManager.h" #include <vector> #include <sstream> #include <iostream> using namespace Dasher; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG_MEMLEAKS #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif CAlphabetManager::CAlphabetManager(CDasherInterfaceBase *pInterface, CNodeCreationManager *pNCManager, CLanguageModel *pLanguageModel) : m_pLanguageModel(pLanguageModel), m_pNCManager(pNCManager) { m_pInterface = pInterface; m_iLearnContext = m_pLanguageModel->CreateEmptyContext(); } CAlphabetManager::CAlphNode::CAlphNode(CDasherNode *pParent, unsigned int iLbnd, unsigned int iHbnd, CDasherNode::SDisplayInfo *pDisplayInfo, CAlphabetManager *pMgr) : CDasherNode(pParent, iLbnd, iHbnd, pDisplayInfo), m_pProbInfo(NULL), m_pMgr(pMgr) { }; CAlphabetManager::CSymbolNode::CSymbolNode(CDasherNode *pParent, unsigned int iLbnd, unsigned int iHbnd, CDasherNode::SDisplayInfo *pDisplayInfo, CAlphabetManager *pMgr, symbol _iSymbol) : CAlphNode(pParent, iLbnd, iHbnd, pDisplayInfo, pMgr), iSymbol(_iSymbol) { }; CAlphabetManager::CGroupNode::CGroupNode(CDasherNode *pParent, unsigned int iLbnd, unsigned int iHbnd, CDasherNode::SDisplayInfo *pDisplayInfo, CAlphabetManager *pMgr, SGroupInfo *pGroup) : CAlphNode(pParent, iLbnd, iHbnd, pDisplayInfo, pMgr), m_pGroup(pGroup) { }; CAlphabetManager::CSymbolNode *CAlphabetManager::makeSymbol(CDasherNode *pParent, unsigned int iLbnd, unsigned int iHbnd, CDasherNode::SDisplayInfo *pDisplayInfo, symbol iSymbol) { return new CSymbolNode(pParent, iLbnd, iHbnd, pDisplayInfo, this, iSymbol); } CAlphabetManager::CGroupNode *CAlphabetManager::makeGroup(CDasherNode *pParent, unsigned int iLbnd, unsigned int iHbnd, CDasherNode::SDisplayInfo *pDisplayInfo, SGroupInfo *pGroup) { return new CGroupNode(pParent, iLbnd, iHbnd, pDisplayInfo, this, pGroup); } CAlphabetManager::CAlphNode *CAlphabetManager::GetRoot(CDasherNode *pParent, unsigned int iLower, unsigned int iUpper, bool bEnteredLast, int iOffset) { int iNewOffset(max(-1,iOffset-1)); std::vector<symbol> vContextSymbols; // TODO: make the LM get the context, rather than force it to fix max context length as an int int iStart = max(0, iNewOffset - m_pLanguageModel->GetContextLength()); if(pParent) { pParent->GetContext(m_pInterface, vContextSymbols, iStart, iNewOffset+1 - iStart); } else { std::string strContext = (iNewOffset == -1) ? m_pNCManager->GetAlphabet()->GetDefaultContext() : m_pInterface->GetContext(iStart, iNewOffset+1 - iStart); m_pNCManager->GetAlphabet()->GetSymbols(vContextSymbols, strContext); } CDasherNode::SDisplayInfo *pDisplayInfo = new CDasherNode::SDisplayInfo; pDisplayInfo->bShove = true; pDisplayInfo->bVisible = true; CAlphNode *pNewNode; CLanguageModel::Context iContext = m_pLanguageModel->CreateEmptyContext(); std::vector<symbol>::iterator it = vContextSymbols.end(); while (it!=vContextSymbols.begin()) { if (*(--it) == 0) { //found an impossible symbol! start after it ++it; break; } } if (it == vContextSymbols.end()) { //previous character was not in the alphabet! //can't construct a node "responsible" for entering it bEnteredLast=false; //instead, Create a node as if we were starting a new sentence... vContextSymbols.clear(); m_pNCManager->GetAlphabet()->GetSymbols(vContextSymbols, m_pNCManager->GetAlphabet()->GetDefaultContext()); it = vContextSymbols.begin(); //TODO: What it the default context somehow contains symbols not in the alphabet? } //enter the symbols we could make sense of, into the LM context... while (it != vContextSymbols.end()) { m_pLanguageModel->EnterSymbol(iContext, *(it++)); } if(!bEnteredLast) { pDisplayInfo->strDisplayText = ""; //equivalent to do m_pNCManager->GetAlphabet()->GetDisplayText(0) pDisplayInfo->iColour = m_pNCManager->GetAlphabet()->GetColour(0, iNewOffset%2); pNewNode = makeGroup(pParent, iLower, iUpper, pDisplayInfo, NULL); } else { const symbol iSymbol(vContextSymbols[vContextSymbols.size() - 1]); pDisplayInfo->strDisplayText = m_pNCManager->GetAlphabet()->GetDisplayText(iSymbol); pDisplayInfo->iColour = m_pNCManager->GetAlphabet()->GetColour(iSymbol, iNewOffset%2); pNewNode = makeSymbol(pParent, iLower, iUpper, pDisplayInfo, iSymbol); //if the new node is not child of an existing node, then it // represents a symbol that's already happened - so we're either // going backwards (rebuildParent) or creating a new root after a language change DASHER_ASSERT (!pParent); pNewNode->SetFlag(NF_SEEN, true); } pNewNode->m_iOffset = iNewOffset; pNewNode->iContext = iContext; return pNewNode; } bool CAlphabetManager::CSymbolNode::GameSearchNode(string strTargetUtf8Char) { if (m_pMgr->m_pNCManager->GetAlphabet()->GetText(iSymbol) == strTargetUtf8Char) { SetFlag(NF_GAME, true); return true; } return false; } bool CAlphabetManager::CGroupNode::GameSearchNode(string strTargetUtf8Char) { if (GameSearchChildren(strTargetUtf8Char)) { SetFlag(NF_GAME, true); return true; } return false; } CLanguageModel::Context CAlphabetManager::CAlphNode::CloneAlphContext(CLanguageModel *pLanguageModel) { if (iContext) return pLanguageModel->CloneContext(iContext); return CDasherNode::CloneAlphContext(pLanguageModel); } void CAlphabetManager::CSymbolNode::GetContext(CDasherInterfaceBase *pInterface, vector<symbol> &vContextSymbols, int iOffset, int iLength) { if (!GetFlag(NF_SEEN) && iOffset+iLength-1 == m_iOffset) { if (iLength > 1) Parent()->GetContext(pInterface, vContextSymbols, iOffset, iLength-1); vContextSymbols.push_back(iSymbol); } else { CDasherNode::GetContext(pInterface, vContextSymbols, iOffset, iLength); } } symbol CAlphabetManager::CSymbolNode::GetAlphSymbol() { return iSymbol; } void CAlphabetManager::CSymbolNode::PopulateChildren() { m_pMgr->IterateChildGroups(this, NULL, NULL); } int CAlphabetManager::CAlphNode::ExpectedNumChildren() { return m_pMgr->m_pNCManager->GetAlphabet()->iNumChildNodes; } std::vector<unsigned int> *CAlphabetManager::CAlphNode::GetProbInfo() { if (!m_pProbInfo) { m_pProbInfo = new std::vector<unsigned int>(); m_pMgr->m_pNCManager->GetProbs(iContext, *m_pProbInfo, m_pMgr->m_pNCManager->GetLongParameter(LP_NORMALIZATION)); // work out cumulative probs in place for(unsigned int i = 1; i < m_pProbInfo->size(); i++) { (*m_pProbInfo)[i] += (*m_pProbInfo)[i - 1]; } } return m_pProbInfo; } std::vector<unsigned int> *CAlphabetManager::CGroupNode::GetProbInfo() { if (m_pGroup && Parent() && Parent()->mgr() == mgr()) { DASHER_ASSERT(Parent()->m_iOffset == m_iOffset); return (static_cast<CAlphNode *>(Parent()))->GetProbInfo(); } //nope, no usable parent. compute here... return CAlphNode::GetProbInfo(); } void CAlphabetManager::CGroupNode::PopulateChildren() { m_pMgr->IterateChildGroups(this, m_pGroup, NULL); - if (GetChildren().size()==1) { - CDasherNode *pChild = GetChildren()[0]; - //single child, must therefore completely fill this node... - DASHER_ASSERT(pChild->Lbnd()==0 && pChild->Hbnd()==65536); - //in earlier versions of Dasher with subnodes, that child would have been created - // at the same time as this node, so this node would never be seen/rendered (as the - // child would cover it). However, lazily (as we do now) creating the child, will - // suddenly obscure this (parent) node, changing it's colour. Hence, avoid this by - // making the child look like the parent...(note that changing the parent, before the - // child is created, to look like the child will do, would more closely mirror the old - // behaviour, but we can't really do that! - CDasherNode::SDisplayInfo *pInfo = (CDasherNode::SDisplayInfo *)pChild->GetDisplayInfo(); - //ick, note the cast to get rid of 'const'ness. TODO: do something about SDisplayInfo...!! - pInfo->bVisible=false; - pInfo->iColour = GetDisplayInfo()->iColour; - } } + int CAlphabetManager::CGroupNode::ExpectedNumChildren() { return (m_pGroup) ? m_pGroup->iNumChildNodes : CAlphNode::ExpectedNumChildren(); } CAlphabetManager::CGroupNode *CAlphabetManager::CreateGroupNode(CAlphNode *pParent, SGroupInfo *pInfo, unsigned int iLbnd, unsigned int iHbnd) { // TODO: More sensible structure in group data to map directly to this CDasherNode::SDisplayInfo *pDisplayInfo = new CDasherNode::SDisplayInfo; pDisplayInfo->iColour = (pInfo->bVisible ? pInfo->iColour : pParent->GetDisplayInfo()->iColour); pDisplayInfo->bShove = true; pDisplayInfo->bVisible = pInfo->bVisible; pDisplayInfo->strDisplayText = pInfo->strLabel; CGroupNode *pNewNode = makeGroup(pParent, iLbnd, iHbnd, pDisplayInfo, pInfo); // When creating a group node... pNewNode->m_iOffset = pParent->m_iOffset; // ...the offset is the same as the parent... pNewNode->iContext = m_pLanguageModel->CloneContext(pParent->iContext); return pNewNode; } CAlphabetManager::CGroupNode *CAlphabetManager::CGroupNode::RebuildGroup(CAlphNode *pParent, SGroupInfo *pInfo, unsigned int iLbnd, unsigned int iHbnd) { if (pInfo == m_pGroup) { SetRange(iLbnd, iHbnd); SetParent(pParent); //offset doesn't increase for groups... DASHER_ASSERT (m_iOffset == pParent->m_iOffset); return this; } CGroupNode *pRet=m_pMgr->CreateGroupNode(pParent, pInfo, iLbnd, iHbnd); if (pInfo->iStart <= m_pGroup->iStart && pInfo->iEnd >= m_pGroup->iEnd) { //created group node should contain this one m_pMgr->IterateChildGroups(pRet,pInfo,this); } return pRet; } CAlphabetManager::CGroupNode *CAlphabetManager::CSymbolNode::RebuildGroup(CAlphNode *pParent, SGroupInfo *pInfo, unsigned int iLbnd, unsigned int iHbnd) { CGroupNode *pRet=m_pMgr->CreateGroupNode(pParent, pInfo, iLbnd, iHbnd); if (pInfo->iStart <= iSymbol && pInfo->iEnd > iSymbol) { m_pMgr->IterateChildGroups(pRet, pInfo, this); } return pRet; } CLanguageModel::Context CAlphabetManager::CreateSymbolContext(CAlphNode *pParent, symbol iSymbol) { CLanguageModel::Context iContext = m_pLanguageModel->CloneContext(pParent->iContext); m_pLanguageModel->EnterSymbol(iContext, iSymbol); // TODO: Don't use symbols? return iContext; } CDasherNode *CAlphabetManager::CreateSymbolNode(CAlphNode *pParent, symbol iSymbol, unsigned int iLbnd, unsigned int iHbnd) { CDasherNode *pNewNode = NULL; //Does not invoke conversion node // TODO: Better way of specifying alternate roots // TODO: Need to fix fact that this is created even when control mode is switched off if(iSymbol == m_pNCManager->GetAlphabet()->GetControlSymbol()) { //ACL setting offset as one more than parent for consistency with "proper" symbol nodes... pNewNode = m_pNCManager->GetCtrlRoot(pParent, iLbnd, iHbnd, pParent->m_iOffset+1); #ifdef _WIN32_WCE //no control manager - but (TODO!) we still try to create (0-size!) control node... DASHER_ASSERT(!pNewNode); // For now, just hack it so we get a normal root node here pNewNode = m_pNCManager->GetAlphRoot(pParent, iLbnd, iHbnd, false, pParent->m_iOffset+1); #else DASHER_ASSERT(pNewNode); #endif } else if(iSymbol == m_pNCManager->GetAlphabet()->GetStartConversionSymbol()) { // else if(iSymbol == m_pNCManager->GetSpaceSymbol()) { //ACL setting m_iOffset+1 for consistency with "proper" symbol nodes... pNewNode = m_pNCManager->GetConvRoot(pParent, iLbnd, iHbnd, pParent->m_iOffset+1); } else { //compute phase directly from offset int iColour = m_pNCManager->GetAlphabet()->GetColour(iSymbol, (pParent->m_iOffset+1)%2); // TODO: Exceptions / error handling in general CDasherNode::SDisplayInfo *pDisplayInfo = new CDasherNode::SDisplayInfo; pDisplayInfo->iColour = iColour; pDisplayInfo->bShove = true; pDisplayInfo->bVisible = true; pDisplayInfo->strDisplayText = m_pNCManager->GetAlphabet()->GetDisplayText(iSymbol); CAlphNode *pAlphNode; pNewNode = pAlphNode = makeSymbol(pParent, iLbnd, iHbnd, pDisplayInfo,iSymbol); // std::stringstream ssLabel; // ssLabel << m_pNCManager->GetAlphabet()->GetDisplayText(iSymbol) << ": " << pNewNode; // pDisplayInfo->strDisplayText = ssLabel.str(); pNewNode->m_iOffset = pParent->m_iOffset + 1; pAlphNode->iContext = CreateSymbolContext(pParent, iSymbol); } return pNewNode; } CDasherNode *CAlphabetManager::CSymbolNode::RebuildSymbol(CAlphNode *pParent, symbol iSymbol, unsigned int iLbnd, unsigned int iHbnd) { if(iSymbol == this->iSymbol) { SetRange(iLbnd, iHbnd); SetParent(pParent); DASHER_ASSERT(m_iOffset == pParent->m_iOffset + 1); return this; } return m_pMgr->CreateSymbolNode(pParent, iSymbol, iLbnd, iHbnd); } CDasherNode *CAlphabetManager::CGroupNode::RebuildSymbol(CAlphNode *pParent, symbol iSymbol, unsigned int iLbnd, unsigned int iHbnd) { return m_pMgr->CreateSymbolNode(pParent, iSymbol, iLbnd, iHbnd); } void CAlphabetManager::IterateChildGroups(CAlphNode *pParent, SGroupInfo *pParentGroup, CAlphNode *buildAround) { std::vector<unsigned int> *pCProb(pParent->GetProbInfo()); const int iMin(pParentGroup ? pParentGroup->iStart : 1); const int iMax(pParentGroup ? pParentGroup->iEnd : pCProb->size()); // TODO: Think through alphabet file formats etc. to make this class easier. // TODO: Throw a warning if parent node already has children // Create child nodes and add them int i(iMin); //lowest index of child which we haven't yet added SGroupInfo *pCurrentNode(pParentGroup ? pParentGroup->pChild : m_pNCManager->GetAlphabet()->m_pBaseGroup); // The SGroupInfo structure has something like linked list behaviour // Each SGroupInfo contains a pNext, a pointer to a sibling group info while (i < iMax) { CDasherNode *pNewChild; bool bSymbol = !pCurrentNode //gone past last subgroup || i < pCurrentNode->iStart; //not reached next subgroup const int iStart=i, iEnd = (bSymbol) ? i+1 : pCurrentNode->iEnd; //uint64 is platform-dependently #defined in DasherTypes.h as an (unsigned) 64-bit int ("__int64" or "long long int") unsigned int iLbnd = (((*pCProb)[iStart-1] - (*pCProb)[iMin-1]) * (uint64)(m_pNCManager->GetLongParameter(LP_NORMALIZATION))) / ((*pCProb)[iMax-1] - (*pCProb)[iMin-1]); unsigned int iHbnd = (((*pCProb)[iEnd-1] - (*pCProb)[iMin-1]) * (uint64)(m_pNCManager->GetLongParameter(LP_NORMALIZATION))) / ((*pCProb)[iMax-1] - (*pCProb)[iMin-1]); - - if (bSymbol) { - pNewChild = (buildAround) ? buildAround->RebuildSymbol(pParent, i, iLbnd, iHbnd) : CreateSymbolNode(pParent, i, iLbnd, iHbnd); - i++; //make one symbol at a time - move onto next in next iteration - } else { //in/reached subgroup - do entire group in one go: - pNewChild= (buildAround) ? buildAround->RebuildGroup(pParent, pCurrentNode, iLbnd, iHbnd) : CreateGroupNode(pParent, pCurrentNode, iLbnd, iHbnd); - i = pCurrentNode->iEnd; //make one group at a time - so move past entire group... - pCurrentNode = pCurrentNode->pNext; + //loop for eliding groups with single children (see below). + // Variables store necessary properties of any elided groups: + std::string groupPrefix=""; int iOverrideColour=-1; + SGroupInfo *pInner=pCurrentNode; + while (true) { + if (bSymbol) { + pNewChild = (buildAround) ? buildAround->RebuildSymbol(pParent, i, iLbnd, iHbnd) : CreateSymbolNode(pParent, i, iLbnd, iHbnd); + i++; //make one symbol at a time - move onto next symbol in next iteration of (outer) loop + break; //exit inner (group elision) loop + } else if (pInner->iNumChildNodes>1) { //in/reached nontrivial subgroup - do make node for entire group: + pNewChild= (buildAround) ? buildAround->RebuildGroup(pParent, pInner, iLbnd, iHbnd) : CreateGroupNode(pParent, pInner, iLbnd, iHbnd); + i = pInner->iEnd; //make one group at a time - so move past entire group... + pCurrentNode = pCurrentNode->pNext; //next sibling of _original_ pCurrentNode (above) + // (maybe not of pCurrentNode now, which might be a subgroup filling the original) + break; //exit inner (group elision) loop + } + //were about to create a group node, which would have only one child + // (eventually, if the group node were PopulateChildren'd). + // Such a child would entirely fill it's parent (the group), and thus, + // creation/destruction of the child would cause the node's colour to flash + // between that for parent group and child. + // Hence, instead we elide the group node and create the child _here_... + + //1. however we also have to take account of the appearance of the elided group. Hence: + groupPrefix += pInner->strLabel; + if (pInner->bVisible) iOverrideColour=pInner->iColour; + //2. now go into the group... + pInner = pInner->pChild; + bSymbol = (pInner==NULL); //which might contain a single subgroup, or a single symbol + if (bSymbol) pCurrentNode = pCurrentNode->pNext; //if a symbol, we've still moved past the outer (elided) group + DASHER_ASSERT(iEnd == (bSymbol ? i+1 : pInner->iEnd)); //probability calcs still ok + //3. loop round inner loop... } + //created a new node - symbol or (group which will have >1 child). DASHER_ASSERT(pParent->GetChildren().back()==pNewChild); + //now adjust the node we've actually created, to take account of any elided group(s)... + // ick: cast away const-ness...TODO! + CDasherNode::SDisplayInfo *pChildInfo = (CDasherNode::SDisplayInfo *)pNewChild->GetDisplayInfo(); + if (iOverrideColour!=-1 && !pChildInfo->bVisible) { + pChildInfo->bVisible = true; + pChildInfo->iColour = iOverrideColour; + } + //if we've reused the existing node, make sure we don't adjust the display text twice... + if (pNewChild != buildAround) pChildInfo->strDisplayText = groupPrefix + pChildInfo->strDisplayText; } pParent->SetFlag(NF_ALLCHILDREN, true); } CAlphabetManager::CAlphNode::~CAlphNode() { delete m_pProbInfo; m_pMgr->m_pLanguageModel->ReleaseContext(iContext); } const std::string &CAlphabetManager::CSymbolNode::outputText() { return mgr()->m_pNCManager->GetAlphabet()->GetText(iSymbol); } void CAlphabetManager::CSymbolNode::Output(Dasher::VECTOR_SYMBOL_PROB* pAdded, int iNormalization) { //std::cout << this << " " << Parent() << ": Output at offset " << m_iOffset << " *" << m_pMgr->m_pNCManager->GetAlphabet()->GetText(t) << "* " << std::endl; Dasher::CEditEvent oEvent(1, outputText(), m_iOffset); m_pMgr->m_pNCManager->InsertEvent(&oEvent); // Track this symbol and its probability for logging purposes if (pAdded != NULL) { Dasher::SymbolProb sItem; sItem.sym = iSymbol; sItem.prob = Range() / (double)iNormalization; pAdded->push_back(sItem); } } void CAlphabetManager::CSymbolNode::Undo(int *pNumDeleted) { Dasher::CEditEvent oEvent(2, outputText(), m_iOffset); m_pMgr->m_pNCManager->InsertEvent(&oEvent); if (pNumDeleted) (*pNumDeleted)++; } CDasherNode *CAlphabetManager::CGroupNode::RebuildParent() { // CAlphNode's always have a parent, they inserted a symbol; CGroupNode's // with an m_pGroup have a container i.e. the parent group, unless // m_pGroup==NULL => "root" node where Alphabet->m_pBaseGroup is the *first*child*... if (m_pGroup == NULL) return NULL; //offset of group node is same as parent... return CAlphNode::RebuildParent(m_iOffset); } CDasherNode *CAlphabetManager::CSymbolNode::RebuildParent() { //parent's offset is one less than this. return CAlphNode::RebuildParent(m_iOffset-1); } CDasherNode *CAlphabetManager::CAlphNode::RebuildParent(int iNewOffset) { //possible that we have a parent, as RebuildParent() rebuilds back to closest AlphNode. if (Parent()) return Parent(); CAlphNode *pNewNode = m_pMgr->GetRoot(NULL, 0, 0, iNewOffset!=-1, iNewOffset+1); //now fill in the new node - recursively - until it reaches us m_pMgr->IterateChildGroups(pNewNode, NULL, this); //finally return our immediate parent (pNewNode may be an ancestor rather than immediate parent!) DASHER_ASSERT(Parent() != NULL); //although not required, we believe only NF_SEEN nodes are ever requested to rebuild their parents... DASHER_ASSERT(GetFlag(NF_SEEN)); //so set NF_SEEN on all created ancestors (of which pNewNode is the last) CDasherNode *pNode = this; do { pNode = pNode->Parent(); pNode->SetFlag(NF_SEEN, true); } while (pNode != pNewNode); return Parent(); } // TODO: Shouldn't there be an option whether or not to learn as we write? // For want of a better solution, game mode exemption explicit in this function void CAlphabetManager::CSymbolNode::SetFlag(int iFlag, bool bValue) { CDasherNode::SetFlag(iFlag, bValue); switch(iFlag) { case NF_COMMITTED: if(bValue && !GetFlag(NF_GAME) && m_pMgr->m_pInterface->GetBoolParameter(BP_LM_ADAPTIVE)) m_pMgr->m_pLanguageModel->LearnSymbol(m_pMgr->m_iLearnContext, iSymbol); break; } }
rgee/HFOSS-Dasher
92b69ceee95c2f289d04a5c620be7fd7bd6d9a69
iPhone tidies to viewcontrollers
diff --git a/Src/iPhone/Classes/InputMethodSelector.mm b/Src/iPhone/Classes/InputMethodSelector.mm index 403cd09..7474fc3 100644 --- a/Src/iPhone/Classes/InputMethodSelector.mm +++ b/Src/iPhone/Classes/InputMethodSelector.mm @@ -1,256 +1,256 @@ // // InputMethodSelector.mm // Dasher // // Created by Alan Lawrence on 20/04/2009. // Copyright 2009 Cavendish Laboratory. All rights reserved. // #import "InputMethodSelector.h" #import "DasherUtil.h" #import "Parameters.h" #import "Common.h" #import "DasherAppDelegate.h" #import "CalibrationController.h" #import "ParametersController.h" typedef struct __FILTER_DESC__ { NSString *title; NSString *subTitle; const char *deviceName; const char *filterName; } SFilterDesc; SFilterDesc asTouchFilters[] = { {@"Hybrid Mode", @"Tap or Hold", TOUCH_INPUT, "Stylus Control"}, {@"Boxes", @"Tap box to select", TOUCH_INPUT, "Direct Mode"}, }; SFilterDesc asDynamicFilters[] = { {@"Scanning", @"Tap screen when box highlighted", TOUCH_INPUT, "Menu Mode"}, {@"One Button Mode", @"Tap screen when cursor near", TOUCH_INPUT, "Static One Button Mode"}, {@"Dynamic 1B Mode", @"Tap anywhere - twice", TOUCH_INPUT, "Two-push Dynamic Mode (New One Button)"}, {@"Dynamic 2B Mode", @"Tap Top or Bottom", TOUCH_INPUT, "Two Button Dynamic Mode"}, }; SFilterDesc asTiltFilters[] = { {@"Full 2D",@"hold-to-go", TILT_INPUT, "Hold-down filter"}, {@"Single-axis",@"with slowdown & tap-to-start", TILT_INPUT, ONE_D_FILTER}, }; SFilterDesc asMixedFilters[] = { {@"(X,Y)", @"by (touch,tilt)", MIXED_INPUT, "Hold-down filter"}, {@"1D-mode", @"tilt for direction, X-touch for speed", MIXED_INPUT, POLAR_FILTER}, {@"(Y,X)", @"by (touch,tilt)", REVERSE_MIX, "Stylus Control"}, }; typedef struct __SECTION_DESC__ { NSString *displayName; SFilterDesc *filters; int numFilters; } SSectionDesc; SSectionDesc allMeths[] = { {@"Touch Control", asTouchFilters, sizeof(asTouchFilters) / sizeof(asTouchFilters[0])}, {@"Button Modes", asDynamicFilters, sizeof(asDynamicFilters) / sizeof(asDynamicFilters[0])}, {@"Tilt Control", asTiltFilters, sizeof(asTiltFilters) / sizeof(asTiltFilters[0])}, {@"Touch/tilt Combo", asMixedFilters, sizeof(asMixedFilters) / sizeof(asMixedFilters[0])}, }; @interface InputMethodSelector () @property (retain) NSIndexPath *selectedPath; @end @implementation InputMethodSelector @synthesize selectedPath; - (id)init { if (self = [super initWithStyle:UITableViewStyleGrouped]) { self.tabBarItem.title = @"Control"; self.tabBarItem.image = [UIImage imageNamed:@"pen.png"]; } return self; } /* - (void)viewDidLoad { [super viewDidLoad]; // Uncomment the following line to display an Edit button in the navigation bar for this view controller. // self.navigationItem.rightBarButtonItem = self.editButtonItem; } */ /* - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; } */ /* - (void)viewDidAppear:(BOOL)animated { [super viewDidAppear:animated]; } */ /* - (void)viewWillDisappear:(BOOL)animated { [super viewWillDisappear:animated]; } */ /* - (void)viewDidDisappear:(BOOL)animated { [super viewDidDisappear:animated]; } */ /* // Override to allow orientations other than the default portrait orientation. - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation { // Return YES for supported orientations return (interfaceOrientation == UIInterfaceOrientationPortrait); } */ - (void)didReceiveMemoryWarning { [super didReceiveMemoryWarning]; // Releases the view if it doesn't have a superview // Release anything that's not essential, such as cached data } #pragma mark Table view methods - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return sizeof(allMeths) / sizeof(allMeths[0]); } // Customize the number of rows in the table view. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return allMeths[section].numFilters; } // Customize the appearance of table view cells. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { DasherAppDelegate *app = [DasherAppDelegate theApp]; static NSString *CellIdentifier = @"Cell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier]; UILabel *subText; if (cell) subText = [cell viewWithTag:1]; else { cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease]; subText = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease]; subText.tag = 1; [cell addSubview:subText]; //cell.autoresizesSubviews = YES; //ineffective even if done [subText setAdjustsFontSizeToFitWidth:YES]; } // Set up the cell... SFilterDesc *filter = &allMeths[ [indexPath section] ].filters[ [indexPath row] ]; if (filter->deviceName == app.dasherInterface->GetStringParameter(SP_INPUT_DEVICE) && filter->filterName == app.dasherInterface->GetStringParameter(SP_INPUT_FILTER) && (!selectedPath || [indexPath compare:selectedPath])) { self.selectedPath = indexPath; [self performSelectorOnMainThread:@selector(doSelect) withObject:nil waitUntilDone:NO]; } UIButton *btn = [UIButton buttonWithType:UIButtonTypeDetailDisclosure]; cell.accessoryView = btn; btn.tag = (int)filter; [btn addTarget:self action:@selector(settings:) forControlEvents:UIControlEventTouchUpInside]; cell.text = filter->title; CGSize titleSize = [filter->title sizeWithFont:cell.font]; subText.frame = CGRectMake(titleSize.width + 30.0, 5.0, 245.0 - titleSize.width, 34.0); subText.text = filter->subTitle; return cell; } - (void)moduleSettingsDone { - [self dismissModalViewControllerAnimated:YES]; + [self.navigationController popViewControllerAnimated:YES]; [self doSelect]; } - (void)doSelect { [self.tableView selectRowAtIndexPath:selectedPath animated:NO scrollPosition:UITableViewScrollPositionMiddle]; } - (void)settings:(id)button { UIButton *btn = (UIButton *)button; SFilterDesc *desc = (SFilterDesc *)btn.tag; CDasherModule *mod = [DasherAppDelegate theApp].dasherInterface->GetModuleByName(desc->filterName); SModuleSettings *settings=NULL; int count=0; if (mod->GetSettings(&settings, &count)) { ParametersController *params = [[[ParametersController alloc] initWithTitle:NSStringFromStdString(desc->filterName) Settings:settings Count:count] autorelease]; [params setTarget:self Selector:@selector(moduleSettingsDone)]; - [self presentModalViewController:[[[UINavigationController alloc] initWithRootViewController:params] autorelease] animated:YES]; + [self.navigationController pushViewController:params animated:YES]; } } - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section { return allMeths[section].displayName; } - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger) section { return 40.0f; } - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath { //[tableView deselectRowAtIndexPath:indexPath animated:NO]; self.selectedPath = indexPath; DasherAppDelegate *app = [DasherAppDelegate theApp]; SFilterDesc *filter = &allMeths[ [indexPath section] ].filters[ [indexPath row] ]; app.dasherInterface->SetStringParameter(SP_INPUT_DEVICE, filter->deviceName); app.dasherInterface->SetStringParameter(SP_INPUT_FILTER, filter->filterName); } /* // Override to support conditional editing of the table view. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath { // Return NO if you do not want the specified item to be editable. return YES; } */ /* // Override to support editing the table view. - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath { if (editingStyle == UITableViewCellEditingStyleDelete) { // Delete the row from the data source [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES]; } else if (editingStyle == UITableViewCellEditingStyleInsert) { // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view } } */ /* // Override to support rearranging the table view. - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath { } */ /* // Override to support conditional rearranging of the table view. - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath { // Return NO if you do not want the item to be re-orderable. return YES; } */ - (void)dealloc { [super dealloc]; } @end diff --git a/Src/iPhone/Classes/ParametersController.h b/Src/iPhone/Classes/ParametersController.h index c8921a0..1fb7a18 100644 --- a/Src/iPhone/Classes/ParametersController.h +++ b/Src/iPhone/Classes/ParametersController.h @@ -1,22 +1,20 @@ // // ParametersController.h // Dasher // // Created by Alan Lawrence on 10/02/2010. // Copyright 2010 Cavendish Laboratory. All rights reserved. // #import <UIKit/UIKit.h> #import "ModuleSettings.h" @interface ParametersController : UIViewController { SModuleSettings *settings; int count; - id targetOnDone; - SEL selector; } -(id)initWithTitle:(NSString *)title Settings:(SModuleSettings *)settings Count:(int)count; -(void)setTarget:(id)target Selector:(SEL)selector; @end
rgee/HFOSS-Dasher
c4a51bd43a54ab835b401e88dcd1bc5fa55c1fde
Rename IsNodeVisible to IsSpaceAroundNode, and make it's meaning consistent!
diff --git a/Src/DasherCore/DasherModel.cpp b/Src/DasherCore/DasherModel.cpp index 0dc3a75..5430cb8 100644 --- a/Src/DasherCore/DasherModel.cpp +++ b/Src/DasherCore/DasherModel.cpp @@ -1,807 +1,810 @@ // DasherModel.cpp // // Copyright (c) 2008 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" #include <iostream> #include <cstring> #include "../Common/Random.h" #include "DasherModel.h" #include "DasherView.h" #include "Parameters.h" #include "Event.h" #include "DasherInterfaceBase.h" #include "NodeCreationManager.h" #include "DasherGameMode.h" #include "AlphabetManager.h" using namespace Dasher; using namespace std; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG_MEMLEAKS #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif // FIXME - need to get node deletion working properly and implement reference counting // CDasherModel CDasherModel::CDasherModel(CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CNodeCreationManager *pNCManager, CDasherInterfaceBase *pDasherInterface, CDasherView *pView, int iOffset) : CFrameRate(pEventHandler, pSettingsStore) { m_pNodeCreationManager = pNCManager; m_pDasherInterface = pDasherInterface; m_bGameMode = GetBoolParameter(BP_GAME_MODE); m_iOffset = iOffset; // TODO: Set through build routine DASHER_ASSERT(m_pNodeCreationManager != NULL); DASHER_ASSERT(m_pDasherInterface != NULL); m_pLastOutput = m_Root = NULL; m_Rootmin = 0; m_Rootmax = 0; m_iDisplayOffset = 0; m_dTotalNats = 0.0; // TODO: Need to rationalise the require conversion methods #ifdef JAPANESE m_bRequireConversion = true; #else m_bRequireConversion = false; #endif SetBoolParameter(BP_CONVERSION_MODE, m_bRequireConversion); m_dAddProb = 0.003; int iNormalization = GetLongParameter(LP_NORMALIZATION); m_Rootmin_min = int64_min / iNormalization / 2; m_Rootmax_max = int64_max / iNormalization / 2; InitialiseAtOffset(iOffset, pView); } CDasherModel::~CDasherModel() { if (m_pLastOutput) m_pLastOutput->Leave(); if(oldroots.size() > 0) { delete oldroots[0]; oldroots.clear(); // At this point we have also deleted the root - so better NULL pointer m_Root = NULL; } else { delete m_Root; m_Root = NULL; } } void CDasherModel::HandleEvent(Dasher::CEvent *pEvent) { CFrameRate::HandleEvent(pEvent); if(pEvent->m_iEventType == EV_PARAM_NOTIFY) { Dasher::CParameterNotificationEvent * pEvt(static_cast < Dasher::CParameterNotificationEvent * >(pEvent)); switch (pEvt->m_iParameter) { case BP_CONTROL_MODE: // Rebuild the model if control mode is switched on/off RebuildAroundCrosshair(); break; case BP_SMOOTH_OFFSET: if (!GetBoolParameter(BP_SMOOTH_OFFSET)) //smoothing has just been turned off. End any transition/jump currently // in progress at it's current point AbortOffset(); break; case BP_DASHER_PAUSED: if(GetBoolParameter(BP_SLOW_START)) TriggerSlowdown(); //else, leave m_iStartTime as is - will result in no slow start break; case BP_GAME_MODE: m_bGameMode = GetBoolParameter(BP_GAME_MODE); // Maybe reload something here to begin game mode? break; default: break; } } else if(pEvent->m_iEventType == EV_EDIT) { // Keep track of where we are in the buffer CEditEvent *pEditEvent(static_cast < CEditEvent * >(pEvent)); if(pEditEvent->m_iEditType == 1) { m_iOffset += pEditEvent->m_sText.size(); } else if(pEditEvent->m_iEditType == 2) { m_iOffset -= pEditEvent->m_sText.size(); } } } void CDasherModel::Make_root(CDasherNode *pNewRoot) { // std::cout << "Make root" << std::endl; DASHER_ASSERT(pNewRoot != NULL); DASHER_ASSERT(pNewRoot->Parent() == m_Root); m_Root->SetFlag(NF_COMMITTED, true); // TODO: Is the stack necessary at all? We may as well just keep the // existing data structure? oldroots.push_back(m_Root); // TODO: tidy up conditional while((oldroots.size() > 10) && (!m_bRequireConversion || (oldroots[0]->GetFlag(NF_CONVERTED)))) { oldroots[0]->OrphanChild(oldroots[1]); delete oldroots[0]; oldroots.pop_front(); } m_Root = pNewRoot; // Update the root coordinates, as well as any currently scheduled locations const myint range = m_Rootmax - m_Rootmin; m_Rootmax = m_Rootmin + (range * m_Root->Hbnd()) / GetLongParameter(LP_NORMALIZATION); m_Rootmin = m_Rootmin + (range * m_Root->Lbnd()) / GetLongParameter(LP_NORMALIZATION); for(std::deque<SGotoItem>::iterator it(m_deGotoQueue.begin()); it != m_deGotoQueue.end(); ++it) { const myint r = it->iN2 - it->iN1; it->iN2 = it->iN1 + (r * m_Root->Hbnd()) / GetLongParameter(LP_NORMALIZATION); it->iN1 = it->iN1 + (r * m_Root->Lbnd()) / GetLongParameter(LP_NORMALIZATION); } } void CDasherModel::RecursiveMakeRoot(CDasherNode *pNewRoot) { DASHER_ASSERT(pNewRoot != NULL); DASHER_ASSERT(m_Root != NULL); if(pNewRoot == m_Root) return; // TODO: we really ought to check that pNewRoot is actually a // descendent of the root, although that should be guaranteed if(pNewRoot->Parent() != m_Root) RecursiveMakeRoot(pNewRoot->Parent()); Make_root(pNewRoot); } // only used when BP_CONTROL changes, so not very often. void CDasherModel::RebuildAroundCrosshair() { CDasherNode *pNode = Get_node_under_crosshair(); DASHER_ASSERT(pNode != NULL); DASHER_ASSERT(pNode == m_pLastOutput); RecursiveMakeRoot(pNode); DASHER_ASSERT(m_Root == pNode); ClearRootQueue(); m_Root->Delete_children(); m_Root->PopulateChildren(); } void CDasherModel::Reparent_root() { DASHER_ASSERT(m_Root != NULL); // Change the root node to the parent of the existing node. We need // to recalculate the coordinates for the "new" root as the user may // have moved around within the current root CDasherNode *pNewRoot; if(oldroots.size() == 0) { pNewRoot = m_Root->RebuildParent(); // Return if there's no existing parent and no way of recreating one if(pNewRoot == NULL) return; } else { pNewRoot = oldroots.back(); oldroots.pop_back(); } pNewRoot->SetFlag(NF_COMMITTED, false); DASHER_ASSERT(m_Root->Parent() == pNewRoot); const myint lower(m_Root->Lbnd()), upper(m_Root->Hbnd()); const myint iRange(upper-lower); myint iRootWidth(m_Rootmax - m_Rootmin); // Fail if the new root is bigger than allowed by normalisation if(((myint((GetLongParameter(LP_NORMALIZATION) - upper)) / static_cast<double>(iRange)) > (m_Rootmax_max - m_Rootmax)/static_cast<double>(iRootWidth)) || ((myint(lower) / static_cast<double>(iRange)) > (m_Rootmin - m_Rootmin_min) / static_cast<double>(iRootWidth))) { //but cache the (currently-unusable) root node - else we'll keep recreating (and deleting) it on every frame... oldroots.push_back(pNewRoot); return; } //Update the root coordinates to reflect the new root m_Root = pNewRoot; m_Rootmax = m_Rootmax + ((GetLongParameter(LP_NORMALIZATION) - upper) * iRootWidth) / iRange; m_Rootmin = m_Rootmin - (lower * iRootWidth) / iRange; for(std::deque<SGotoItem>::iterator it(m_deGotoQueue.begin()); it != m_deGotoQueue.end(); ++it) { iRootWidth = it->iN2 - it->iN1; it->iN2 = it->iN2 + (myint((GetLongParameter(LP_NORMALIZATION) - upper)) * iRootWidth / iRange); it->iN1 = it->iN1 - (myint(lower) * iRootWidth / iRange); } } void CDasherModel::ClearRootQueue() { while(oldroots.size() > 0) { if(oldroots.size() > 1) { oldroots[0]->OrphanChild(oldroots[1]); } else { oldroots[0]->OrphanChild(m_Root); } delete oldroots[0]; oldroots.pop_front(); } } CDasherNode *CDasherModel::Get_node_under_crosshair() { DASHER_ASSERT(m_Root != NULL); return m_Root->Get_node_under(GetLongParameter(LP_NORMALIZATION), m_Rootmin + m_iDisplayOffset, m_Rootmax + m_iDisplayOffset, GetLongParameter(LP_OX), GetLongParameter(LP_OY)); } void CDasherModel::DeleteTree() { ClearRootQueue(); delete m_Root; m_Root = NULL; } void CDasherModel::InitialiseAtOffset(int iOffset, CDasherView *pView) { if (m_pLastOutput) m_pLastOutput->Leave(); DeleteTree(); m_Root = m_pNodeCreationManager->GetAlphRoot(NULL, 0,GetLongParameter(LP_NORMALIZATION), iOffset!=0, iOffset); m_pLastOutput = (m_Root->GetFlag(NF_SEEN)) ? m_Root : NULL; // Create children of the root... ExpandNode(m_Root); // Set the root coordinates so that the root node is an appropriate // size and we're not in any of the children double dFraction( 1 - (1 - m_Root->MostProbableChild() / static_cast<double>(GetLongParameter(LP_NORMALIZATION))) / 2.0 ); int iWidth( static_cast<int>( (GetLongParameter(LP_MAX_Y) / (2.0*dFraction)) ) ); m_Rootmin = GetLongParameter(LP_MAX_Y) / 2 - iWidth / 2; m_Rootmax = GetLongParameter(LP_MAX_Y) / 2 + iWidth / 2; m_iDisplayOffset = 0; //now (re)create parents, while they show on the screen + // - if we were lazy, we could leave this to NewFrame, + // and one node around the root would be recreated per frame, + // but we'll do it properly here. if(pView) { - while(pView->IsNodeVisible(m_Rootmin,m_Rootmax)) { + while(pView->IsSpaceAroundNode(m_Rootmin,m_Rootmax)) { CDasherNode *pOldRoot = m_Root; Reparent_root(); if(m_Root == pOldRoot) break; } } // TODO: See if this is better positioned elsewhere m_pDasherInterface->ScheduleRedraw(); } void CDasherModel::Get_new_root_coords(dasherint X, dasherint Y, dasherint &r1, dasherint &r2, unsigned long iTime) { DASHER_ASSERT(m_Root != NULL); if(m_iStartTime == 0) m_iStartTime = iTime; int iSteps = Steps(); double dFactor; if(GetBoolParameter(BP_SLOW_START) && ((iTime - m_iStartTime) < GetLongParameter(LP_SLOW_START_TIME))) dFactor = 0.1 * (1 + 9 * ((iTime - m_iStartTime) / static_cast<double>(GetLongParameter(LP_SLOW_START_TIME)))); else dFactor = 1.0; iSteps = static_cast<int>(iSteps / dFactor); // Avoid X == 0, as this corresponds to infinite zoom if (X <= 0) X = 1; // If X is too large we risk overflow errors, so limit it dasherint iMaxX = (1 << 29) / iSteps; if (X > iMaxX) X = iMaxX; // Mouse coords X, Y // new root{min,max} r1,r2, old root{min,max} R1,R2 const dasherint R1 = m_Rootmin; const dasherint R2 = m_Rootmax; // const dasherint Y1 = 0; dasherint Y2(GetLongParameter(LP_MAX_Y)); dasherint iOX(GetLongParameter(LP_OX)); dasherint iOY(GetLongParameter(LP_OY)); // Calculate what the extremes of the viewport will be when the // point under the cursor is at the cross-hair. This is where // we want to be in iSteps updates dasherint y1(Y - (Y2 * X) / (2 * iOX)); dasherint y2(Y + (Y2 * X) / (2 * iOY)); // iSteps is the number of update steps we need to get the point // under the cursor over to the cross hair. Calculated in order to // keep a constant bit-rate. DASHER_ASSERT(iSteps > 0); // Calculate the new values of y1 and y2 required to perform a single update // step. dasherint newy1, newy2, denom; denom = Y2 + (iSteps - 1) * (y2 - y1); newy1 = y1 * Y2 / denom; newy2 = ((y2 * iSteps - y1 * (iSteps - 1)) * Y2) / denom; y1 = newy1; y2 = newy2; // Calculate the minimum size of the viewport corresponding to the // maximum zoom. dasherint iMinSize(MinSize(Y2, dFactor)); if((y2 - y1) < iMinSize) { newy1 = y1 * (Y2 - iMinSize) / (Y2 - (y2 - y1)); newy2 = newy1 + iMinSize; y1 = newy1; y2 = newy2; } // If |(0,Y2)| = |(y1,y2)|, the "zoom factor" is 1, so we just translate. if (Y2 == y2 - y1) { r1 = R1 - y1; r2 = R2 - y1; return; } // There is a point C on the y-axis such the ratios (y1-C):(Y1-C) and // (y2-C):(Y2-C) are equal. (Obvious when drawn on separate parallel axes.) const dasherint C = (y1 * Y2) / (y1 + Y2 - y2); r1 = ((R1 - C) * Y2) / (y2 - y1) + C; r2 = ((R2 - C) * Y2) / (y2 - y1) + C; } bool CDasherModel::NextScheduledStep(unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB *pAdded, int *pNumDeleted) { DASHER_ASSERT (!GetBoolParameter(BP_DASHER_PAUSED) || m_deGotoQueue.size()==0); if (m_deGotoQueue.size() == 0) return false; myint iNewMin, iNewMax; iNewMin = m_deGotoQueue.front().iN1; iNewMax = m_deGotoQueue.front().iN2; m_deGotoQueue.pop_front(); UpdateBounds(iNewMin, iNewMax, iTime, pAdded, pNumDeleted); if (m_deGotoQueue.size() == 0) SetBoolParameter(BP_DASHER_PAUSED, true); return true; } void CDasherModel::OneStepTowards(myint miMousex, myint miMousey, unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { DASHER_ASSERT(!GetBoolParameter(BP_DASHER_PAUSED)); myint iNewMin, iNewMax; // works out next viewpoint Get_new_root_coords(miMousex, miMousey, iNewMin, iNewMax, iTime); UpdateBounds(iNewMin, iNewMax, iTime, pAdded, pNumDeleted); } void CDasherModel::UpdateBounds(myint iNewMin, myint iNewMax, unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { m_dTotalNats += log((iNewMax - iNewMin) / static_cast<double>(m_Rootmax - m_Rootmin)); // Now actually zoom to the new location NewGoTo(iNewMin, iNewMax, pAdded, pNumDeleted); // Check whether new nodes need to be created ExpandNode(Get_node_under_crosshair()); // This'll get done again when we render the frame, later, but we use NF_SEEN // (set here) to ensure the node under the cursor can never be collapsed // (even when the node budget is exceeded) when we do the rendering... HandleOutput(pAdded, pNumDeleted); } void CDasherModel::RecordFrame(unsigned long Time) { CFrameRate::RecordFrame(Time); ///GAME MODE TEMP///Pass new frame events onto our teacher GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher(); if(m_bGameMode && pTeacher) pTeacher->NewFrame(Time); } void CDasherModel::RecursiveOutput(CDasherNode *pNode, Dasher::VECTOR_SYMBOL_PROB* pAdded) { if(pNode->Parent()) { if (!pNode->Parent()->GetFlag(NF_SEEN)) RecursiveOutput(pNode->Parent(), pAdded); pNode->Parent()->Leave(); } pNode->Enter(); m_pLastOutput = pNode; pNode->SetFlag(NF_SEEN, true); pNode->Output(pAdded, GetLongParameter(LP_NORMALIZATION)); // If the node we are outputting is the last one in a game target sentence, then // notify the game mode teacher. if(m_bGameMode) if(pNode->GetFlag(NF_END_GAME)) GameMode::CDasherGameMode::GetTeacher()->SentenceFinished(); } void CDasherModel::NewGoTo(myint newRootmin, myint newRootmax, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { // Update the max and min of the root node to make iTargetMin and // iTargetMax the edges of the viewport. if(newRootmin + m_iDisplayOffset > (myint)GetLongParameter(LP_MAX_Y) / 2 - 1) newRootmin = (myint)GetLongParameter(LP_MAX_Y) / 2 - 1 - m_iDisplayOffset; if(newRootmax + m_iDisplayOffset < (myint)GetLongParameter(LP_MAX_Y) / 2 + 1) newRootmax = (myint)GetLongParameter(LP_MAX_Y) / 2 + 1 - m_iDisplayOffset; // Check that we haven't drifted too far. The rule is that we're not // allowed to let the root max and min cross the midpoint of the // screen. if(newRootmax < m_Rootmax_max && newRootmin > m_Rootmin_min) { // Only update if we're not making things big enough to risk // overflow. (Otherwise, forcibly choose a new root node, below) if ((newRootmax - newRootmin) > (myint)GetLongParameter(LP_MAX_Y) / 4) { // Also don't allow the update if it will result in making the // root too small. We should have re-generated a deeper root // before now already, but the original root is an exception. m_Rootmax = newRootmax; m_Rootmin = newRootmin; } //else, we just stop - this prevents the user from zooming too far back //outside the root node (when we can't generate an older root). m_iDisplayOffset = (m_iDisplayOffset * 90) / 100; } else { // can't make existing root any bigger because of overflow. So force a new root // to be chosen (so that Dasher doesn't just stop!)... //pick _child_ covering crosshair... const myint iWidth(m_Rootmax-m_Rootmin); for (CDasherNode::ChildMap::const_iterator it = m_Root->GetChildren().begin(), E = m_Root->GetChildren().end(); it!=E; it++) { CDasherNode *pChild(*it); DASHER_ASSERT(m_Rootmin + ((pChild->Lbnd() * iWidth) / GetLongParameter(LP_NORMALIZATION)) <= GetLongParameter(LP_OY)); if (m_Rootmin + ((pChild->Hbnd() * iWidth) / GetLongParameter(LP_NORMALIZATION)) > GetLongParameter(LP_OY)) { //proceed only if new root is on the game path. If the user's strayed // that far off the game path, having Dasher stop seems reasonable! if (!m_bGameMode || !pChild->GetFlag(NF_GAME)) { //make pChild the root node...but put (newRootmin,newRootmax) somewhere there'll be converted: SGotoItem temp; temp.iN1 = newRootmin; temp.iN2 = newRootmax; m_deGotoQueue.push_back(temp); m_Root->DeleteNephews(pChild); RecursiveMakeRoot(pChild); temp=m_deGotoQueue.back(); m_deGotoQueue.pop_back(); // std::cout << "NewGoto Recursing - was (" << newRootmin << "," << newRootmax << "), now (" << temp.iN1 << "," << temp.iN2 << ")" << std::endl; NewGoTo(temp.iN1, temp.iN2, pAdded,pNumDeleted); } return; } } DASHER_ASSERT(false); //did not find a child covering crosshair...?! } } void CDasherModel::HandleOutput(Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { CDasherNode *pNewNode = Get_node_under_crosshair(); DASHER_ASSERT(pNewNode != NULL); // std::cout << "HandleOutput: " << m_pLastOutput << " => " << pNewNode << std::endl; CDasherNode *pLastSeen = pNewNode; while (pLastSeen && !pLastSeen->GetFlag(NF_SEEN)) pLastSeen = pLastSeen->Parent(); while (m_pLastOutput != pLastSeen) { m_pLastOutput->Undo(pNumDeleted); m_pLastOutput->Leave(); //Should we? I think so, but the old code didn't...? m_pLastOutput->SetFlag(NF_SEEN, false); m_pLastOutput = m_pLastOutput->Parent(); if (m_pLastOutput) m_pLastOutput->Enter(); } if(!pNewNode->GetFlag(NF_SEEN)) { RecursiveOutput(pNewNode, pAdded); } } void CDasherModel::ExpandNode(CDasherNode *pNode) { DASHER_ASSERT(pNode != NULL); // TODO: Is NF_ALLCHILDREN any more useful/efficient than reading the map size? if(pNode->GetFlag(NF_ALLCHILDREN)) { DASHER_ASSERT(pNode->GetChildren().size() > 0); return; } // TODO: Do we really need to delete all of the children at this point? pNode->Delete_children(); // trial commented out - pconlon #ifdef DEBUG unsigned int iExpect = pNode->ExpectedNumChildren(); #endif pNode->PopulateChildren(); #ifdef DEBUG if (iExpect != pNode->GetChildren().size()) { std::cout << "(Note: expected " << iExpect << " children, actually created " << pNode->GetChildren().size() << ")" << std::endl; } #endif pNode->SetFlag(NF_ALLCHILDREN, true); // We get here if all our children (groups) and grandchildren (symbols) are created. // So lets find the correct letters. ///GAME MODE TEMP/////////// // If we are in GameMode, then we do a bit of cooperation with the teacher object when we create // new children. GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher(); if(m_bGameMode && pNode->GetFlag(NF_GAME) && pTeacher ) { std::string strTargetUtf8Char(pTeacher->GetSymbolAtOffset(pNode->m_iOffset + 1)); // Check if this is the last node in the sentence... if(strTargetUtf8Char == "GameEnd") pNode->SetFlag(NF_END_GAME, true); else if (!pNode->GameSearchChildren(strTargetUtf8Char)) { // Target character not found - not in our current alphabet?!?! // Let's give up! pNode->SetFlag(NF_END_GAME, true); } } //////////////////////////// } bool CDasherModel::RenderToView(CDasherView *pView, CExpansionPolicy &policy) { DASHER_ASSERT(pView != NULL); DASHER_ASSERT(m_Root != NULL); // XXX we HandleOutput in RenderToView // DASHER_ASSERT(Get_node_under_crosshair() == m_pLastOutput); bool bReturnValue = false; // The Render routine will fill iGameTargetY with the Dasher Coordinate of the // youngest node with NF_GAME set. The model is responsible for setting NF_GAME on // the appropriate Nodes. pView->Render(m_Root, m_Rootmin + m_iDisplayOffset, m_Rootmax + m_iDisplayOffset, policy, true); /////////GAME MODE TEMP////////////// if(m_bGameMode) if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) { //ACL 27/10/09 I note the following vector: std::vector<std::pair<myint,bool> > vGameTargetY; //was declared earlier and passed to pView->Render, above; but pView->Render //would never do _anything_ to it. Hence the below seems a bit redundant too, //but leaving around for now as a reminder that Game Mode generally is a TODO. pTeacher->SetTargetY(vGameTargetY); } ////////////////////////////////////// // TODO: Fix up stats // TODO: Is this the right way to handle this? HandleOutput(NULL, NULL); //ACL Off-screen nodes (zero collapse cost) will have been collapsed already. //Hence, this acts to maintain the node budget....or whatever the queue's policy is! if (policy.apply(m_pNodeCreationManager,this)) bReturnValue=true; return bReturnValue; } bool CDasherModel::CheckForNewRoot(CDasherView *pView) { DASHER_ASSERT(m_Root != NULL); // TODO: pView is redundant here #ifdef DEBUG CDasherNode *pOldNode = Get_node_under_crosshair(); #endif CDasherNode *root(m_Root); if(!(m_Root->GetFlag(NF_SUPER))) { Reparent_root(); return(m_Root != root); } CDasherNode *pNewRoot = NULL; for (CDasherNode::ChildMap::const_iterator it = m_Root->GetChildren().begin(); it != m_Root->GetChildren().end(); it++) { if ((*it)->GetFlag(NF_SUPER)) { //at most one child should have NF_SUPER set... DASHER_ASSERT(pNewRoot == NULL); pNewRoot = *it; #ifndef DEBUG break; #endif } } ////GAME MODE TEMP - only change the root if it is on the game path///////// if (pNewRoot && (!m_bGameMode || pNewRoot->GetFlag(NF_GAME))) { m_Root->DeleteNephews(pNewRoot); RecursiveMakeRoot(pNewRoot); } DASHER_ASSERT(Get_node_under_crosshair() == pOldNode); return false; } void CDasherModel::ScheduleZoom(long time, dasherint X, dasherint Y, int iMaxZoom) { // 1 = min, 2 = max. y1, y2 is the length we select from Y1, Y2. With // that ratio we calculate the new root{min,max} r1, r2 from current R1, R2. const int nsteps = GetLongParameter(LP_ZOOMSTEPS); const int safety = GetLongParameter(LP_S); // over safety_denom gives % const int safety_denom = 1024; const int ymax = GetLongParameter(LP_MAX_Y); const int scale = ymax; // (0,1) -> (ymin=0,ymax) // (X,Y) is mouse position in dasher coordinates // Prevent clicking too far to the right => y1 <> y2 see below if (X < 2) X = 2; // Lines with gradient +/- 1 passing through (X,Y) intersect y-axis at dasherint y1 = Y - X; // y = x + (Y - X) dasherint y2 = Y + X; // y = -x + (Y + X) // Rename for readability. const dasherint Y1 = 0; const dasherint Y2 = ymax; const dasherint R1 = m_Rootmin; const dasherint R2 = m_Rootmax; // So, want to zoom (y1 - safety/2, y2 + safety/2) -> (Y1, Y2) // Adjust y1, y2 for safety margin dasherint ds = (safety * scale) / (2 * safety_denom); y1 -= ds; y2 += ds; dasherint C, r1, r2; // If |(y1,y2)| = |(Y1,Y2)|, the "zoom factor" is 1, so we just translate. // y2 - y1 == Y2 - Y1 => y1 - Y1 == y2 - Y2 C = y1 - Y1; if (C == y2 - Y2) { r1 = R1 + C; r2 = R2 + C; } else { // There is a point C on the y-axis such the ratios (y1-C):(Y1-C) and // (y2-C):(Y2-C) are equal. (Obvious when drawn on separate parallel axes.) C = (y1 * Y2 - y2 * Y1) / (y1 + Y2 - y2 - Y1); // So another point r's zoomed y coordinate R, has the same ratio (r-C):(R-C) if (y1 != C) { r1 = ((R1 - C) * (Y1 - C)) / (y1 - C) + C; r2 = ((R2 - C) * (Y1 - C)) / (y1 - C) + C; } else if (y2 != C) { r1 = ((R1 - C) * (Y2 - C)) / (y2 - C) + C; r2 = ((R2 - C) * (Y2 - C)) / (y2 - C) + C; } else { // implies y1 = y2 std::cerr << "Impossible geometry in CDasherModel::ScheduleZoom\n"; } // iMaxZoom seems to be in tenths if (iMaxZoom != 0 && 10 * (r2 - r1) > iMaxZoom * (R2 - R1)) { r1 = ((R1 - C) * iMaxZoom) / 10 + C; r2 = ((R2 - C) * iMaxZoom) / 10 + C; } } // sNewItem seems to contain a list of root{min,max} for the frames of the // zoom, so split r -> R into n steps, with accurate R m_deGotoQueue.clear(); for (int s = nsteps - 1; s >= 0; --s) { SGotoItem sNewItem; sNewItem.iN1 = r1 - (s * (r1 - R1)) / nsteps; sNewItem.iN2 = r2 - (s * (r2 - R2)) / nsteps; m_deGotoQueue.push_back(sNewItem); } //steps having been scheduled, we're gonna start moving accordingly... m_pDasherInterface->Unpause(time); } void CDasherModel::ClearScheduledSteps() { m_deGotoQueue.clear(); } void CDasherModel::Offset(int iOffset) { m_Rootmin += iOffset; m_Rootmax += iOffset; if (GetBoolParameter(BP_SMOOTH_OFFSET)) m_iDisplayOffset -= iOffset; } void CDasherModel::AbortOffset() { m_Rootmin += m_iDisplayOffset; m_Rootmax += m_iDisplayOffset; m_iDisplayOffset = 0; } void CDasherModel::LimitRoot(int iMaxWidth) { m_Rootmin = GetLongParameter(LP_MAX_Y) / 2 - iMaxWidth / 2; m_Rootmax = GetLongParameter(LP_MAX_Y) / 2 + iMaxWidth / 2; } void CDasherModel::SetOffset(int iLocation, CDasherView *pView) { if(iLocation == m_iOffset) return; // We're already there // std::cout << "Initialising at offset: " << iLocation << std::endl; // TODO: Special cases, ie this can be done without rebuilding the // model m_iOffset = iLocation; // Now actually rebuild the model InitialiseAtOffset(iLocation, pView); } void CDasherModel::SetControlOffset(int iOffset) { // This is a hack, making many dubious assumptions which happen to // work right now. CDasherNode *pNode = Get_node_under_crosshair(); pNode->SetControlOffset(iOffset); } diff --git a/Src/DasherCore/DasherView.h b/Src/DasherCore/DasherView.h index 28416f7..9ef110a 100644 --- a/Src/DasherCore/DasherView.h +++ b/Src/DasherCore/DasherView.h @@ -1,212 +1,212 @@ // DasherView.h // // Copyright (c) 2001-2005 David Ward #ifndef __DasherView_h_ #define __DasherView_h_ namespace Dasher { class CDasherModel; class CDasherInput; // Why does DasherView care about input? - pconlon class CDasherComponent; class CDasherView; class CDasherNode; } #include "DasherTypes.h" #include "DasherComponent.h" #include "ExpansionPolicy.h" #include "DasherScreen.h" /// \defgroup View Visualisation of the model /// @{ /// \brief View base class. /// /// Dasher views represent the visualisation of a Dasher model on the screen. /// /// Note that we really should aim to avoid having to try and keep /// multiple pointers to the same object (model etc.) up-to-date at /// once. We should be able to avoid the need for this just by being /// sane about passing pointers as arguments to the relevant /// functions, for example we could pass a pointer to the canvas every /// time we call the render routine, rather than worrying about /// notifying this object every time it changes. The same logic can be /// applied in several other places. /// /// We should also attempt to try and remove the need for this class /// to know about the model. When we call render we should just pass a /// pointer to the root node, which we can obtain elsewhere, and make /// sure that the data structure contains all the info we need to do /// the rendering (eg make sure it contains strings as well as symbol /// IDs). /// /// There are really three roles played by CDasherView: providing high /// level drawing functions, providing a mapping between Dasher /// co-ordinates and screen co-ordinates and providing a mapping /// between true and effective Dasher co-ordinates (eg for eyetracking /// mode). We should probably consider creating separate classes for /// these. class Dasher::CDasherView : public Dasher::CDasherComponent { public: /// Constructor /// /// \param pEventHandler Pointer to the event handler /// \param pSettingsStore Pointer to the settings store /// \param DasherScreen Pointer to the CDasherScreen object used to do rendering CDasherView(CEventHandler * pEventHandler, CSettingsStore * pSettingsStore, CDasherScreen * DasherScreen); virtual ~CDasherView() { } /// @name Pointing device mappings /// @{ /// Set the input device class. Note that this class will now assume ownership of the pointer, ie it will delete the object when it's done with it. /// \param _pInput Pointer to the new CDasherInput. void SetInput(CDasherInput * _pInput); void SetDemoMode(bool); void SetGameMode(bool); /// Translates the screen coordinates to Dasher coordinates and calls /// dashermodel.TapOnDisplay virtual int GetCoordinates(myint &iDasherX, myint &iDasherY); /// Get the co-ordinate count from the input device int GetCoordinateCount(); /// @} /// /// @name Coordinate system conversion /// Convert between screen and Dasher coordinates /// @{ /// /// Convert a screen co-ordinate to Dasher co-ordinates /// virtual void Screen2Dasher(screenint iInputX, screenint iInputY, myint & iDasherX, myint & iDasherY) = 0; /// /// Convert Dasher co-ordinates to screen co-ordinates /// virtual void Dasher2Screen(myint iDasherX, myint iDasherY, screenint & iScreenX, screenint & iScreenY) = 0; /// /// Convert Dasher co-ordinates to polar co-ordinates (r,theta), with 0<r<1, 0<theta<2*pi /// virtual void Dasher2Polar(myint iDasherX, myint iDasherY, double &r, double &theta) = 0; - virtual bool IsNodeVisible(myint y1, myint y2) { return true; }; + virtual bool IsSpaceAroundNode(myint y1, myint y2)=0; virtual void VisibleRegion( myint &iDasherMinX, myint &iDasherMinY, myint &iDasherMaxX, myint &iDasherMaxY ) = 0; /// @} /// Change the screen - must be called if the Screen is replaced or resized /// \param NewScreen Pointer to the new CDasherScreen. virtual void ChangeScreen(CDasherScreen * NewScreen); /// @name High level drawing /// Drawing more complex structures, generally implemented by derived class /// @{ /// Renders Dasher with mouse-dependent items /// \todo Clarify relationship between Render functions and probably only expose one virtual void Render(CDasherNode *pRoot, myint iRootMin, myint iRootMax, CExpansionPolicy &policy, bool bRedrawDisplay); /// @} ////// Return a reference to the screen - can't be protected due to circlestarthandler CDasherScreen *Screen() { return m_pScreen; } /// /// @name Low level drawing /// Basic drawing primitives specified in Dasher coordinates. /// @{ ///Draw a straight line in Dasher-space - which may be curved on the screen... void DasherSpaceLine(myint x1, myint y1, myint x2, myint y2, int iWidth, int iColour); /// /// Draw a polyline specified in Dasher co-ordinates /// void DasherPolyline(myint * x, myint * y, int n, int iWidth, int iColour); /// Draw a polyarrow void DasherPolyarrow(myint * x, myint * y, int n, int iWidth, int iColour, double dArrowSizeFactor = 0.7071); /// /// Draw a rectangle specified in Dasher co-ordinates /// Color of -1 => no fill; any other value => fill in that color /// iOutlineColor of -1 => no outline; any other value => outline in that color, EXCEPT /// Thickness < 1 => no outline. /// void DasherDrawRectangle(myint iLeft, myint iTop, myint iRight, myint iBottom, const int Color, int iOutlineColour, Opts::ColorSchemes ColorScheme, int iThickness); /// /// Draw a centred rectangle specified in Dasher co-ordinates (used for mouse cursor) /// void DasherDrawCentredRectangle(myint iDasherX, myint iDasherY, screenint iSize, const int Color, Opts::ColorSchemes ColorScheme, bool bDrawOutline); void DrawText(const std::string & str, myint x, myint y, int Size, int iColor); /// Request the Screen to copy its buffer to the Display /// \todo Shouldn't be public? void Display(); /// @} protected: /// Clips a line (specified in Dasher co-ordinates) to the visible region /// by intersecting with all boundaries. /// \return true if any part of the line was within the visible region; in this case, (x1,y1)-(x2,y2) delineate exactly that part /// false if the line would be entirely outside the visible region; x1, y1, x2, y2 unaffected. bool ClipLineToVisible(myint &x1, myint &y1, myint &x2, myint &y2); ///Convert a straight line in Dasher-space, to coordinates for a corresponding polyline on the screen /// (because of nonlinearity, this may require multiple line segments) /// \param x1,y1 Dasher co-ordinates of start of line segment; note that these are guaranteed within VisibleRegion. /// \param x2,y2 Dasher co-ordinates of end of line segment; also guaranteed within VisibleRegion. /// \param vPoints vector to which to add screen points. Note that at the point that DasherLine2Screen is called, /// the screen coordinates of the first point should already have been added to this vector; DasherLine2Screen /// will then add exactly one CDasherScreen::point for each line segment required. virtual void DasherLine2Screen(myint x1, myint y1, myint x2, myint y2, std::vector<CDasherScreen::point> &vPoints)=0; // Orientation of Dasher Screen /* inline void MapScreen(screenint * DrawX, screenint * DrawY); */ /* inline void UnMapScreen(screenint * DrawX, screenint * DrawY); */ bool m_bVisibleRegionValid; int m_iRenderCount; private: CDasherScreen *m_pScreen; // provides the graphics (text, lines, rectangles): CDasherInput *m_pInput; // Input device abstraction /// Renders the Dasher node structure virtual void RenderNodes(CDasherNode *pRoot, myint iRootMin, myint iRootMax, CExpansionPolicy &policy) = 0; /// Get the co-ordinates from the input device int GetInputCoordinates(int iN, myint * pCoordinates); bool m_bDemoMode; bool m_bGameMode; }; /// @} #endif /* #ifndef __DasherView_h_ */ diff --git a/Src/DasherCore/DasherViewSquare.cpp b/Src/DasherCore/DasherViewSquare.cpp index 9ae0fce..966ad52 100644 --- a/Src/DasherCore/DasherViewSquare.cpp +++ b/Src/DasherCore/DasherViewSquare.cpp @@ -1,923 +1,922 @@ // DasherViewSquare.cpp // // Copyright (c) 2008 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" #ifdef _WIN32 #include "..\Win32\Common\WinCommon.h" #endif //#include "DasherGameMode.h" #include "DasherViewSquare.h" #include "DasherModel.h" #include "DasherView.h" #include "DasherTypes.h" #include "Event.h" #include "EventHandler.h" #include <algorithm> #include <iostream> #include <limits> #include <stdlib.h> using namespace Dasher; using namespace Opts; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG_MEMLEAKS #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif // FIXME - quite a lot of the code here probably should be moved to // the parent class (DasherView). I think we really should make the // parent class less general - we're probably not going to implement // anything which uses radically different co-ordinate transforms, and // we can always override if necessary. // FIXME - duplicated 'mode' code throught - needs to be fixed (actually, mode related stuff, Input2Dasher etc should probably be at least partially in some other class) CDasherViewSquare::CDasherViewSquare(CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CDasherScreen *DasherScreen) : CDasherView(pEventHandler, pSettingsStore, DasherScreen), m_Y1(4), m_Y2(0.95 * GetLongParameter(LP_MAX_Y)), m_Y3(0.05 * GetLongParameter((LP_MAX_Y))) { // TODO - AutoOffset should be part of the eyetracker input filter // Make sure that the auto calibration is set to zero berfore we start // m_yAutoOffset = 0; ChangeScreen(DasherScreen); //Note, nonlinearity parameters set in SetScaleFactor m_bVisibleRegionValid = false; } CDasherViewSquare::~CDasherViewSquare() {} void CDasherViewSquare::HandleEvent(Dasher::CEvent *pEvent) { // Let the parent class do its stuff CDasherView::HandleEvent(pEvent); // And then interpret events for ourself if(pEvent->m_iEventType == 1) { Dasher::CParameterNotificationEvent * pEvt(static_cast < Dasher::CParameterNotificationEvent * >(pEvent)); switch (pEvt->m_iParameter) { case LP_REAL_ORIENTATION: case LP_MARGIN_WIDTH: case BP_NONLINEAR_Y: case LP_NONLINEAR_X: m_bVisibleRegionValid = false; SetScaleFactor(); break; default: break; } } } /// Draw text specified in Dasher co-ordinates. The position is /// specified as two co-ordinates, intended to the be the corners of /// the leading edge of the containing box. void CDasherViewSquare::DasherDrawText(myint iAnchorX1, myint iAnchorY1, myint iAnchorX2, myint iAnchorY2, const std::string &sDisplayText, int &mostleft, bool bShove) { // Don't draw text which will overlap with text in an ancestor. if(iAnchorX1 > mostleft) iAnchorX1 = mostleft; if(iAnchorX2 > mostleft) iAnchorX2 = mostleft; myint iDasherMinX; myint iDasherMinY; myint iDasherMaxX; myint iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); iAnchorY1 = std::min( iDasherMaxY, std::max( iDasherMinY, iAnchorY1 ) ); iAnchorY2 = std::min( iDasherMaxY, std::max( iDasherMinY, iAnchorY2 ) ); screenint iScreenAnchorX1; screenint iScreenAnchorY1; screenint iScreenAnchorX2; screenint iScreenAnchorY2; // FIXME - Truncate here before converting - otherwise we risk integer overflow in screen coordinates Dasher2Screen(iAnchorX1, iAnchorY1, iScreenAnchorX1, iScreenAnchorY1); Dasher2Screen(iAnchorX2, iAnchorY2, iScreenAnchorX2, iScreenAnchorY2); // Truncate the ends of the anchor line to be on the screen - this // prevents us from loosing characters off the top and bottom of the // screen // TruncateToScreen(iScreenAnchorX1, iScreenAnchorY1); // TruncateToScreen(iScreenAnchorX2, iScreenAnchorY2); // Actual anchor point is the midpoint of the anchor line screenint iScreenAnchorX((iScreenAnchorX1 + iScreenAnchorX2) / 2); screenint iScreenAnchorY((iScreenAnchorY1 + iScreenAnchorY2) / 2); // Compute font size based on position int Size = GetLongParameter( LP_DASHER_FONTSIZE ); // FIXME - this could be much more elegant, and probably needs a // rethink anyway - behvaiour here is too dependent on screen size screenint iLeftTimesFontSize = ((myint)GetLongParameter(LP_MAX_Y) - (iAnchorX1 + iAnchorX2)/ 2 )*Size; if(iLeftTimesFontSize < (myint)GetLongParameter(LP_MAX_Y) * 19/ 20) Size *= 20; else if(iLeftTimesFontSize < (myint)GetLongParameter(LP_MAX_Y) * 159 / 160) Size *= 14; else Size *= 11; screenint TextWidth, TextHeight; Screen()->TextSize(sDisplayText, &TextWidth, &TextHeight, Size); // Poistion of text box relative to anchor depends on orientation screenint newleft2 = 0; screenint newtop2 = 0; screenint newright2 = 0; screenint newbottom2 = 0; switch (Dasher::Opts::ScreenOrientations(GetLongParameter(LP_REAL_ORIENTATION))) { case (Dasher::Opts::LeftToRight): newleft2 = iScreenAnchorX; newtop2 = iScreenAnchorY - TextHeight / 2; newright2 = iScreenAnchorX + TextWidth; newbottom2 = iScreenAnchorY + TextHeight / 2; break; case (Dasher::Opts::RightToLeft): newleft2 = iScreenAnchorX - TextWidth; newtop2 = iScreenAnchorY - TextHeight / 2; newright2 = iScreenAnchorX; newbottom2 = iScreenAnchorY + TextHeight / 2; break; case (Dasher::Opts::TopToBottom): newleft2 = iScreenAnchorX - TextWidth / 2; newtop2 = iScreenAnchorY; newright2 = iScreenAnchorX + TextWidth / 2; newbottom2 = iScreenAnchorY + TextHeight; break; case (Dasher::Opts::BottomToTop): newleft2 = iScreenAnchorX - TextWidth / 2; newtop2 = iScreenAnchorY - TextHeight; newright2 = iScreenAnchorX + TextWidth / 2; newbottom2 = iScreenAnchorY; break; default: break; } // Update the value of mostleft to take into account the new text if(bShove) { myint iDasherNewLeft; myint iDasherNewTop; myint iDasherNewRight; myint iDasherNewBottom; Screen2Dasher(newleft2, newtop2, iDasherNewLeft, iDasherNewTop); Screen2Dasher(newright2, newbottom2, iDasherNewRight, iDasherNewBottom); mostleft = std::min(iDasherNewRight, iDasherNewLeft); } // Actually draw the text. We use DelayDrawText as the text should // be overlayed once all of the boxes have been drawn. m_DelayDraw.DelayDrawText(sDisplayText, newleft2, newtop2, Size); } void CDasherViewSquare::RenderNodes(CDasherNode *pRoot, myint iRootMin, myint iRootMax, CExpansionPolicy &policy) { DASHER_ASSERT(pRoot != 0); myint iDasherMinX; myint iDasherMinY; myint iDasherMaxX; myint iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); // screenint iScreenLeft; screenint iScreenTop; screenint iScreenRight; screenint iScreenBottom; Dasher2Screen(iRootMax-iRootMin, iRootMin, iScreenLeft, iScreenTop); Dasher2Screen(0, iRootMax, iScreenRight, iScreenBottom); //ifiScreenTop < 0) // iScreenTop = 0; //if(iScreenLeft < 0) // iScreenLeft=0; //// TODO: Should these be right on the boundary? //if(iScreenBottom > Screen()->GetHeight()) // iScreenBottom=Screen()->GetHeight(); //if(iScreenRight > Screen()->GetWidth()) // iScreenRight=Screen()->GetWidth(); // Blank the region around the root node: if(iRootMin > iDasherMinY) DasherDrawRectangle(iDasherMaxX, iDasherMinY, iDasherMinX, iRootMin, 0, -1, Nodes1, 0); //if(iScreenTop > 0) // Screen()->DrawRectangle(0, 0, Screen()->GetWidth(), iScreenTop, 0, -1, Nodes1, false, true, 1); if(iRootMax < iDasherMaxY) DasherDrawRectangle(iDasherMaxX, iRootMax, iDasherMinX, iDasherMaxY, 0, -1, Nodes1, 0); //if(iScreenBottom <= Screen()->GetHeight()) // Screen()->DrawRectangle(0, iScreenBottom, Screen()->GetWidth(), Screen()->GetHeight(), 0, -1, Nodes1, false, true, 1); DasherDrawRectangle(0, iDasherMinY, iDasherMinX, iDasherMaxY, 0, -1, Nodes1, 0); // Screen()->DrawRectangle(iScreenRight, std::max(0, (int)iScreenTop), // Screen()->GetWidth(), std::min(Screen()->GetHeight(), (int)iScreenBottom), // 0, -1, Nodes1, false, true, 1); // Render the root node (and children) RecursiveRender(pRoot, iRootMin, iRootMax, iDasherMaxX, policy, std::numeric_limits<double>::infinity(), iDasherMaxX,0,0); // Labels are drawn in a second parse to get the overlapping right m_DelayDraw.Draw(Screen()); // Finally decorate the view Crosshair((myint)GetLongParameter(LP_OX)); } //min size in *Dasher co-ordinates* to consider rendering a node #define QUICK_REJECT 50 //min size in *screen* (pixel) co-ordinates to render a node #define MIN_SIZE 2 bool CDasherViewSquare::CheckRender(CDasherNode *pRender, myint y1, myint y2, int mostleft, CExpansionPolicy &policy, double dMaxCost, myint parent_width, int parent_color, int iDepth) { if (y2-y1 >= QUICK_REJECT) { myint iDasherMinX; myint iDasherMinY; myint iDasherMaxX; myint iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); if (y1 <= iDasherMaxY && y2 >= iDasherMinY) { screenint iScreenX1; screenint iScreenY1; screenint iScreenX2; screenint iScreenY2; Dasher2Screen(0, std::max(y1, iDasherMinY), iScreenX1, iScreenY1); Dasher2Screen(0, std::min(y2, iDasherMaxY), iScreenX2, iScreenY2); Cint32 iHeight = std::max(myint(iScreenY2 - iScreenY1),myint( 0)); if (iHeight >= MIN_SIZE) { //node should be rendered! RecursiveRender(pRender, y1, y2, mostleft, policy, dMaxCost, parent_width, parent_color, iDepth); return true; } } } // We get here if the node is too small to render or is off-screen. // So, collapse it immediately. // // In game mode, we get here if the child is too small to draw, but we need the // coordinates - if this is the case then we shouldn't delete any children. // // TODO: Should probably render the parent segment here anyway (or // in the above) if(!pRender->GetFlag(NF_GAME)) pRender->Delete_children(); return false; } void CDasherViewSquare::RecursiveRender(CDasherNode *pRender, myint y1, myint y2, int mostleft, CExpansionPolicy &policy, double dMaxCost, myint parent_width,int parent_color, int iDepth) { DASHER_ASSERT_VALIDPTR_RW(pRender); // if(iDepth == 2) // std::cout << pRender->GetDisplayInfo()->strDisplayText << std::endl; // TODO: We need an overhall of the node creation/deletion logic - // make sure that we only maintain the minimum number of nodes which // are actually needed. This is especially true at the moment in // Game mode, which feels very sluggish. Node creation also feels // slower in Windows than Linux, especially if many nodes are // created at once (eg untrained Hiragana) ++m_iRenderCount; // myint trange = y2 - y1; // Attempt to draw the region to the left of this node inside its parent. // if(iDepth == 2) { // std::cout << "y1: " << y1 << " y2: " << y2 << std::endl; // Set the NF_SUPER flag if this node entirely frames the visual // area. // TODO: too slow? // TODO: use flags more rather than delete/reparent lists myint iDasherMinX; myint iDasherMinY; myint iDasherMaxX; myint iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); DasherDrawRectangle(std::min(parent_width,iDasherMaxX), std::max(y1,iDasherMinY), std::min(y2-y1,iDasherMaxX), std::min(y2,iDasherMaxY), parent_color, -1, Nodes1, 0); const std::string &sDisplayText(pRender->GetDisplayInfo()->strDisplayText); if( sDisplayText.size() > 0 ) { DasherDrawText(y2-y1, y1, y2-y1, y2, sDisplayText, mostleft, pRender->GetDisplayInfo()->bShove); } - - pRender->SetFlag(NF_SUPER, (y1 < iDasherMinY) && (y2 > iDasherMaxY) && ((y2 - y1) > iDasherMaxX)); + pRender->SetFlag(NF_SUPER, !IsSpaceAroundNode(y1,y2)); // If there are no children then we still need to render the parent if(pRender->ChildCount() == 0) { DasherDrawRectangle(std::min(y2-y1,iDasherMaxX), std::min(y2,iDasherMaxY),0, std::max(y1,iDasherMinY), pRender->GetDisplayInfo()->iColour, -1, Nodes1, 0); //also allow it to be expanded, it's big enough. policy.pushNode(pRender, y1, y2, true, dMaxCost); return; } //Node has children. It can therefore be collapsed...however, // we don't allow a node covering the crosshair to be collapsed // (at best this'll mean there's nowhere useful to go forwards; // at worst, all kinds of crashes trying to do text output!) if (!pRender->GetFlag(NF_GAME) && !pRender->GetFlag(NF_SEEN)) dMaxCost = policy.pushNode(pRender, y1, y2, false, dMaxCost); // Render children int norm = (myint)GetLongParameter(LP_NORMALIZATION); myint lasty=y1; int id=-1; // int lower=-1,upper=-1; myint temp_parentwidth=y2-y1; int temp_parentcolor = pRender->GetDisplayInfo()->iColour; const myint Range(y2 - y1); if (CDasherNode *pChild = pRender->onlyChildRendered) { //if child still covers screen, render _just_ it and return myint newy1 = y1 + (Range * (myint)pChild->Lbnd()) / (myint)norm; myint newy2 = y1 + (Range * (myint)pChild->Hbnd()) / (myint)norm; if (newy1 < iDasherMinY && newy2 > iDasherMaxY) { //still covers entire screen. Parent should too... DASHER_ASSERT(dMaxCost == std::numeric_limits<double>::infinity()); //don't inc iDepth, meaningless when covers the screen RecursiveRender(pChild, newy1, newy2, mostleft, policy, dMaxCost, temp_parentwidth, temp_parentcolor, iDepth); //leave pRender->onlyChildRendered set, so remaining children are skipped } else pRender->onlyChildRendered = NULL; } if (!pRender->onlyChildRendered) { //render all children... for(CDasherNode::ChildMap::const_iterator i = pRender->GetChildren().begin(); i != pRender->GetChildren().end(); i++) { id++; CDasherNode *pChild = *i; myint newy1 = y1 + (Range * (myint)pChild->Lbnd()) / (myint)norm;/// norm and lbnd are simple ints myint newy2 = y1 + (Range * (myint)pChild->Hbnd()) / (myint)norm; if (newy1 < iDasherMinY && newy2 > iDasherMaxY) { DASHER_ASSERT(dMaxCost == std::numeric_limits<double>::infinity()); pRender->onlyChildRendered = pChild; RecursiveRender(pChild, newy1, newy2, mostleft, policy, dMaxCost, temp_parentwidth, temp_parentcolor, iDepth); //ensure we don't blank over this child in "finishing off" the parent (!) lasty=newy2; break; //no need to render any more children! } if (CheckRender(pChild, newy1, newy2, mostleft, policy, dMaxCost, temp_parentwidth, temp_parentcolor, iDepth+1)) { if (lasty<newy1) { //if child has been drawn then the interval between him and the //last drawn child should be drawn too. //std::cout << "Fill in: " << lasty << " " << newy1 << std::endl; RenderNodePartFast(temp_parentcolor, lasty, newy1, mostleft, pRender->GetDisplayInfo()->strDisplayText, pRender->GetDisplayInfo()->bShove, temp_parentwidth); } lasty = newy2; } } // Finish off the drawing process // if(iDepth == 1) { // Theres a chance that we haven't yet filled the entire parent, so finish things off if necessary. if(lasty<y2) { RenderNodePartFast(temp_parentcolor, lasty, y2, mostleft, pRender->GetDisplayInfo()->strDisplayText, pRender->GetDisplayInfo()->bShove, temp_parentwidth); } } // Draw the outline if(pRender->GetDisplayInfo()->bVisible) { RenderNodeOutlineFast(pRender->GetDisplayInfo()->iColour, y1, y2, mostleft, pRender->GetDisplayInfo()->strDisplayText, pRender->GetDisplayInfo()->bShove); } // } } -bool CDasherViewSquare::IsNodeVisible(myint y1, myint y2) { +bool CDasherViewSquare::IsSpaceAroundNode(myint y1, myint y2) { myint iDasherMinX; myint iDasherMinY; myint iDasherMaxX; myint iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); - return ((y2 - y1) < iDasherMaxX) || ((y1 > iDasherMinY) && (y2 < iDasherMaxY)); + return ((y2 - y1) < iDasherMaxX) || (y1 > iDasherMinY) || (y2 < iDasherMaxY); } // Draw the outline of a node int CDasherViewSquare::RenderNodeOutlineFast(const int Color, myint y1, myint y2, int &mostleft, const std::string &sDisplayText, bool bShove) { // Commenting because click mode occasionally fails this assert. // I don't know why. -- cjb. if (!(y2 >= y1)) { return 1; } // TODO - Get sensible limits here (to allow for non-linearities) myint iDasherMinX; myint iDasherMinY; myint iDasherMaxX; myint iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); screenint iScreenX1; screenint iScreenY1; screenint iScreenX2; screenint iScreenY2; Dasher2Screen(0, std::max(y1, iDasherMinY), iScreenX1, iScreenY1); Dasher2Screen(0, std::min(y2, iDasherMaxY), iScreenX2, iScreenY2); Cint32 iHeight = std::max(myint(iScreenY2 - iScreenY1),myint( 0)); Cint32 iWidth = std::max(myint(iScreenX2 - iScreenX1),myint( 0)); if((iHeight <= 1) && (iWidth <= 1)) return 0; // We're too small to render if((y1 > iDasherMaxY) || (y2 < iDasherMinY)){ return 0; // We're entirely off screen, so don't render. } // TODO: This should be earlier? if(!GetBoolParameter(BP_OUTLINE_MODE)) return 1; myint iDasherSize(y2 - y1); // std::cout << std::min(iDasherSize,iDasherMaxX) << " " << std::min(y2,iDasherMaxY) << " 0 " << std::max(y1,iDasherMinY) << std::endl; DasherDrawRectangle(0, std::min(y1,iDasherMaxY),std::min(iDasherSize,iDasherMaxX), std::max(y2,iDasherMinY), -1, Color, Nodes1, 1); // // FIXME - get rid of pointless assignment below // int iTruncation(GetLongParameter(LP_TRUNCATION)); // Trucation farction times 100; // if(iTruncation == 0) { // Regular squares // } // else { // // TODO: Put something back here? // } return 1; } // Draw a filled block of a node right down to the baseline (intended // for the case when you have no visible child) int CDasherViewSquare::RenderNodePartFast(const int Color, myint y1, myint y2, int &mostleft, const std::string &sDisplayText, bool bShove,myint iParentWidth ) { // Commenting because click mode occasionally fails this assert. // I don't know why. -- cjb. if (!(y2 >= y1)) { return 1; } // TODO - Get sensible limits here (to allow for non-linearities) myint iDasherMinX; myint iDasherMinY; myint iDasherMaxX; myint iDasherMaxY; VisibleRegion(iDasherMinX, iDasherMinY, iDasherMaxX, iDasherMaxY); screenint iScreenX1; screenint iScreenY1; screenint iScreenX2; screenint iScreenY2; Dasher2Screen(0, std::max(y1, iDasherMinY), iScreenX1, iScreenY1); Dasher2Screen(0, std::min(y2, iDasherMaxY), iScreenX2, iScreenY2); // std::cout << "Fill in components: " << iScreenY1 << " " << iScreenY2 << std::endl; Cint32 iHeight = std::max(myint(iScreenY2 - iScreenY1),myint( 0)); Cint32 iWidth = std::max(myint(iScreenX2 - iScreenX1),myint( 0)); if((iHeight < 1) && (iWidth < 1)) { // std::cout << "b" << std::endl; return 0; // We're too small to render } if((y1 > iDasherMaxY) || (y2 < iDasherMinY)){ //std::cout << "a" << std::endl; return 0; // We're entirely off screen, so don't render. } DasherDrawRectangle(std::min(iParentWidth,iDasherMaxX), std::min(y2,iDasherMaxY),0, std::max(y1,iDasherMinY), Color, -1, Nodes1, 0); return 1; } /// Convert screen co-ordinates to dasher co-ordinates. This doesn't /// include the nonlinear mapping for eyetracking mode etc - it is /// just the inverse of the mapping used to calculate the screen /// positions of boxes etc. void CDasherViewSquare::Screen2Dasher(screenint iInputX, screenint iInputY, myint &iDasherX, myint &iDasherY) { // Things we're likely to need: //myint iDasherWidth = (myint)GetLongParameter(LP_MAX_Y); myint iDasherHeight = (myint)GetLongParameter(LP_MAX_Y); screenint iScreenWidth = Screen()->GetWidth(); screenint iScreenHeight = Screen()->GetHeight(); int eOrientation(GetLongParameter(LP_REAL_ORIENTATION)); switch(eOrientation) { case Dasher::Opts::LeftToRight: iDasherX = iCenterX - ( iInputX - iScreenWidth / 2 ) * m_iScalingFactor / iScaleFactorX; iDasherY = iDasherHeight / 2 + ( iInputY - iScreenHeight / 2 ) * m_iScalingFactor / iScaleFactorY; break; case Dasher::Opts::RightToLeft: iDasherX = myint(iCenterX + ( iInputX - iScreenWidth / 2 ) * m_iScalingFactor/ iScaleFactorX); iDasherY = myint(iDasherHeight / 2 + ( iInputY - iScreenHeight / 2 ) * m_iScalingFactor/ iScaleFactorY); break; case Dasher::Opts::TopToBottom: iDasherX = myint(iCenterX - ( iInputY - iScreenHeight / 2 ) * m_iScalingFactor/ iScaleFactorY); iDasherY = myint(iDasherHeight / 2 + ( iInputX - iScreenWidth / 2 ) * m_iScalingFactor/ iScaleFactorX); break; case Dasher::Opts::BottomToTop: iDasherX = myint(iCenterX + ( iInputY - iScreenHeight / 2 ) * m_iScalingFactor/ iScaleFactorY); iDasherY = myint(iDasherHeight / 2 + ( iInputX - iScreenWidth / 2 ) * m_iScalingFactor/ iScaleFactorX); break; } iDasherX = ixmap(iDasherX); iDasherY = iymap(iDasherY); } void CDasherViewSquare::SetScaleFactor( void ) { //Parameters for X non-linearity. // Set some defaults here, in case we change(d) them later... m_dXmpb = 0.5; //threshold: DasherX's less than (m_dXmpb * MAX_Y) are linear... m_dXmpc = 0.9; //...but multiplied by m_dXmpc; DasherX's above that, are logarithmic... //set log scaling coefficient (unused if LP_NONLINEAR_X==0) // note previous value of m_dXmpa = 0.2, i.e. a value of LP_NONLINEAR_X =~= 4.8 m_dXmpa = exp(GetLongParameter(LP_NONLINEAR_X)/-3.0); myint iDasherWidth = (myint)GetLongParameter(LP_MAX_Y); myint iDasherHeight = iDasherWidth; screenint iScreenWidth = Screen()->GetWidth(); screenint iScreenHeight = Screen()->GetHeight(); // Try doing this a different way: myint iDasherMargin( GetLongParameter(LP_MARGIN_WIDTH) ); // Make this a parameter myint iMinX( 0-iDasherMargin ); myint iMaxX( iDasherWidth ); iCenterX = (iMinX + iMaxX)/2; myint iMinY( 0 ); myint iMaxY( iDasherHeight ); Dasher::Opts::ScreenOrientations eOrientation(Dasher::Opts::ScreenOrientations(GetLongParameter(LP_REAL_ORIENTATION))); double dScaleFactorX, dScaleFactorY; if (eOrientation == Dasher::Opts::LeftToRight || eOrientation == Dasher::Opts::RightToLeft) { dScaleFactorX = iScreenWidth / static_cast<double>( iMaxX - iMinX ); dScaleFactorY = iScreenHeight / static_cast<double>( iMaxY - iMinY ); } else { dScaleFactorX = iScreenHeight / static_cast<double>( iMaxX - iMinX ); dScaleFactorY = iScreenWidth / static_cast<double>( iMaxY - iMinY ); } if (dScaleFactorX < dScaleFactorY) { //fewer (pixels per dasher coord) in X direction - i.e., X is more compressed. //So, use X scale for Y too...except first, we'll _try_ to reduce the difference // by changing the relative scaling of X and Y (by at most 20%): double dMul = max(0.8, dScaleFactorX / dScaleFactorY); m_dXmpc *= dMul; dScaleFactorX /= dMul; iScaleFactorX = myint(dScaleFactorX * m_iScalingFactor); iScaleFactorY = myint(std::max(dScaleFactorX, dScaleFactorY / 4.0) * m_iScalingFactor); } else { //X has more room; use Y scale for both -> will get lots history iScaleFactorX = myint(std::max(dScaleFactorY, dScaleFactorX / 4.0) * m_iScalingFactor); iScaleFactorY = myint(dScaleFactorY * m_iScalingFactor); // however, "compensate" by relaxing the default "relative scaling" of X // (normally only 90% of Y) towards 1... m_dXmpc = std::min(1.0,0.9 * dScaleFactorX / dScaleFactorY); } iCenterX *= m_dXmpc; } inline myint CDasherViewSquare::CustomIDiv(myint iNumerator, myint iDenominator) { // Integer division rounding away from zero long long int num, denom, quot, rem; myint res; num = iNumerator; denom = iDenominator; DASHER_ASSERT(denom != 0); #ifdef HAVE_LLDIV lldiv_t ans = ::lldiv(num, denom); quot = ans.quot; rem = ans.rem; #else quot = num / denom; rem = num % denom; #endif if (rem < 0) res = quot - 1; else if (rem > 0) res = quot + 1; else res = quot; return res; // return (iNumerator + iDenominator - 1) / iDenominator; } void CDasherViewSquare::Dasher2Screen(myint iDasherX, myint iDasherY, screenint &iScreenX, screenint &iScreenY) { // Apply the nonlinearities iDasherX = xmap(iDasherX); iDasherY = ymap(iDasherY); // Things we're likely to need: //myint iDasherWidth = (myint)GetLongParameter(LP_MAX_Y); myint iDasherHeight = (myint)GetLongParameter(LP_MAX_Y); screenint iScreenWidth = Screen()->GetWidth(); screenint iScreenHeight = Screen()->GetHeight(); int eOrientation( GetLongParameter(LP_REAL_ORIENTATION) ); // Note that integer division is rounded *away* from zero here to // ensure that this really is the inverse of the map the other way // around. switch( eOrientation ) { case Dasher::Opts::LeftToRight: iScreenX = screenint(iScreenWidth / 2 - CustomIDiv((( iDasherX - iCenterX ) * iScaleFactorX), m_iScalingFactor)); iScreenY = screenint(iScreenHeight / 2 + CustomIDiv(( iDasherY - iDasherHeight / 2 ) * iScaleFactorY, m_iScalingFactor)); break; case Dasher::Opts::RightToLeft: iScreenX = screenint(iScreenWidth / 2 + CustomIDiv(( iDasherX - iCenterX ) * iScaleFactorX, m_iScalingFactor)); iScreenY = screenint(iScreenHeight / 2 + CustomIDiv(( iDasherY - iDasherHeight / 2 ) * iScaleFactorY, m_iScalingFactor)); break; case Dasher::Opts::TopToBottom: iScreenX = screenint(iScreenWidth / 2 + CustomIDiv(( iDasherY - iDasherHeight / 2 ) * iScaleFactorX, m_iScalingFactor)); iScreenY = screenint(iScreenHeight / 2 - CustomIDiv(( iDasherX - iCenterX ) * iScaleFactorY, m_iScalingFactor)); break; case Dasher::Opts::BottomToTop: iScreenX = screenint(iScreenWidth / 2 + CustomIDiv(( iDasherY - iDasherHeight / 2 ) * iScaleFactorX, m_iScalingFactor)); iScreenY = screenint(iScreenHeight / 2 + CustomIDiv(( iDasherX - iCenterX ) * iScaleFactorY, m_iScalingFactor)); break; } } void CDasherViewSquare::Dasher2Polar(myint iDasherX, myint iDasherY, double &r, double &theta) { iDasherX = xmap(iDasherX); iDasherY = ymap(iDasherY); myint iDasherOX = xmap(GetLongParameter(LP_OX)); myint iDasherOY = ymap(GetLongParameter(LP_OY)); double x = -(iDasherX - iDasherOX) / double(iDasherOX); //Use normalised coords so min r works double y = -(iDasherY - iDasherOY) / double(iDasherOY); theta = atan2(y, x); r = sqrt(x * x + y * y); } void CDasherViewSquare::DasherLine2Screen(myint x1, myint y1, myint x2, myint y2, vector<CDasherScreen::point> &vPoints) { if (x1!=x2 && y1!=y2) { //only diagonal lines ever get changed... if (GetBoolParameter(BP_NONLINEAR_Y)) { if ((y1 < m_Y3 && y2 > m_Y3) ||(y2 < m_Y3 && y1 > m_Y3)) { //crosses bottom non-linearity border int x_mid = x1+(x2-x1) * (m_Y3-y1)/(y2-y1); DasherLine2Screen(x1, y1, x_mid, m_Y3, vPoints); x1=x_mid; y1=m_Y3; }//else //no, a single line might cross _both_ borders! if ((y1 > m_Y2 && y2 < m_Y2) || (y2 > m_Y2 && y1 < m_Y2)) { //crosses top non-linearity border int x_mid = x1 + (x2-x1) * (m_Y2-y1)/(y2-y1); DasherLine2Screen(x1, y1, x_mid, m_Y2, vPoints); x1=x_mid; y1=m_Y2; } } double dMax(static_cast<double>(GetLongParameter(LP_MAX_Y))); if (GetLongParameter(LP_NONLINEAR_X) && (x1 / dMax > m_dXmpb || x2 / dMax > m_dXmpb)) { //into logarithmic section CDasherScreen::point pStart, pScreenMid, pEnd; Dasher2Screen(x2, y2, pEnd.x, pEnd.y); for(;;) { Dasher2Screen(x1, y1, pStart.x, pStart.y); //a straight line on the screen between pStart and pEnd passes through pScreenMid: pScreenMid.x = (pStart.x + pEnd.x)/2; pScreenMid.y = (pStart.y + pEnd.y)/2; //whereas a straight line _in_Dasher_space_ passes through pDasherMid: int xMid=(x1+x2)/2, yMid=(y1+y2)/2; CDasherScreen::point pDasherMid; Dasher2Screen(xMid, yMid, pDasherMid.x, pDasherMid.y); //since we know both endpoints are in the same section of the screen wrt. Y nonlinearity, //the midpoint along the DasherY axis of both lines should be the same. const Dasher::Opts::ScreenOrientations orient(Dasher::Opts::ScreenOrientations(GetLongParameter(LP_REAL_ORIENTATION))); if (orient==Dasher::Opts::LeftToRight || orient==Dasher::Opts::RightToLeft) { DASHER_ASSERT(abs(pDasherMid.y - pScreenMid.y)<=1);//allow for rounding error if (abs(pDasherMid.x - pScreenMid.x)<=1) break; //call a straight line accurate enough } else { DASHER_ASSERT(abs(pDasherMid.x - pScreenMid.x)<=1); if (abs(pDasherMid.y - pScreenMid.y)<=1) break; } //line should appear bent. Subdivide! DasherLine2Screen(x1,y1,xMid,yMid,vPoints); //recurse for first half (to Dasher-space midpoint) x1=xMid; y1=yMid; //& loop round for second half } //broke out of loop. a straight line (x1,y1)-(x2,y2) on the screen is an accurate portrayal of a straight line in Dasher-space. vPoints.push_back(pEnd); return; } //ok, not in x nonlinear section; fall through. } #ifdef DEBUG CDasherScreen::point pTest; Dasher2Screen(x1, y1, pTest.x, pTest.y); DASHER_ASSERT(vPoints.back().x == pTest.x && vPoints.back().y == pTest.y); #endif CDasherScreen::point p; Dasher2Screen(x2, y2, p.x, p.y); vPoints.push_back(p); } void CDasherViewSquare::VisibleRegion( myint &iDasherMinX, myint &iDasherMinY, myint &iDasherMaxX, myint &iDasherMaxY ) { // TODO: Change output parameters to pointers and allow NULL to mean // 'I don't care'. Need to be slightly careful about this as it will // require a slightly more sophisticated caching mechanism if(!m_bVisibleRegionValid) { int eOrientation( GetLongParameter(LP_REAL_ORIENTATION) ); switch( eOrientation ) { case Dasher::Opts::LeftToRight: Screen2Dasher(Screen()->GetWidth(),0,m_iDasherMinX,m_iDasherMinY); Screen2Dasher(0,Screen()->GetHeight(),m_iDasherMaxX,m_iDasherMaxY); break; case Dasher::Opts::RightToLeft: Screen2Dasher(0,0,m_iDasherMinX,m_iDasherMinY); Screen2Dasher(Screen()->GetWidth(),Screen()->GetHeight(),m_iDasherMaxX,m_iDasherMaxY); break; case Dasher::Opts::TopToBottom: Screen2Dasher(0,Screen()->GetHeight(),m_iDasherMinX,m_iDasherMinY); Screen2Dasher(Screen()->GetWidth(),0,m_iDasherMaxX,m_iDasherMaxY); break; case Dasher::Opts::BottomToTop: Screen2Dasher(0,0,m_iDasherMinX,m_iDasherMinY); Screen2Dasher(Screen()->GetWidth(),Screen()->GetHeight(),m_iDasherMaxX,m_iDasherMaxY); break; } m_bVisibleRegionValid = true; } iDasherMinX = m_iDasherMinX; iDasherMaxX = m_iDasherMaxX; iDasherMinY = m_iDasherMinY; iDasherMaxY = m_iDasherMaxY; } // void CDasherViewSquare::NewDrawGoTo(myint iDasherMin, myint iDasherMax, bool bActive) { // myint iHeight(iDasherMax - iDasherMin); // int iColour; // int iWidth; // if(bActive) { // iColour = 1; // iWidth = 3; // } // else { // iColour = 2; // iWidth = 1; // } // CDasherScreen::point p[4]; // Dasher2Screen( 0, iDasherMin, p[0].x, p[0].y); // Dasher2Screen( iHeight, iDasherMin, p[1].x, p[1].y); // Dasher2Screen( iHeight, iDasherMax, p[2].x, p[2].y); // Dasher2Screen( 0, iDasherMax, p[3].x, p[3].y); // Screen()->Polyline(p, 4, iWidth, iColour); // } void CDasherViewSquare::ChangeScreen(CDasherScreen *NewScreen) { CDasherView::ChangeScreen(NewScreen); m_bVisibleRegionValid = false; m_iScalingFactor = 100000000; SetScaleFactor(); } diff --git a/Src/DasherCore/DasherViewSquare.h b/Src/DasherCore/DasherViewSquare.h index 79140ad..433c477 100644 --- a/Src/DasherCore/DasherViewSquare.h +++ b/Src/DasherCore/DasherViewSquare.h @@ -1,201 +1,202 @@ // DasherViewSquare.h // // Copyright (c) 2001-2004 David Ward #ifndef __DasherViewSquare_h__ #define __DasherViewSquare_h__ #include "DasherView.h" #include "DelayedDraw.h" #include "DasherScreen.h" #include <deque> #include "Alphabet/GroupInfo.h" using namespace std; namespace Dasher { class CDasherViewSquare; class CDasherView; class CDasherModel; class CDelayedDraw; class CDasherNode; } class Dasher::CDasherViewSquare; class Dasher::CDasherModel; class Dasher::CDelayedDraw; class Dasher::CDasherNode; /// \ingroup View /// @{ /// An implementation of the DasherView class /// /// This class renders Dasher in the vanilla style, /// but with horizontal and vertical mappings /// /// Horizontal mapping - linear and log /// Vertical mapping - linear with different gradient class Dasher::CDasherViewSquare:public Dasher::CDasherView { public: /// Constructor /// /// \param pEventHandler Event handler. /// \param pSettingsStore Settings store. /// \param DasherScreen Pointer to creen to which the view will render. /// \todo Don't cache screen and model locally - screen can be /// passed as parameter to the drawing functions, and data structure /// can be extracted from the model and passed too. CDasherViewSquare(CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CDasherScreen *DasherScreen); ~CDasherViewSquare(); /// /// Event handler /// virtual void HandleEvent(Dasher::CEvent * pEvent); /// /// Supply a new screen to draw to /// void ChangeScreen(CDasherScreen * NewScreen); /// /// @name Coordinate system conversion /// Convert between screen and Dasher coordinates /// @{ /// /// Convert a screen co-ordinate to Dasher co-ordinates /// void Screen2Dasher(screenint iInputX, screenint iInputY, myint & iDasherX, myint & iDasherY); /// /// Convert Dasher co-ordinates to screen co-ordinates /// void Dasher2Screen(myint iDasherX, myint iDasherY, screenint & iScreenX, screenint & iScreenY); /// /// Convert Dasher co-ordinates to polar co-ordinates (r,theta), with 0<r<1, 0<theta<2*pi /// virtual void Dasher2Polar(myint iDasherX, myint iDasherY, double &r, double &theta); /// - /// Return true if a node spanning y1 to y2 is entirely enclosed by + /// Return true if there is any space around a node spanning y1 to y2 + /// and the screen boundary; return false if such a node entirely encloses /// the screen boundary /// - bool IsNodeVisible(myint y1, myint y2); + bool IsSpaceAroundNode(myint y1, myint y2); /// /// Get the bounding box of the visible region. /// void VisibleRegion( myint &iDasherMinX, myint &iDasherMinY, myint &iDasherMaxX, myint &iDasherMaxY ); /// @} void DasherSpaceLine(myint x1, myint x2, myint y1, myint y2, int iColor, int iWidth); private: /// /// Draw text specified in Dasher co-ordinates /// void DasherDrawText(myint iAnchorX1, myint iAnchorY1, myint iAnchorX2, myint iAnchorY2, const std::string & sDisplayText, int &mostleft, bool bShove); CDelayedDraw m_DelayDraw; /// /// Render the current state of the model. /// virtual void RenderNodes(CDasherNode *pRoot, myint iRootMin, myint iRootMax, CExpansionPolicy &policy); /// /// Recursively render all nodes in a tree. Responsible for all the Render_node calls /// void RecursiveRender(CDasherNode * Render, myint y1, myint y2, int mostleft, CExpansionPolicy &policy, double dMaxCost, myint parent_width,int parent_color, int iDepth); ///Check that a node is large enough, and onscreen, to render; ///calls RecursiveRender if so, or collapses the node immediately if not bool CheckRender(CDasherNode * Render, myint y1, myint y2, int mostleft, CExpansionPolicy &policy, double dMaxCost, myint parent_width,int parent_color, int iDepth); /// Render a single node /// \param Color The colour to draw it /// \param y1 Upper extent. /// \param y2 Lower extent /// \param mostleft The left most position in which the text (l->r) /// can be displayed in order to avoid overlap. This is updated by /// the function to allow for the new text /// \param sDisplayText Text to display. /// \param bShove Whether the node shoves /// \todo Character and displaytext are redundant. We shouldn't need /// to know about alphabets here, so only use the latterr // int RenderNode(const int Color, myint y1, myint y2, int &mostleft, const std::string &sDisplayText, bool bShove); int RenderNodeOutlineFast(const int Color, myint y1, myint y2, int &mostleft, const std::string &sDisplayText, bool bShove); int RenderNodePartFast(const int Color, myint y1, myint y2, int &mostleft, const std::string &sDisplayText, bool bShove, myint iParentWidth); #ifdef _WIN32 /// /// FIXME - couldn't find windows version of round(double) so here's one! /// \param number to be rounded /// double round(double d) { if(d - floor(d) < 0.5) return floor(d); else return ceil(d); }; #endif /// @name Nonlinearity /// Implements the non-linear part of the coordinate space mapping /// Maps a dasher Y coordinate to the Y value in a linear version of Dasher space (i.e. still not screen pixels) /// (i.e. screen coordinate = scale(ymap(dasher coord))) inline myint ymap(myint iDasherY) const; /// Inverse of the previous - i.e. dasher coord = iymap(scale(screen coord)) myint iymap(myint y) const; ///parameters used by previous const myint m_Y1, m_Y2, m_Y3; myint xmap(myint x) const; myint ixmap(myint x) const; inline void Crosshair(myint sx); inline myint CustomIDiv(myint iNumerator, myint iDenominator); void DasherLine2Screen(myint x1, myint y1, myint x2, myint y2, vector<CDasherScreen::point> &vPoints); // Called on screen size or orientation changes void SetScaleFactor(); // Data double m_dXmpa, m_dXmpb, m_dXmpc; screenint iCenterX; // Cached values for scaling myint iScaleFactorX; myint iScaleFactorY; // The factor that scale factors are multipled by myint m_iScalingFactor; // Cached extents of visible region myint m_iDasherMinX; myint m_iDasherMaxX; myint m_iDasherMinY; myint m_iDasherMaxY; }; /// @} #include "DasherViewSquare.inl" #endif /* #ifndef __DasherViewSquare_h__ */
rgee/HFOSS-Dasher
6a92981fde4b8b1746e8d3a4dcd0e7ad57edc55e
Remove CDasherNode::m_iNumSymbols
diff --git a/Src/DasherCore/AlphabetManager.cpp b/Src/DasherCore/AlphabetManager.cpp index f7b1132..d8b5aed 100644 --- a/Src/DasherCore/AlphabetManager.cpp +++ b/Src/DasherCore/AlphabetManager.cpp @@ -1,469 +1,467 @@ // AlphabetManager.cpp // // Copyright (c) 2007 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" #include "AlphabetManager.h" #include "ConversionManager.h" #include "DasherInterfaceBase.h" #include "DasherNode.h" #include "Event.h" #include "EventHandler.h" #include "NodeCreationManager.h" #include <vector> #include <sstream> #include <iostream> using namespace Dasher; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG_MEMLEAKS #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif CAlphabetManager::CAlphabetManager(CDasherInterfaceBase *pInterface, CNodeCreationManager *pNCManager, CLanguageModel *pLanguageModel) : m_pLanguageModel(pLanguageModel), m_pNCManager(pNCManager) { m_pInterface = pInterface; m_iLearnContext = m_pLanguageModel->CreateEmptyContext(); } CAlphabetManager::CAlphNode::CAlphNode(CDasherNode *pParent, unsigned int iLbnd, unsigned int iHbnd, CDasherNode::SDisplayInfo *pDisplayInfo, CAlphabetManager *pMgr) : CDasherNode(pParent, iLbnd, iHbnd, pDisplayInfo), m_pProbInfo(NULL), m_pMgr(pMgr) { }; CAlphabetManager::CSymbolNode::CSymbolNode(CDasherNode *pParent, unsigned int iLbnd, unsigned int iHbnd, CDasherNode::SDisplayInfo *pDisplayInfo, CAlphabetManager *pMgr, symbol _iSymbol) : CAlphNode(pParent, iLbnd, iHbnd, pDisplayInfo, pMgr), iSymbol(_iSymbol) { }; CAlphabetManager::CGroupNode::CGroupNode(CDasherNode *pParent, unsigned int iLbnd, unsigned int iHbnd, CDasherNode::SDisplayInfo *pDisplayInfo, CAlphabetManager *pMgr, SGroupInfo *pGroup) : CAlphNode(pParent, iLbnd, iHbnd, pDisplayInfo, pMgr), m_pGroup(pGroup) { }; CAlphabetManager::CSymbolNode *CAlphabetManager::makeSymbol(CDasherNode *pParent, unsigned int iLbnd, unsigned int iHbnd, CDasherNode::SDisplayInfo *pDisplayInfo, symbol iSymbol) { return new CSymbolNode(pParent, iLbnd, iHbnd, pDisplayInfo, this, iSymbol); } CAlphabetManager::CGroupNode *CAlphabetManager::makeGroup(CDasherNode *pParent, unsigned int iLbnd, unsigned int iHbnd, CDasherNode::SDisplayInfo *pDisplayInfo, SGroupInfo *pGroup) { return new CGroupNode(pParent, iLbnd, iHbnd, pDisplayInfo, this, pGroup); } CAlphabetManager::CAlphNode *CAlphabetManager::GetRoot(CDasherNode *pParent, unsigned int iLower, unsigned int iUpper, bool bEnteredLast, int iOffset) { int iNewOffset(max(-1,iOffset-1)); std::vector<symbol> vContextSymbols; // TODO: make the LM get the context, rather than force it to fix max context length as an int int iStart = max(0, iNewOffset - m_pLanguageModel->GetContextLength()); if(pParent) { pParent->GetContext(m_pInterface, vContextSymbols, iStart, iNewOffset+1 - iStart); } else { std::string strContext = (iNewOffset == -1) ? m_pNCManager->GetAlphabet()->GetDefaultContext() : m_pInterface->GetContext(iStart, iNewOffset+1 - iStart); m_pNCManager->GetAlphabet()->GetSymbols(vContextSymbols, strContext); } CDasherNode::SDisplayInfo *pDisplayInfo = new CDasherNode::SDisplayInfo; pDisplayInfo->bShove = true; pDisplayInfo->bVisible = true; CAlphNode *pNewNode; CLanguageModel::Context iContext = m_pLanguageModel->CreateEmptyContext(); std::vector<symbol>::iterator it = vContextSymbols.end(); while (it!=vContextSymbols.begin()) { if (*(--it) == 0) { //found an impossible symbol! start after it ++it; break; } } if (it == vContextSymbols.end()) { //previous character was not in the alphabet! //can't construct a node "responsible" for entering it bEnteredLast=false; //instead, Create a node as if we were starting a new sentence... vContextSymbols.clear(); m_pNCManager->GetAlphabet()->GetSymbols(vContextSymbols, m_pNCManager->GetAlphabet()->GetDefaultContext()); it = vContextSymbols.begin(); //TODO: What it the default context somehow contains symbols not in the alphabet? } //enter the symbols we could make sense of, into the LM context... while (it != vContextSymbols.end()) { m_pLanguageModel->EnterSymbol(iContext, *(it++)); } if(!bEnteredLast) { pDisplayInfo->strDisplayText = ""; //equivalent to do m_pNCManager->GetAlphabet()->GetDisplayText(0) pDisplayInfo->iColour = m_pNCManager->GetAlphabet()->GetColour(0, iNewOffset%2); pNewNode = makeGroup(pParent, iLower, iUpper, pDisplayInfo, NULL); } else { const symbol iSymbol(vContextSymbols[vContextSymbols.size() - 1]); pDisplayInfo->strDisplayText = m_pNCManager->GetAlphabet()->GetDisplayText(iSymbol); pDisplayInfo->iColour = m_pNCManager->GetAlphabet()->GetColour(iSymbol, iNewOffset%2); pNewNode = makeSymbol(pParent, iLower, iUpper, pDisplayInfo, iSymbol); //if the new node is not child of an existing node, then it // represents a symbol that's already happened - so we're either // going backwards (rebuildParent) or creating a new root after a language change DASHER_ASSERT (!pParent); pNewNode->SetFlag(NF_SEEN, true); } pNewNode->m_iOffset = iNewOffset; pNewNode->iContext = iContext; return pNewNode; } bool CAlphabetManager::CSymbolNode::GameSearchNode(string strTargetUtf8Char) { if (m_pMgr->m_pNCManager->GetAlphabet()->GetText(iSymbol) == strTargetUtf8Char) { SetFlag(NF_GAME, true); return true; } return false; } bool CAlphabetManager::CGroupNode::GameSearchNode(string strTargetUtf8Char) { if (GameSearchChildren(strTargetUtf8Char)) { SetFlag(NF_GAME, true); return true; } return false; } CLanguageModel::Context CAlphabetManager::CAlphNode::CloneAlphContext(CLanguageModel *pLanguageModel) { if (iContext) return pLanguageModel->CloneContext(iContext); return CDasherNode::CloneAlphContext(pLanguageModel); } void CAlphabetManager::CSymbolNode::GetContext(CDasherInterfaceBase *pInterface, vector<symbol> &vContextSymbols, int iOffset, int iLength) { if (!GetFlag(NF_SEEN) && iOffset+iLength-1 == m_iOffset) { if (iLength > 1) Parent()->GetContext(pInterface, vContextSymbols, iOffset, iLength-1); vContextSymbols.push_back(iSymbol); } else { CDasherNode::GetContext(pInterface, vContextSymbols, iOffset, iLength); } } symbol CAlphabetManager::CSymbolNode::GetAlphSymbol() { return iSymbol; } void CAlphabetManager::CSymbolNode::PopulateChildren() { m_pMgr->IterateChildGroups(this, NULL, NULL); } int CAlphabetManager::CAlphNode::ExpectedNumChildren() { return m_pMgr->m_pNCManager->GetAlphabet()->iNumChildNodes; } std::vector<unsigned int> *CAlphabetManager::CAlphNode::GetProbInfo() { if (!m_pProbInfo) { m_pProbInfo = new std::vector<unsigned int>(); m_pMgr->m_pNCManager->GetProbs(iContext, *m_pProbInfo, m_pMgr->m_pNCManager->GetLongParameter(LP_NORMALIZATION)); // work out cumulative probs in place for(unsigned int i = 1; i < m_pProbInfo->size(); i++) { (*m_pProbInfo)[i] += (*m_pProbInfo)[i - 1]; } } return m_pProbInfo; } std::vector<unsigned int> *CAlphabetManager::CGroupNode::GetProbInfo() { if (m_pGroup && Parent() && Parent()->mgr() == mgr()) { DASHER_ASSERT(Parent()->m_iOffset == m_iOffset); return (static_cast<CAlphNode *>(Parent()))->GetProbInfo(); } //nope, no usable parent. compute here... return CAlphNode::GetProbInfo(); } void CAlphabetManager::CGroupNode::PopulateChildren() { m_pMgr->IterateChildGroups(this, m_pGroup, NULL); if (GetChildren().size()==1) { CDasherNode *pChild = GetChildren()[0]; //single child, must therefore completely fill this node... DASHER_ASSERT(pChild->Lbnd()==0 && pChild->Hbnd()==65536); //in earlier versions of Dasher with subnodes, that child would have been created // at the same time as this node, so this node would never be seen/rendered (as the // child would cover it). However, lazily (as we do now) creating the child, will // suddenly obscure this (parent) node, changing it's colour. Hence, avoid this by // making the child look like the parent...(note that changing the parent, before the // child is created, to look like the child will do, would more closely mirror the old // behaviour, but we can't really do that! CDasherNode::SDisplayInfo *pInfo = (CDasherNode::SDisplayInfo *)pChild->GetDisplayInfo(); //ick, note the cast to get rid of 'const'ness. TODO: do something about SDisplayInfo...!! pInfo->bVisible=false; pInfo->iColour = GetDisplayInfo()->iColour; } } int CAlphabetManager::CGroupNode::ExpectedNumChildren() { return (m_pGroup) ? m_pGroup->iNumChildNodes : CAlphNode::ExpectedNumChildren(); } CAlphabetManager::CGroupNode *CAlphabetManager::CreateGroupNode(CAlphNode *pParent, SGroupInfo *pInfo, unsigned int iLbnd, unsigned int iHbnd) { // TODO: More sensible structure in group data to map directly to this CDasherNode::SDisplayInfo *pDisplayInfo = new CDasherNode::SDisplayInfo; pDisplayInfo->iColour = (pInfo->bVisible ? pInfo->iColour : pParent->GetDisplayInfo()->iColour); pDisplayInfo->bShove = true; pDisplayInfo->bVisible = pInfo->bVisible; pDisplayInfo->strDisplayText = pInfo->strLabel; CGroupNode *pNewNode = makeGroup(pParent, iLbnd, iHbnd, pDisplayInfo, pInfo); // When creating a group node... pNewNode->m_iOffset = pParent->m_iOffset; // ...the offset is the same as the parent... pNewNode->iContext = m_pLanguageModel->CloneContext(pParent->iContext); return pNewNode; } CAlphabetManager::CGroupNode *CAlphabetManager::CGroupNode::RebuildGroup(CAlphNode *pParent, SGroupInfo *pInfo, unsigned int iLbnd, unsigned int iHbnd) { if (pInfo == m_pGroup) { SetRange(iLbnd, iHbnd); SetParent(pParent); //offset doesn't increase for groups... DASHER_ASSERT (m_iOffset == pParent->m_iOffset); return this; } CGroupNode *pRet=m_pMgr->CreateGroupNode(pParent, pInfo, iLbnd, iHbnd); if (pInfo->iStart <= m_pGroup->iStart && pInfo->iEnd >= m_pGroup->iEnd) { //created group node should contain this one m_pMgr->IterateChildGroups(pRet,pInfo,this); } return pRet; } CAlphabetManager::CGroupNode *CAlphabetManager::CSymbolNode::RebuildGroup(CAlphNode *pParent, SGroupInfo *pInfo, unsigned int iLbnd, unsigned int iHbnd) { CGroupNode *pRet=m_pMgr->CreateGroupNode(pParent, pInfo, iLbnd, iHbnd); if (pInfo->iStart <= iSymbol && pInfo->iEnd > iSymbol) { m_pMgr->IterateChildGroups(pRet, pInfo, this); } return pRet; } CLanguageModel::Context CAlphabetManager::CreateSymbolContext(CAlphNode *pParent, symbol iSymbol) { CLanguageModel::Context iContext = m_pLanguageModel->CloneContext(pParent->iContext); m_pLanguageModel->EnterSymbol(iContext, iSymbol); // TODO: Don't use symbols? return iContext; } CDasherNode *CAlphabetManager::CreateSymbolNode(CAlphNode *pParent, symbol iSymbol, unsigned int iLbnd, unsigned int iHbnd) { CDasherNode *pNewNode = NULL; //Does not invoke conversion node // TODO: Better way of specifying alternate roots // TODO: Need to fix fact that this is created even when control mode is switched off if(iSymbol == m_pNCManager->GetAlphabet()->GetControlSymbol()) { //ACL setting offset as one more than parent for consistency with "proper" symbol nodes... pNewNode = m_pNCManager->GetCtrlRoot(pParent, iLbnd, iHbnd, pParent->m_iOffset+1); #ifdef _WIN32_WCE //no control manager - but (TODO!) we still try to create (0-size!) control node... DASHER_ASSERT(!pNewNode); // For now, just hack it so we get a normal root node here pNewNode = m_pNCManager->GetAlphRoot(pParent, iLbnd, iHbnd, false, pParent->m_iOffset+1); #else DASHER_ASSERT(pNewNode); #endif } else if(iSymbol == m_pNCManager->GetAlphabet()->GetStartConversionSymbol()) { // else if(iSymbol == m_pNCManager->GetSpaceSymbol()) { //ACL setting m_iOffset+1 for consistency with "proper" symbol nodes... pNewNode = m_pNCManager->GetConvRoot(pParent, iLbnd, iHbnd, pParent->m_iOffset+1); } else { //compute phase directly from offset int iColour = m_pNCManager->GetAlphabet()->GetColour(iSymbol, (pParent->m_iOffset+1)%2); // TODO: Exceptions / error handling in general CDasherNode::SDisplayInfo *pDisplayInfo = new CDasherNode::SDisplayInfo; pDisplayInfo->iColour = iColour; pDisplayInfo->bShove = true; pDisplayInfo->bVisible = true; pDisplayInfo->strDisplayText = m_pNCManager->GetAlphabet()->GetDisplayText(iSymbol); CAlphNode *pAlphNode; pNewNode = pAlphNode = makeSymbol(pParent, iLbnd, iHbnd, pDisplayInfo,iSymbol); // std::stringstream ssLabel; // ssLabel << m_pNCManager->GetAlphabet()->GetDisplayText(iSymbol) << ": " << pNewNode; // pDisplayInfo->strDisplayText = ssLabel.str(); - - pNewNode->m_iNumSymbols = 1; - pNewNode->m_iOffset = pParent->m_iOffset + 1; pAlphNode->iContext = CreateSymbolContext(pParent, iSymbol); } return pNewNode; } CDasherNode *CAlphabetManager::CSymbolNode::RebuildSymbol(CAlphNode *pParent, symbol iSymbol, unsigned int iLbnd, unsigned int iHbnd) { if(iSymbol == this->iSymbol) { SetRange(iLbnd, iHbnd); SetParent(pParent); DASHER_ASSERT(m_iOffset == pParent->m_iOffset + 1); return this; } return m_pMgr->CreateSymbolNode(pParent, iSymbol, iLbnd, iHbnd); } CDasherNode *CAlphabetManager::CGroupNode::RebuildSymbol(CAlphNode *pParent, symbol iSymbol, unsigned int iLbnd, unsigned int iHbnd) { return m_pMgr->CreateSymbolNode(pParent, iSymbol, iLbnd, iHbnd); } void CAlphabetManager::IterateChildGroups(CAlphNode *pParent, SGroupInfo *pParentGroup, CAlphNode *buildAround) { std::vector<unsigned int> *pCProb(pParent->GetProbInfo()); const int iMin(pParentGroup ? pParentGroup->iStart : 1); const int iMax(pParentGroup ? pParentGroup->iEnd : pCProb->size()); // TODO: Think through alphabet file formats etc. to make this class easier. // TODO: Throw a warning if parent node already has children // Create child nodes and add them int i(iMin); //lowest index of child which we haven't yet added SGroupInfo *pCurrentNode(pParentGroup ? pParentGroup->pChild : m_pNCManager->GetAlphabet()->m_pBaseGroup); // The SGroupInfo structure has something like linked list behaviour // Each SGroupInfo contains a pNext, a pointer to a sibling group info while (i < iMax) { CDasherNode *pNewChild; bool bSymbol = !pCurrentNode //gone past last subgroup || i < pCurrentNode->iStart; //not reached next subgroup const int iStart=i, iEnd = (bSymbol) ? i+1 : pCurrentNode->iEnd; //uint64 is platform-dependently #defined in DasherTypes.h as an (unsigned) 64-bit int ("__int64" or "long long int") unsigned int iLbnd = (((*pCProb)[iStart-1] - (*pCProb)[iMin-1]) * (uint64)(m_pNCManager->GetLongParameter(LP_NORMALIZATION))) / ((*pCProb)[iMax-1] - (*pCProb)[iMin-1]); unsigned int iHbnd = (((*pCProb)[iEnd-1] - (*pCProb)[iMin-1]) * (uint64)(m_pNCManager->GetLongParameter(LP_NORMALIZATION))) / ((*pCProb)[iMax-1] - (*pCProb)[iMin-1]); if (bSymbol) { pNewChild = (buildAround) ? buildAround->RebuildSymbol(pParent, i, iLbnd, iHbnd) : CreateSymbolNode(pParent, i, iLbnd, iHbnd); i++; //make one symbol at a time - move onto next in next iteration } else { //in/reached subgroup - do entire group in one go: pNewChild= (buildAround) ? buildAround->RebuildGroup(pParent, pCurrentNode, iLbnd, iHbnd) : CreateGroupNode(pParent, pCurrentNode, iLbnd, iHbnd); i = pCurrentNode->iEnd; //make one group at a time - so move past entire group... pCurrentNode = pCurrentNode->pNext; } DASHER_ASSERT(pParent->GetChildren().back()==pNewChild); } pParent->SetFlag(NF_ALLCHILDREN, true); } CAlphabetManager::CAlphNode::~CAlphNode() { delete m_pProbInfo; m_pMgr->m_pLanguageModel->ReleaseContext(iContext); } const std::string &CAlphabetManager::CSymbolNode::outputText() { return mgr()->m_pNCManager->GetAlphabet()->GetText(iSymbol); } void CAlphabetManager::CSymbolNode::Output(Dasher::VECTOR_SYMBOL_PROB* pAdded, int iNormalization) { //std::cout << this << " " << Parent() << ": Output at offset " << m_iOffset << " *" << m_pMgr->m_pNCManager->GetAlphabet()->GetText(t) << "* " << std::endl; Dasher::CEditEvent oEvent(1, outputText(), m_iOffset); m_pMgr->m_pNCManager->InsertEvent(&oEvent); // Track this symbol and its probability for logging purposes if (pAdded != NULL) { Dasher::SymbolProb sItem; sItem.sym = iSymbol; sItem.prob = Range() / (double)iNormalization; pAdded->push_back(sItem); } } -void CAlphabetManager::CSymbolNode::Undo() { +void CAlphabetManager::CSymbolNode::Undo(int *pNumDeleted) { Dasher::CEditEvent oEvent(2, outputText(), m_iOffset); m_pMgr->m_pNCManager->InsertEvent(&oEvent); + if (pNumDeleted) (*pNumDeleted)++; } CDasherNode *CAlphabetManager::CGroupNode::RebuildParent() { // CAlphNode's always have a parent, they inserted a symbol; CGroupNode's // with an m_pGroup have a container i.e. the parent group, unless // m_pGroup==NULL => "root" node where Alphabet->m_pBaseGroup is the *first*child*... if (m_pGroup == NULL) return NULL; //offset of group node is same as parent... return CAlphNode::RebuildParent(m_iOffset); } CDasherNode *CAlphabetManager::CSymbolNode::RebuildParent() { //parent's offset is one less than this. return CAlphNode::RebuildParent(m_iOffset-1); } CDasherNode *CAlphabetManager::CAlphNode::RebuildParent(int iNewOffset) { //possible that we have a parent, as RebuildParent() rebuilds back to closest AlphNode. if (Parent()) return Parent(); CAlphNode *pNewNode = m_pMgr->GetRoot(NULL, 0, 0, iNewOffset!=-1, iNewOffset+1); //now fill in the new node - recursively - until it reaches us m_pMgr->IterateChildGroups(pNewNode, NULL, this); //finally return our immediate parent (pNewNode may be an ancestor rather than immediate parent!) DASHER_ASSERT(Parent() != NULL); //although not required, we believe only NF_SEEN nodes are ever requested to rebuild their parents... DASHER_ASSERT(GetFlag(NF_SEEN)); //so set NF_SEEN on all created ancestors (of which pNewNode is the last) CDasherNode *pNode = this; do { pNode = pNode->Parent(); pNode->SetFlag(NF_SEEN, true); } while (pNode != pNewNode); return Parent(); } // TODO: Shouldn't there be an option whether or not to learn as we write? // For want of a better solution, game mode exemption explicit in this function void CAlphabetManager::CSymbolNode::SetFlag(int iFlag, bool bValue) { CDasherNode::SetFlag(iFlag, bValue); switch(iFlag) { case NF_COMMITTED: if(bValue && !GetFlag(NF_GAME) && m_pMgr->m_pInterface->GetBoolParameter(BP_LM_ADAPTIVE)) m_pMgr->m_pLanguageModel->LearnSymbol(m_pMgr->m_iLearnContext, iSymbol); break; } } diff --git a/Src/DasherCore/AlphabetManager.h b/Src/DasherCore/AlphabetManager.h index a301870..dc65355 100644 --- a/Src/DasherCore/AlphabetManager.h +++ b/Src/DasherCore/AlphabetManager.h @@ -1,150 +1,150 @@ // AlphabetManager.h // // Copyright (c) 2007 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #ifndef __alphabetmanager_h__ #define __alphabetmanager_h__ #include "LanguageModelling/LanguageModel.h" #include "DasherNode.h" #include "Parameters.h" #include "NodeManager.h" class CNodeCreationManager; struct SGroupInfo; namespace Dasher { class CDasherInterfaceBase; /// \ingroup Model /// @{ /// Implementation of CNodeManager for regular 'alphabet' nodes, ie /// the basic Dasher behaviour. Child nodes are populated according /// to the appropriate alphabet file, with sizes given by the /// language model. /// class CAlphabetManager : public CNodeManager { public: CAlphabetManager(CDasherInterfaceBase *pInterface, CNodeCreationManager *pNCManager, CLanguageModel *pLanguageModel); protected: class CGroupNode; class CAlphNode : public CDasherNode { public: virtual CAlphabetManager *mgr() {return m_pMgr;} CAlphNode(CDasherNode *pParent, unsigned int iLbnd, unsigned int iHbnd, CDasherNode::SDisplayInfo *pDispInfo, CAlphabetManager *pMgr); CLanguageModel::Context iContext; /// /// Delete any storage alocated for this node /// virtual ~CAlphNode(); virtual CLanguageModel::Context CloneAlphContext(CLanguageModel *pLanguageModel); CDasherNode *RebuildParent(int iNewOffset); ///Have to call this from CAlphabetManager, and from CGroupNode on a _different_ CAlphNode, hence public... virtual std::vector<unsigned int> *GetProbInfo(); virtual int ExpectedNumChildren(); virtual CDasherNode *RebuildSymbol(CAlphNode *pParent, symbol iSymbol, unsigned int iLbnd, unsigned int iHbnd)=0; virtual CGroupNode *RebuildGroup(CAlphNode *pParent, SGroupInfo *pInfo, unsigned int iLbnd, unsigned int iHbnd)=0; private: std::vector<unsigned int> *m_pProbInfo; protected: CAlphabetManager *m_pMgr; }; class CSymbolNode : public CAlphNode { public: CSymbolNode(CDasherNode *pParent, unsigned int iLbnd, unsigned int iHbnd, CDasherNode::SDisplayInfo *pDispInfo, CAlphabetManager *pMgr, symbol iSymbol); /// /// Provide children for the supplied node /// virtual void PopulateChildren(); virtual CDasherNode *RebuildParent(); virtual void Output(Dasher::VECTOR_SYMBOL_PROB* pAdded, int iNormalization); - virtual void Undo(); + virtual void Undo(int *pNumDeleted); virtual void SetFlag(int iFlag, bool bValue); virtual bool GameSearchNode(std::string strTargetUtf8Char); virtual void GetContext(CDasherInterfaceBase *pInterface, std::vector<symbol> &vContextSymbols, int iOffset, int iLength); virtual symbol GetAlphSymbol(); const symbol iSymbol; virtual CDasherNode *RebuildSymbol(CAlphNode *pParent, symbol iSymbol, unsigned int iLbnd, unsigned int iHbnd); virtual CGroupNode *RebuildGroup(CAlphNode *pParent, SGroupInfo *pInfo, unsigned int iLbnd, unsigned int iHbnd); private: virtual const std::string &outputText(); }; class CGroupNode : public CAlphNode { public: CGroupNode(CDasherNode *pParent, unsigned int iLbnd, unsigned int iHbnd, CDasherNode::SDisplayInfo *pDispInfo, CAlphabetManager *pMgr, SGroupInfo *pGroup); /// /// Provide children for the supplied node /// virtual CDasherNode *RebuildParent(); virtual void PopulateChildren(); virtual int ExpectedNumChildren(); virtual bool GameSearchNode(std::string strTargetUtf8Char); virtual CDasherNode *RebuildSymbol(CAlphNode *pParent, symbol iSymbol, unsigned int iLbnd, unsigned int iHbnd); virtual CGroupNode *RebuildGroup(CAlphNode *pParent, SGroupInfo *pInfo, unsigned int iLbnd, unsigned int iHbnd); std::vector<unsigned int> *GetProbInfo(); private: SGroupInfo *m_pGroup; }; public: /// /// Get a new root node owned by this manager /// bEnteredLast - true if this "root" node should be considered as entering the preceding symbol /// Offset is the index of the character which _child_ nodes (i.e. between which this root allows selection) /// will enter. (Also used to build context for preceding characters.) virtual CAlphNode *GetRoot(CDasherNode *pParent, unsigned int iLower, unsigned int iUpper, bool bEnteredLast, int iOffset); protected: /// /// Factory method for CAlphNode construction, so subclasses can override. /// virtual CSymbolNode *makeSymbol(CDasherNode *pParent, unsigned int iLbnd, unsigned int iHbnd, CDasherNode::SDisplayInfo *pDispInfo, symbol iSymbol); virtual CGroupNode *makeGroup(CDasherNode *pParent, unsigned int iLbnd, unsigned int iHbnd, CDasherNode::SDisplayInfo *pDispInfo, SGroupInfo *pGroup); virtual CDasherNode *CreateSymbolNode(CAlphNode *pParent, symbol iSymbol, unsigned int iLbnd, unsigned int iHbnd); virtual CLanguageModel::Context CreateSymbolContext(CAlphNode *pParent, symbol iSymbol); virtual CGroupNode *CreateGroupNode(CAlphNode *pParent, SGroupInfo *pInfo, unsigned int iLbnd, unsigned int iHbnd); CLanguageModel *m_pLanguageModel; CNodeCreationManager *m_pNCManager; private: void IterateChildGroups(CAlphNode *pParent, SGroupInfo *pParentGroup, CAlphNode *buildAround); CLanguageModel::Context m_iLearnContext; CDasherInterfaceBase *m_pInterface; }; /// @} } #endif diff --git a/Src/DasherCore/ControlManager.cpp b/Src/DasherCore/ControlManager.cpp index 0517681..ee64dbc 100644 --- a/Src/DasherCore/ControlManager.cpp +++ b/Src/DasherCore/ControlManager.cpp @@ -1,417 +1,405 @@ // ControlManager.cpp // // Copyright (c) 2007 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" #include "ControlManager.h" #include <cstring> using namespace Dasher; using namespace std; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG_MEMLEAKS #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif int CControlManager::m_iNextID = 0; CControlManager::CControlManager( CNodeCreationManager *pNCManager ) : m_pNCManager(pNCManager) { string SystemString = m_pNCManager->GetStringParameter(SP_SYSTEM_LOC); string UserLocation = m_pNCManager->GetStringParameter(SP_USER_LOC); m_iNextID = 0; // TODO: Need to fix this on WinCE build #ifndef _WIN32_WCE struct stat sFileInfo; string strFileName = UserLocation + "controllabels.xml"; // check first location for file if(stat(strFileName.c_str(), &sFileInfo) == -1) { // something went wrong strFileName = SystemString + "controllabels.xml"; // check second location for file if(stat(strFileName.c_str(), &sFileInfo) == -1) { // all else fails do something default LoadDefaultLabels(); } else LoadLabelsFromFile(strFileName, sFileInfo.st_size); } else LoadLabelsFromFile(strFileName, sFileInfo.st_size); ConnectNodes(); #endif } int CControlManager::LoadLabelsFromFile(string strFileName, int iFileSize) { // Implement Unicode names via xml from file: char* szFileBuffer = new char[iFileSize]; ifstream oFile(strFileName.c_str()); oFile.read(szFileBuffer, iFileSize); XML_Parser Parser = XML_ParserCreate(NULL); // Members passed as callbacks must be static, so don't have a "this" pointer. // We give them one through horrible casting so they can effect changes. XML_SetUserData(Parser, this); XML_SetElementHandler(Parser, XmlStartHandler, XmlEndHandler); XML_SetCharacterDataHandler(Parser, XmlCDataHandler); XML_Parse(Parser, szFileBuffer, iFileSize, false); // deallocate resources XML_ParserFree(Parser); oFile.close(); delete [] szFileBuffer; return 0; } int CControlManager::LoadDefaultLabels() { // TODO: Need to figure out how to handle offset changes here RegisterNode(CTL_ROOT, "Control", 8); RegisterNode(CTL_STOP, "Stop", 242); RegisterNode(CTL_PAUSE, "Pause", 241); RegisterNode(CTL_MOVE, "Move", -1); RegisterNode(CTL_MOVE_FORWARD, "->", -1); RegisterNode(CTL_MOVE_FORWARD_CHAR, ">", -1); RegisterNode(CTL_MOVE_FORWARD_WORD, ">>", -1); RegisterNode(CTL_MOVE_FORWARD_LINE, ">>>", -1); RegisterNode(CTL_MOVE_FORWARD_FILE, ">>>>", -1); RegisterNode(CTL_MOVE_BACKWARD, "<-", -1); RegisterNode(CTL_MOVE_BACKWARD_CHAR, "<", -1); RegisterNode(CTL_MOVE_BACKWARD_WORD, "<<", -1); RegisterNode(CTL_MOVE_BACKWARD_LINE, "<<<", -1); RegisterNode(CTL_MOVE_BACKWARD_FILE, "<<<<", -1); RegisterNode(CTL_DELETE, "Delete", -1); RegisterNode(CTL_DELETE_FORWARD, "->", -1); RegisterNode(CTL_DELETE_FORWARD_CHAR, ">", -1); RegisterNode(CTL_DELETE_FORWARD_WORD, ">>", -1); RegisterNode(CTL_DELETE_FORWARD_LINE, ">>>", -1); RegisterNode(CTL_DELETE_FORWARD_FILE, ">>>>", -1); RegisterNode(CTL_DELETE_BACKWARD, "<-", -1); RegisterNode(CTL_DELETE_BACKWARD_CHAR, "<", -1); RegisterNode(CTL_DELETE_BACKWARD_WORD, "<<", -1); RegisterNode(CTL_DELETE_BACKWARD_LINE, "<<<", -1); RegisterNode(CTL_DELETE_BACKWARD_FILE, "<<<<", -1); return 0; } int CControlManager::ConnectNodes() { ConnectNode(-1, CTL_ROOT, -2); ConnectNode(CTL_STOP, CTL_ROOT, -2); ConnectNode(CTL_PAUSE, CTL_ROOT, -2); ConnectNode(CTL_MOVE, CTL_ROOT, -2); ConnectNode(CTL_DELETE, CTL_ROOT, -2); ConnectNode(-1, CTL_STOP, -2); ConnectNode(CTL_ROOT, CTL_STOP, -2); ConnectNode(-1, CTL_PAUSE, -2); ConnectNode(CTL_ROOT, CTL_PAUSE, -2); ConnectNode(CTL_MOVE_FORWARD, CTL_MOVE, -2); ConnectNode(CTL_MOVE_BACKWARD, CTL_MOVE, -2); ConnectNode(CTL_MOVE_FORWARD_CHAR, CTL_MOVE_FORWARD, -2); ConnectNode(CTL_MOVE_FORWARD_WORD, CTL_MOVE_FORWARD, -2); ConnectNode(CTL_MOVE_FORWARD_LINE, CTL_MOVE_FORWARD, -2); ConnectNode(CTL_MOVE_FORWARD_FILE, CTL_MOVE_FORWARD, -2); ConnectNode(CTL_ROOT, CTL_MOVE_FORWARD_CHAR, -2); ConnectNode(CTL_MOVE_FORWARD, CTL_MOVE_FORWARD_CHAR, -2); ConnectNode(CTL_MOVE_BACKWARD, CTL_MOVE_FORWARD_CHAR, -2); ConnectNode(CTL_ROOT, CTL_MOVE_FORWARD_WORD, -2); ConnectNode(CTL_MOVE_FORWARD, CTL_MOVE_FORWARD_WORD, -2); ConnectNode(CTL_MOVE_BACKWARD, CTL_MOVE_FORWARD_WORD, -2); ConnectNode(CTL_ROOT, CTL_MOVE_FORWARD_LINE, -2); ConnectNode(CTL_MOVE_FORWARD, CTL_MOVE_FORWARD_LINE, -2); ConnectNode(CTL_MOVE_BACKWARD, CTL_MOVE_FORWARD_LINE, -2); ConnectNode(CTL_ROOT, CTL_MOVE_FORWARD_FILE, -2); ConnectNode(CTL_MOVE_FORWARD, CTL_MOVE_FORWARD_FILE, -2); ConnectNode(CTL_MOVE_BACKWARD, CTL_MOVE_FORWARD_FILE, -2); ConnectNode(CTL_MOVE_BACKWARD_CHAR, CTL_MOVE_BACKWARD, -2); ConnectNode(CTL_MOVE_BACKWARD_WORD, CTL_MOVE_BACKWARD, -2); ConnectNode(CTL_MOVE_BACKWARD_LINE, CTL_MOVE_BACKWARD, -2); ConnectNode(CTL_MOVE_BACKWARD_FILE, CTL_MOVE_BACKWARD, -2); ConnectNode(CTL_ROOT, CTL_MOVE_BACKWARD_CHAR, -2); ConnectNode(CTL_MOVE_FORWARD, CTL_MOVE_BACKWARD_CHAR, -2); ConnectNode(CTL_MOVE_BACKWARD, CTL_MOVE_BACKWARD_CHAR, -2); ConnectNode(CTL_ROOT, CTL_MOVE_BACKWARD_WORD, -2); ConnectNode(CTL_MOVE_FORWARD, CTL_MOVE_BACKWARD_WORD, -2); ConnectNode(CTL_MOVE_BACKWARD, CTL_MOVE_BACKWARD_WORD, -2); ConnectNode(CTL_ROOT, CTL_MOVE_BACKWARD_LINE, -2); ConnectNode(CTL_MOVE_FORWARD, CTL_MOVE_BACKWARD_LINE, -2); ConnectNode(CTL_MOVE_BACKWARD, CTL_MOVE_BACKWARD_LINE, -2); ConnectNode(CTL_ROOT, CTL_MOVE_BACKWARD_FILE, -2); ConnectNode(CTL_MOVE_FORWARD, CTL_MOVE_BACKWARD_FILE, -2); ConnectNode(CTL_MOVE_BACKWARD, CTL_MOVE_BACKWARD_FILE, -2); ConnectNode(CTL_DELETE_FORWARD, CTL_DELETE, -2); ConnectNode(CTL_DELETE_BACKWARD, CTL_DELETE, -2); ConnectNode(CTL_DELETE_FORWARD_CHAR, CTL_DELETE_FORWARD, -2); ConnectNode(CTL_DELETE_FORWARD_WORD, CTL_DELETE_FORWARD, -2); ConnectNode(CTL_DELETE_FORWARD_LINE, CTL_DELETE_FORWARD, -2); ConnectNode(CTL_DELETE_FORWARD_FILE, CTL_DELETE_FORWARD, -2); ConnectNode(CTL_ROOT, CTL_DELETE_FORWARD_CHAR, -2); ConnectNode(CTL_DELETE_FORWARD, CTL_DELETE_FORWARD_CHAR, -2); ConnectNode(CTL_DELETE_BACKWARD, CTL_DELETE_FORWARD_CHAR, -2); ConnectNode(CTL_ROOT, CTL_DELETE_FORWARD_WORD, -2); ConnectNode(CTL_DELETE_FORWARD, CTL_DELETE_FORWARD_WORD, -2); ConnectNode(CTL_DELETE_BACKWARD, CTL_DELETE_FORWARD_WORD, -2); ConnectNode(CTL_ROOT, CTL_DELETE_FORWARD_LINE, -2); ConnectNode(CTL_DELETE_FORWARD, CTL_DELETE_FORWARD_LINE, -2); ConnectNode(CTL_DELETE_BACKWARD, CTL_DELETE_FORWARD_LINE, -2); ConnectNode(CTL_ROOT, CTL_DELETE_FORWARD_FILE, -2); ConnectNode(CTL_DELETE_FORWARD, CTL_DELETE_FORWARD_FILE, -2); ConnectNode(CTL_DELETE_BACKWARD, CTL_DELETE_FORWARD_FILE, -2); ConnectNode(CTL_DELETE_BACKWARD_CHAR, CTL_DELETE_BACKWARD, -2); ConnectNode(CTL_DELETE_BACKWARD_WORD, CTL_DELETE_BACKWARD, -2); ConnectNode(CTL_DELETE_BACKWARD_LINE, CTL_DELETE_BACKWARD, -2); ConnectNode(CTL_DELETE_BACKWARD_FILE, CTL_DELETE_BACKWARD, -2); ConnectNode(CTL_ROOT, CTL_DELETE_BACKWARD_CHAR, -2); ConnectNode(CTL_DELETE_FORWARD, CTL_DELETE_BACKWARD_CHAR, -2); ConnectNode(CTL_DELETE_BACKWARD, CTL_DELETE_BACKWARD_CHAR, -2); ConnectNode(CTL_ROOT, CTL_DELETE_BACKWARD_WORD, -2); ConnectNode(CTL_DELETE_FORWARD, CTL_DELETE_BACKWARD_WORD, -2); ConnectNode(CTL_DELETE_BACKWARD, CTL_DELETE_BACKWARD_WORD, -2); ConnectNode(CTL_ROOT, CTL_DELETE_BACKWARD_LINE, -2); ConnectNode(CTL_DELETE_FORWARD, CTL_DELETE_BACKWARD_LINE, -2); ConnectNode(CTL_DELETE_BACKWARD, CTL_DELETE_BACKWARD_LINE, -2); ConnectNode(CTL_ROOT, CTL_DELETE_BACKWARD_FILE, -2); ConnectNode(CTL_DELETE_FORWARD, CTL_DELETE_BACKWARD_FILE, -2); ConnectNode(CTL_DELETE_BACKWARD, CTL_DELETE_BACKWARD_FILE, -2); return 0; } CControlManager::~CControlManager() { for(std::map<int,SControlItem*>::iterator i = m_mapControlMap.begin(); i != m_mapControlMap.end(); i++) { SControlItem* pNewNode = i->second; if (pNewNode != NULL) { delete pNewNode; pNewNode = NULL; } } } void CControlManager::RegisterNode( int iID, std::string strLabel, int iColour ) { SControlItem *pNewNode; pNewNode = new SControlItem; // FIXME - do constructor sanely pNewNode->strLabel = strLabel; pNewNode->iID = iID; pNewNode->iColour = iColour; m_mapControlMap[iID] = pNewNode; } void CControlManager::ConnectNode(int iChild, int iParent, int iAfter) { // FIXME - iAfter currently ignored (eventually -1 = start, -2 = end) if( iChild == -1 ) {// Corresponds to escaping back to alphabet SControlItem* node = m_mapControlMap[iParent]; if(node) node->vChildren.push_back(NULL); } else m_mapControlMap[iParent]->vChildren.push_back(m_mapControlMap[iChild]); } void CControlManager::DisconnectNode(int iChild, int iParent) { SControlItem* pParentNode = m_mapControlMap[iParent]; SControlItem* pChildNode = m_mapControlMap[iChild]; for(std::vector<SControlItem *>::iterator itChild(pParentNode->vChildren.begin()); itChild != pParentNode->vChildren.end(); ++itChild) if(*itChild == pChildNode) pParentNode->vChildren.erase(itChild); } CDasherNode *CControlManager::GetRoot(CDasherNode *pParent, unsigned int iLower, unsigned int iUpper, int iOffset) { // TODO: Tie this structure to info contained in control map CDasherNode::SDisplayInfo *pDisplayInfo = new CDasherNode::SDisplayInfo; pDisplayInfo->iColour = m_mapControlMap[0]->iColour; pDisplayInfo->bShove = false; pDisplayInfo->bVisible = true; pDisplayInfo->strDisplayText = m_mapControlMap[0]->strLabel; CContNode *pNewNode = new CContNode(pParent, iLower, iUpper, pDisplayInfo, this); // FIXME - handle context properly // pNewNode->SetContext(m_pLanguageModel->CreateEmptyContext()); pNewNode->pControlItem = m_mapControlMap[0]; pNewNode->m_iOffset = iOffset; return pNewNode; } CControlManager::CContNode::CContNode(CDasherNode *pParent, unsigned int iLbnd, unsigned int iHbnd, CDasherNode::SDisplayInfo *pDisplayInfo, CControlManager *pMgr) : CDasherNode(pParent, iLbnd, iHbnd, pDisplayInfo), m_pMgr(pMgr) { } void CControlManager::CContNode::PopulateChildren() { CDasherNode *pNewNode; int iNChildren( pControlItem->vChildren.size() ); int iIdx(0); for(std::vector<SControlItem *>::iterator it(pControlItem->vChildren.begin()); it != pControlItem->vChildren.end(); ++it) { // FIXME - could do this better unsigned int iLbnd( iIdx*(m_pMgr->m_pNCManager->GetLongParameter(LP_NORMALIZATION)/iNChildren)); unsigned int iHbnd( (iIdx+1)*(m_pMgr->m_pNCManager->GetLongParameter(LP_NORMALIZATION)/iNChildren)); if( *it == NULL ) { // Escape back to alphabet pNewNode = m_pMgr->m_pNCManager->GetAlphRoot(this, iLbnd, iHbnd, false, m_iOffset); } else { int iColour((*it)->iColour); if( iColour == -1 ) { iColour = (iIdx%99)+11; } CDasherNode::SDisplayInfo *pDisplayInfo = new CDasherNode::SDisplayInfo; pDisplayInfo->iColour = iColour; pDisplayInfo->bShove = false; pDisplayInfo->bVisible = true; pDisplayInfo->strDisplayText = (*it)->strLabel; CContNode *pContNode; pNewNode = pContNode = new CContNode(this, iLbnd, iHbnd, pDisplayInfo, m_pMgr); pContNode->pControlItem = *it; pNewNode->m_iOffset = m_iOffset; } DASHER_ASSERT(GetChildren().back()==pNewNode); ++iIdx; } } int CControlManager::CContNode::ExpectedNumChildren() { return pControlItem->vChildren.size(); } void CControlManager::CContNode::Output(Dasher::VECTOR_SYMBOL_PROB* pAdded, int iNormalization ) { CControlEvent oEvent(pControlItem->iID); // TODO: Need to reimplement this // m_pNCManager->m_bContextSensitive=false; m_pMgr->m_pNCManager->InsertEvent(&oEvent); } -void CControlManager::CContNode::Undo() { - // Do we ever need this? - // One other thing we probably want is notification when we leave a node - that way we can eg speed up again if we slowed down - m_pMgr->m_pNCManager->SetLongParameter(LP_BOOSTFACTOR, 100); - //Re-enable auto speed control! - if (m_pMgr->bDisabledSpeedControl) - { - m_pMgr->bDisabledSpeedControl = false; - m_pMgr->m_pNCManager->SetBoolParameter(BP_AUTO_SPEEDCONTROL, 1); - } -} - void CControlManager::CContNode::Enter() { // Slow down to half the speed we were at m_pMgr->m_pNCManager->SetLongParameter(LP_BOOSTFACTOR, 50); //Disable auto speed control! m_pMgr->bDisabledSpeedControl = m_pMgr->m_pNCManager->GetBoolParameter(BP_AUTO_SPEEDCONTROL); m_pMgr->m_pNCManager->SetBoolParameter(BP_AUTO_SPEEDCONTROL, 0); } void CControlManager::CContNode::Leave() { // Now speed back up, by doubling the speed we were at in control mode m_pMgr->m_pNCManager->SetLongParameter(LP_BOOSTFACTOR, 100); //Re-enable auto speed control! if (m_pMgr->bDisabledSpeedControl) { m_pMgr->bDisabledSpeedControl = false; m_pMgr->m_pNCManager->SetBoolParameter(BP_AUTO_SPEEDCONTROL, 1); } } void CControlManager::XmlStartHandler(void *pUserData, const XML_Char *szName, const XML_Char **aszAttr) { int colour=-1; string str; if(0==strcmp(szName, "label")) { for(int i = 0; aszAttr[i]; i += 2) { if(0==strcmp(aszAttr[i],"value")) { str = string(aszAttr[i+1]); } if(0==strcmp(aszAttr[i],"color")) { colour = atoi(aszAttr[i+1]); } } ((CControlManager*)pUserData)->RegisterNode(CControlManager::m_iNextID++, str, colour); } } void CControlManager::XmlEndHandler(void *pUserData, const XML_Char *szName) { return; } void CControlManager::XmlCDataHandler(void *pUserData, const XML_Char *szData, int iLength){ return; } void CControlManager::CContNode::SetControlOffset(int iOffset) { m_iOffset = iOffset; } diff --git a/Src/DasherCore/ControlManager.h b/Src/DasherCore/ControlManager.h index 3cc47d3..dc01666 100644 --- a/Src/DasherCore/ControlManager.h +++ b/Src/DasherCore/ControlManager.h @@ -1,134 +1,133 @@ // ControlManager.h // // Copyright (c) 2007 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #ifndef __controlmanager_h__ #define __controlmanager_h__ #include "DasherModel.h" #include "DasherNode.h" #include "Event.h" #include "NodeManager.h" #include <vector> #include <map> #include <fstream> #include <iostream> #ifndef _WIN32_WCE #include <sys/stat.h> #endif #include <string> #include <expat.h> using namespace std; namespace Dasher { class CDasherModel; /// \ingroup Model /// @{ /// A node manager which deals with control nodes. /// Currently can only have one instance due to use /// of static members for callbacks from expat. /// class CControlManager : public CNodeManager { public: enum { CTL_ROOT, CTL_STOP, CTL_PAUSE, CTL_MOVE, CTL_MOVE_FORWARD, CTL_MOVE_FORWARD_CHAR, CTL_MOVE_FORWARD_WORD, CTL_MOVE_FORWARD_LINE, CTL_MOVE_FORWARD_FILE, CTL_MOVE_BACKWARD, CTL_MOVE_BACKWARD_CHAR, CTL_MOVE_BACKWARD_WORD, CTL_MOVE_BACKWARD_LINE, CTL_MOVE_BACKWARD_FILE, CTL_DELETE, CTL_DELETE_FORWARD, CTL_DELETE_FORWARD_CHAR, CTL_DELETE_FORWARD_WORD, CTL_DELETE_FORWARD_LINE, CTL_DELETE_FORWARD_FILE, CTL_DELETE_BACKWARD, CTL_DELETE_BACKWARD_CHAR, CTL_DELETE_BACKWARD_WORD, CTL_DELETE_BACKWARD_LINE, CTL_DELETE_BACKWARD_FILE, CTL_USER }; CControlManager(CNodeCreationManager *pNCManager); ~CControlManager(); /// /// Get a new root node owned by this manager /// virtual CDasherNode *GetRoot(CDasherNode *pParent, unsigned int iLower, unsigned int iUpper, int iOffset); void RegisterNode( int iID, std::string strLabel, int iColour ); void ConnectNode(int iChild, int iParent, int iAfter); void DisconnectNode(int iChild, int iParent); private: struct SControlItem { std::vector<SControlItem *> vChildren; std::string strLabel; int iID; int iColour; }; class CContNode : public CDasherNode { public: CControlManager *mgr() {return m_pMgr;} CContNode(CDasherNode *pParent, unsigned int iLbnd, unsigned int iHbnd, CDasherNode::SDisplayInfo *pDisplayInfo, CControlManager *pMgr); /// /// Provide children for the supplied node /// virtual void PopulateChildren(); virtual int ExpectedNumChildren(); virtual void Output(Dasher::VECTOR_SYMBOL_PROB* pAdded, int iNormalization ); - virtual void Undo(); virtual void Enter(); virtual void Leave(); void SetControlOffset(int iOffset); SControlItem *pControlItem; private: CControlManager *m_pMgr; }; static void XmlStartHandler(void *pUserData, const XML_Char *szName, const XML_Char **aszAttr); static void XmlEndHandler(void *pUserData, const XML_Char *szName); static void XmlCDataHandler(void *pUserData, const XML_Char *szData, int iLength); int LoadLabelsFromFile(string strFileName, int iFileSize); int LoadDefaultLabels(); int ConnectNodes(); static int m_iNextID; CNodeCreationManager *m_pNCManager; std::map<int,SControlItem*> m_mapControlMap; ///Whether we'd temporarily disabled Automatic Speed Control ///(if _and only if_ so, should re-enable it when leaving a node) bool bDisabledSpeedControl; }; /// @} } #endif diff --git a/Src/DasherCore/ConversionManager.cpp b/Src/DasherCore/ConversionManager.cpp index 2b41eb7..183a5ec 100644 --- a/Src/DasherCore/ConversionManager.cpp +++ b/Src/DasherCore/ConversionManager.cpp @@ -1,198 +1,200 @@ // ConversionManager.cpp // // Copyright (c) 2007 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #ifdef HAVE_CONFIG_H #include <config.h> #endif #include "ConversionManager.h" #include "Event.h" #include "EventHandler.h" #include "NodeCreationManager.h" #include "DasherModel.h" #include <iostream> #include <cstring> #include <string> #include <vector> #include <stdlib.h> //Note the new implementation in Mandarin Dasher may not be compatible with the previous implementation of Japanese Dasher //Need to reconcile (a small project) using namespace Dasher; CConversionManager::CConversionManager(CNodeCreationManager *pNCManager, CAlphabet *pAlphabet) { m_pNCManager = pNCManager; m_pAlphabet = pAlphabet; m_iRefCount = 1; //Testing for alphabet details, delete if needed: /* int alphSize = pNCManager->GetAlphabet()->GetNumberSymbols(); std::cout<<"Alphabet size: "<<alphSize<<std::endl; for(int i =0; i<alphSize; i++) std::cout<<"symbol: "<<i<<" display text:"<<pNCManager->GetAlphabet()->GetDisplayText(i)<<std::endl; */ } CConversionManager::CConvNode *CConversionManager::makeNode(CDasherNode *pParent, unsigned int iLbnd, unsigned int iHbnd, CDasherNode::SDisplayInfo *pDispInfo) { return new CConvNode(pParent, iLbnd, iHbnd, pDispInfo, this); } CConversionManager::CConvNode *CConversionManager::GetRoot(CDasherNode *pParent, unsigned int iLower, unsigned int iUpper, int iOffset) { // TODO: Parameters here are placeholders - need to figure out what's right CDasherNode::SDisplayInfo *pDisplayInfo = new CDasherNode::SDisplayInfo; pDisplayInfo->iColour = 9; // TODO: Hard coded value pDisplayInfo->bShove = true; pDisplayInfo->bVisible = true; pDisplayInfo->strDisplayText = ""; // TODO: Hard coded value, needs i18n CConvNode *pNewNode = makeNode(pParent, iLower, iUpper, pDisplayInfo); // FIXME - handle context properly // TODO: Reimplemnt ----- // pNewNode->SetContext(m_pLanguageModel->CreateEmptyContext()); // ----- pNewNode->bisRoot = true; pNewNode->m_iOffset = iOffset; pNewNode->pLanguageModel = NULL; pNewNode->pSCENode = 0; return pNewNode; } CConversionManager::CConvNode::CConvNode(CDasherNode *pParent, unsigned int iLbnd, unsigned int iHbnd, CDasherNode::SDisplayInfo *pDispInfo, CConversionManager *pMgr) : CDasherNode(pParent, iLbnd, iHbnd, pDispInfo), m_pMgr(pMgr) { pMgr->m_iRefCount++; } void CConversionManager::CConvNode::PopulateChildren() { DASHER_ASSERT(m_pMgr->m_pNCManager); // If no helper class is present then just drop straight back to an // alphabet root. This should only happen in error cases, and the // user should have been warned here. // unsigned int iLbnd(0); unsigned int iHbnd(m_pMgr->m_pNCManager->GetLongParameter(LP_NORMALIZATION)); CDasherNode *pNewNode = m_pMgr->m_pNCManager->GetAlphRoot(this, iLbnd, iHbnd, false, m_iOffset + 1); DASHER_ASSERT(GetChildren().back()==pNewNode); } int CConversionManager::CConvNode::ExpectedNumChildren() { return 1; //the alphabet root } CConversionManager::CConvNode::~CConvNode() { pLanguageModel->ReleaseContext(iContext); m_pMgr->Unref(); } void CConversionManager::RecursiveDumpTree(SCENode *pCurrent, unsigned int iDepth) { const std::vector<SCENode *> &children = pCurrent->GetChildren(); for (std::vector<SCENode *>::const_iterator it = children.begin(); it!=children.end(); it++) { SCENode *pCurrent(*it); for(unsigned int i(0); i < iDepth; ++i) std::cout << "-"; std::cout << " " << pCurrent->pszConversion << std::endl;//" " << pCurrent->IsHeadAndCandNum << " " << pCurrent->CandIndex << " " << pCurrent->IsComplete << " " << pCurrent->AcCharCount << std::endl; RecursiveDumpTree(pCurrent, iDepth + 1); } } void CConversionManager::CConvNode::GetContext(CDasherInterfaceBase *pInterface, std::vector<symbol> &vContextSymbols, int iOffset, int iLength) { if (!GetFlag(NF_SEEN) && iOffset+iLength-1 == m_iOffset) { //ACL I'm extrapolating from PinYinConversionHelper (in which root nodes have their // Symbol set by SetConvSymbol, and child nodes are created in PopulateChildren // from SCENode's with Symbols having been set in in AssignSizes); not really sure // whether this is applicable in the general case(! - but although I think it's right // for PinYin, it wouldn't actually be used there, as MandarinDasher overrides contexts // everywhere!) DASHER_ASSERT(bisRoot || pSCENode); if (bisRoot || pSCENode->Symbol!=-1) { if (iLength>1) Parent()->GetContext(pInterface, vContextSymbols, iOffset, iLength-1); vContextSymbols.push_back(bisRoot ? iSymbol : pSCENode->Symbol); return; } //else, non-root with pSCENode->Symbol==-1 => fallthrough back to superclass code } CDasherNode::GetContext(pInterface, vContextSymbols, iOffset, iLength); } void CConversionManager::CConvNode::Output(Dasher::VECTOR_SYMBOL_PROB* pAdded, int iNormalization) { // TODO: Reimplement this // m_pNCManager->m_bContextSensitive = true; SCENode *pCurrentSCENode(pSCENode); if(pCurrentSCENode){ Dasher::CEditEvent oEvent(1, pCurrentSCENode->pszConversion, m_iOffset); m_pMgr->m_pNCManager->InsertEvent(&oEvent); if((GetChildren())[0]->mgr() == m_pMgr) { if (static_cast<CConvNode *>(GetChildren()[0])->m_pMgr == m_pMgr) { Dasher::CEditEvent oEvent(11, "", 0); m_pMgr->m_pNCManager->InsertEvent(&oEvent); } } } else { if(!bisRoot) { Dasher::CEditEvent oOPEvent(1, "|", m_iOffset); m_pMgr->m_pNCManager->InsertEvent(&oOPEvent); } else { Dasher::CEditEvent oOPEvent(1, ">", m_iOffset); m_pMgr->m_pNCManager->InsertEvent(&oOPEvent); } Dasher::CEditEvent oEvent(10, "", 0); m_pMgr->m_pNCManager->InsertEvent(&oEvent); } } -void CConversionManager::CConvNode::Undo() { +void CConversionManager::CConvNode::Undo(int *pNumDeleted) { + //ACL note: possibly ought to update pNumDeleted here if non-null, + // but conversion symbols were not logged by old code so am not starting now! SCENode *pCurrentSCENode(pSCENode); if(pCurrentSCENode) { if(pCurrentSCENode->pszConversion && (strlen(pCurrentSCENode->pszConversion) > 0)) { Dasher::CEditEvent oEvent(2, pCurrentSCENode->pszConversion, m_iOffset); m_pMgr->m_pNCManager->InsertEvent(&oEvent); } } else { if(!bisRoot) { Dasher::CEditEvent oOPEvent(2, "|", m_iOffset); m_pMgr->m_pNCManager->InsertEvent(&oOPEvent); } else { Dasher::CEditEvent oOPEvent(2, ">", m_iOffset); m_pMgr->m_pNCManager->InsertEvent(&oOPEvent); } } } diff --git a/Src/DasherCore/ConversionManager.h b/Src/DasherCore/ConversionManager.h index 02d5d05..146304b 100644 --- a/Src/DasherCore/ConversionManager.h +++ b/Src/DasherCore/ConversionManager.h @@ -1,157 +1,157 @@ // ConversionManager.h // // Copyright (c) 2007 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #ifndef __conversion_manager_h__ #define __conversion_manager_h__ #include "DasherTypes.h" #include "LanguageModelling/LanguageModel.h" // Urgh - we really shouldn't need to know about language models here #include "DasherNode.h" #include "SCENode.h" #include "NodeManager.h" // TODO: Conversion manager needs to deal with offsets and contexts - Will: See Phil for an explanation. class CNodeCreationManager; namespace Dasher { /// \ingroup Model /// @{ /// This class manages nodes in conversion subtrees, typically used /// for languages where complex characters are entered through a /// composition process, for example Japanese and Chinese. /// /// A new CConversionManager is created for each subtree, and /// therefore represents the conversion of a single phrase. The /// phrase to be converted is read by recursing through the parent /// tree. An instance of CConversionHelper is shared by several /// CConversionManagers, and performs the language dependent aspects /// of conversion. Specifically construction of the candidate /// lattice and assignment of weights. /// /// The general policy is to delay computation as far as possible, /// to avoid unnecessary computational load. The candidate lattice /// is therefore built at the first call to PopulateChildren, and /// weights are only assigned when the appropriate node has its /// child list populated. /// /// See CConversionHelper for details of the language specific /// aspects of conversion, and CNodeManager for details of the node /// management process. /// class CConversionManager : public CNodeManager { public: // TODO: We shouldn't need to know about this stuff, but the code is somewhat in knots at the moment CConversionManager(CNodeCreationManager *pNCManager, CAlphabet *pAlphabet); /// /// Decrement reference count /// virtual void Unref() { --m_iRefCount; // std::cout << "Unref, new count = " << m_iRefCount << std::endl; if(m_iRefCount == 0) { // std::cout << "Deleting " << this << std::endl; delete this; } }; protected: class CConvNode : public CDasherNode { public: CConversionManager *mgr() {return m_pMgr;} CConvNode(CDasherNode *pParent, unsigned int iLbnd, unsigned int iHbnd, CDasherNode::SDisplayInfo *pDispInfo, CConversionManager *pMgr); /// /// Provide children for the supplied node /// virtual void PopulateChildren(); virtual int ExpectedNumChildren(); ~CConvNode(); ///Attempts to fill vContextSymbols with the context that would exist _after_ this node has been entered void GetContext(CDasherInterfaceBase *pInterface, std::vector<symbol> &vContextSymbols, int iOffset, int iLength); /// /// Called whenever a node belonging to this manager first /// moves under the crosshair /// virtual void Output(Dasher::VECTOR_SYMBOL_PROB* pAdded, int iNormalization); /// /// Called when a node is left backwards /// - virtual void Undo(); + virtual void Undo(int *pNumDeleted); protected: CConversionManager *m_pMgr; public: //to ConversionManager and subclasses only, of course... //TODO: REVISE symbol iSymbol; // int iPhase; CLanguageModel *pLanguageModel; CLanguageModel::Context iContext; SCENode * pSCENode; bool bisRoot; // True for root conversion nodes //int iGameOffset; }; public: /// /// Get a new root node owned by this manager /// virtual CConvNode *GetRoot(CDasherNode *pParent, unsigned int iLower, unsigned int iUpper, int iOffset); protected: virtual CConvNode *makeNode(CDasherNode *pParent, unsigned int iLbnd, unsigned int iHbnd, CDasherNode::SDisplayInfo *pDispInfo); CNodeCreationManager *m_pNCManager; CAlphabet *m_pAlphabet; private: /// /// Dump tree to stdout (debug) /// void RecursiveDumpTree(SCENode *pCurrent, unsigned int iDepth); /// /// Reference count /// int m_iRefCount; }; /// @} } #endif diff --git a/Src/DasherCore/DasherModel.cpp b/Src/DasherCore/DasherModel.cpp index 7d08ddb..0dc3a75 100644 --- a/Src/DasherCore/DasherModel.cpp +++ b/Src/DasherCore/DasherModel.cpp @@ -36,775 +36,772 @@ using namespace Dasher; using namespace std; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG_MEMLEAKS #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif // FIXME - need to get node deletion working properly and implement reference counting // CDasherModel CDasherModel::CDasherModel(CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CNodeCreationManager *pNCManager, CDasherInterfaceBase *pDasherInterface, CDasherView *pView, int iOffset) : CFrameRate(pEventHandler, pSettingsStore) { m_pNodeCreationManager = pNCManager; m_pDasherInterface = pDasherInterface; m_bGameMode = GetBoolParameter(BP_GAME_MODE); m_iOffset = iOffset; // TODO: Set through build routine DASHER_ASSERT(m_pNodeCreationManager != NULL); DASHER_ASSERT(m_pDasherInterface != NULL); m_pLastOutput = m_Root = NULL; m_Rootmin = 0; m_Rootmax = 0; m_iDisplayOffset = 0; m_dTotalNats = 0.0; // TODO: Need to rationalise the require conversion methods #ifdef JAPANESE m_bRequireConversion = true; #else m_bRequireConversion = false; #endif SetBoolParameter(BP_CONVERSION_MODE, m_bRequireConversion); m_dAddProb = 0.003; int iNormalization = GetLongParameter(LP_NORMALIZATION); m_Rootmin_min = int64_min / iNormalization / 2; m_Rootmax_max = int64_max / iNormalization / 2; InitialiseAtOffset(iOffset, pView); } CDasherModel::~CDasherModel() { if (m_pLastOutput) m_pLastOutput->Leave(); if(oldroots.size() > 0) { delete oldroots[0]; oldroots.clear(); // At this point we have also deleted the root - so better NULL pointer m_Root = NULL; } else { delete m_Root; m_Root = NULL; } } void CDasherModel::HandleEvent(Dasher::CEvent *pEvent) { CFrameRate::HandleEvent(pEvent); if(pEvent->m_iEventType == EV_PARAM_NOTIFY) { Dasher::CParameterNotificationEvent * pEvt(static_cast < Dasher::CParameterNotificationEvent * >(pEvent)); switch (pEvt->m_iParameter) { case BP_CONTROL_MODE: // Rebuild the model if control mode is switched on/off RebuildAroundCrosshair(); break; case BP_SMOOTH_OFFSET: if (!GetBoolParameter(BP_SMOOTH_OFFSET)) //smoothing has just been turned off. End any transition/jump currently // in progress at it's current point AbortOffset(); break; case BP_DASHER_PAUSED: if(GetBoolParameter(BP_SLOW_START)) TriggerSlowdown(); //else, leave m_iStartTime as is - will result in no slow start break; case BP_GAME_MODE: m_bGameMode = GetBoolParameter(BP_GAME_MODE); // Maybe reload something here to begin game mode? break; default: break; } } else if(pEvent->m_iEventType == EV_EDIT) { // Keep track of where we are in the buffer CEditEvent *pEditEvent(static_cast < CEditEvent * >(pEvent)); if(pEditEvent->m_iEditType == 1) { m_iOffset += pEditEvent->m_sText.size(); } else if(pEditEvent->m_iEditType == 2) { m_iOffset -= pEditEvent->m_sText.size(); } } } void CDasherModel::Make_root(CDasherNode *pNewRoot) { // std::cout << "Make root" << std::endl; DASHER_ASSERT(pNewRoot != NULL); DASHER_ASSERT(pNewRoot->Parent() == m_Root); m_Root->SetFlag(NF_COMMITTED, true); // TODO: Is the stack necessary at all? We may as well just keep the // existing data structure? oldroots.push_back(m_Root); // TODO: tidy up conditional while((oldroots.size() > 10) && (!m_bRequireConversion || (oldroots[0]->GetFlag(NF_CONVERTED)))) { oldroots[0]->OrphanChild(oldroots[1]); delete oldroots[0]; oldroots.pop_front(); } m_Root = pNewRoot; // Update the root coordinates, as well as any currently scheduled locations const myint range = m_Rootmax - m_Rootmin; m_Rootmax = m_Rootmin + (range * m_Root->Hbnd()) / GetLongParameter(LP_NORMALIZATION); m_Rootmin = m_Rootmin + (range * m_Root->Lbnd()) / GetLongParameter(LP_NORMALIZATION); for(std::deque<SGotoItem>::iterator it(m_deGotoQueue.begin()); it != m_deGotoQueue.end(); ++it) { const myint r = it->iN2 - it->iN1; it->iN2 = it->iN1 + (r * m_Root->Hbnd()) / GetLongParameter(LP_NORMALIZATION); it->iN1 = it->iN1 + (r * m_Root->Lbnd()) / GetLongParameter(LP_NORMALIZATION); } } void CDasherModel::RecursiveMakeRoot(CDasherNode *pNewRoot) { DASHER_ASSERT(pNewRoot != NULL); DASHER_ASSERT(m_Root != NULL); if(pNewRoot == m_Root) return; // TODO: we really ought to check that pNewRoot is actually a // descendent of the root, although that should be guaranteed if(pNewRoot->Parent() != m_Root) RecursiveMakeRoot(pNewRoot->Parent()); Make_root(pNewRoot); } // only used when BP_CONTROL changes, so not very often. void CDasherModel::RebuildAroundCrosshair() { CDasherNode *pNode = Get_node_under_crosshair(); DASHER_ASSERT(pNode != NULL); DASHER_ASSERT(pNode == m_pLastOutput); RecursiveMakeRoot(pNode); DASHER_ASSERT(m_Root == pNode); ClearRootQueue(); m_Root->Delete_children(); m_Root->PopulateChildren(); } void CDasherModel::Reparent_root() { DASHER_ASSERT(m_Root != NULL); // Change the root node to the parent of the existing node. We need // to recalculate the coordinates for the "new" root as the user may // have moved around within the current root CDasherNode *pNewRoot; if(oldroots.size() == 0) { pNewRoot = m_Root->RebuildParent(); // Return if there's no existing parent and no way of recreating one if(pNewRoot == NULL) return; } else { pNewRoot = oldroots.back(); oldroots.pop_back(); } pNewRoot->SetFlag(NF_COMMITTED, false); DASHER_ASSERT(m_Root->Parent() == pNewRoot); const myint lower(m_Root->Lbnd()), upper(m_Root->Hbnd()); const myint iRange(upper-lower); myint iRootWidth(m_Rootmax - m_Rootmin); // Fail if the new root is bigger than allowed by normalisation if(((myint((GetLongParameter(LP_NORMALIZATION) - upper)) / static_cast<double>(iRange)) > (m_Rootmax_max - m_Rootmax)/static_cast<double>(iRootWidth)) || ((myint(lower) / static_cast<double>(iRange)) > (m_Rootmin - m_Rootmin_min) / static_cast<double>(iRootWidth))) { //but cache the (currently-unusable) root node - else we'll keep recreating (and deleting) it on every frame... oldroots.push_back(pNewRoot); return; } //Update the root coordinates to reflect the new root m_Root = pNewRoot; m_Rootmax = m_Rootmax + ((GetLongParameter(LP_NORMALIZATION) - upper) * iRootWidth) / iRange; m_Rootmin = m_Rootmin - (lower * iRootWidth) / iRange; for(std::deque<SGotoItem>::iterator it(m_deGotoQueue.begin()); it != m_deGotoQueue.end(); ++it) { iRootWidth = it->iN2 - it->iN1; it->iN2 = it->iN2 + (myint((GetLongParameter(LP_NORMALIZATION) - upper)) * iRootWidth / iRange); it->iN1 = it->iN1 - (myint(lower) * iRootWidth / iRange); } } void CDasherModel::ClearRootQueue() { while(oldroots.size() > 0) { if(oldroots.size() > 1) { oldroots[0]->OrphanChild(oldroots[1]); } else { oldroots[0]->OrphanChild(m_Root); } delete oldroots[0]; oldroots.pop_front(); } } CDasherNode *CDasherModel::Get_node_under_crosshair() { DASHER_ASSERT(m_Root != NULL); return m_Root->Get_node_under(GetLongParameter(LP_NORMALIZATION), m_Rootmin + m_iDisplayOffset, m_Rootmax + m_iDisplayOffset, GetLongParameter(LP_OX), GetLongParameter(LP_OY)); } void CDasherModel::DeleteTree() { ClearRootQueue(); delete m_Root; m_Root = NULL; } void CDasherModel::InitialiseAtOffset(int iOffset, CDasherView *pView) { if (m_pLastOutput) m_pLastOutput->Leave(); DeleteTree(); m_Root = m_pNodeCreationManager->GetAlphRoot(NULL, 0,GetLongParameter(LP_NORMALIZATION), iOffset!=0, iOffset); m_pLastOutput = (m_Root->GetFlag(NF_SEEN)) ? m_Root : NULL; // Create children of the root... ExpandNode(m_Root); // Set the root coordinates so that the root node is an appropriate // size and we're not in any of the children double dFraction( 1 - (1 - m_Root->MostProbableChild() / static_cast<double>(GetLongParameter(LP_NORMALIZATION))) / 2.0 ); int iWidth( static_cast<int>( (GetLongParameter(LP_MAX_Y) / (2.0*dFraction)) ) ); m_Rootmin = GetLongParameter(LP_MAX_Y) / 2 - iWidth / 2; m_Rootmax = GetLongParameter(LP_MAX_Y) / 2 + iWidth / 2; m_iDisplayOffset = 0; //now (re)create parents, while they show on the screen if(pView) { while(pView->IsNodeVisible(m_Rootmin,m_Rootmax)) { CDasherNode *pOldRoot = m_Root; Reparent_root(); if(m_Root == pOldRoot) break; } } // TODO: See if this is better positioned elsewhere m_pDasherInterface->ScheduleRedraw(); } void CDasherModel::Get_new_root_coords(dasherint X, dasherint Y, dasherint &r1, dasherint &r2, unsigned long iTime) { DASHER_ASSERT(m_Root != NULL); if(m_iStartTime == 0) m_iStartTime = iTime; int iSteps = Steps(); double dFactor; if(GetBoolParameter(BP_SLOW_START) && ((iTime - m_iStartTime) < GetLongParameter(LP_SLOW_START_TIME))) dFactor = 0.1 * (1 + 9 * ((iTime - m_iStartTime) / static_cast<double>(GetLongParameter(LP_SLOW_START_TIME)))); else dFactor = 1.0; iSteps = static_cast<int>(iSteps / dFactor); // Avoid X == 0, as this corresponds to infinite zoom if (X <= 0) X = 1; // If X is too large we risk overflow errors, so limit it dasherint iMaxX = (1 << 29) / iSteps; if (X > iMaxX) X = iMaxX; // Mouse coords X, Y // new root{min,max} r1,r2, old root{min,max} R1,R2 const dasherint R1 = m_Rootmin; const dasherint R2 = m_Rootmax; // const dasherint Y1 = 0; dasherint Y2(GetLongParameter(LP_MAX_Y)); dasherint iOX(GetLongParameter(LP_OX)); dasherint iOY(GetLongParameter(LP_OY)); // Calculate what the extremes of the viewport will be when the // point under the cursor is at the cross-hair. This is where // we want to be in iSteps updates dasherint y1(Y - (Y2 * X) / (2 * iOX)); dasherint y2(Y + (Y2 * X) / (2 * iOY)); // iSteps is the number of update steps we need to get the point // under the cursor over to the cross hair. Calculated in order to // keep a constant bit-rate. DASHER_ASSERT(iSteps > 0); // Calculate the new values of y1 and y2 required to perform a single update // step. dasherint newy1, newy2, denom; denom = Y2 + (iSteps - 1) * (y2 - y1); newy1 = y1 * Y2 / denom; newy2 = ((y2 * iSteps - y1 * (iSteps - 1)) * Y2) / denom; y1 = newy1; y2 = newy2; // Calculate the minimum size of the viewport corresponding to the // maximum zoom. dasherint iMinSize(MinSize(Y2, dFactor)); if((y2 - y1) < iMinSize) { newy1 = y1 * (Y2 - iMinSize) / (Y2 - (y2 - y1)); newy2 = newy1 + iMinSize; y1 = newy1; y2 = newy2; } // If |(0,Y2)| = |(y1,y2)|, the "zoom factor" is 1, so we just translate. if (Y2 == y2 - y1) { r1 = R1 - y1; r2 = R2 - y1; return; } // There is a point C on the y-axis such the ratios (y1-C):(Y1-C) and // (y2-C):(Y2-C) are equal. (Obvious when drawn on separate parallel axes.) const dasherint C = (y1 * Y2) / (y1 + Y2 - y2); r1 = ((R1 - C) * Y2) / (y2 - y1) + C; r2 = ((R2 - C) * Y2) / (y2 - y1) + C; } bool CDasherModel::NextScheduledStep(unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB *pAdded, int *pNumDeleted) { DASHER_ASSERT (!GetBoolParameter(BP_DASHER_PAUSED) || m_deGotoQueue.size()==0); if (m_deGotoQueue.size() == 0) return false; myint iNewMin, iNewMax; iNewMin = m_deGotoQueue.front().iN1; iNewMax = m_deGotoQueue.front().iN2; m_deGotoQueue.pop_front(); UpdateBounds(iNewMin, iNewMax, iTime, pAdded, pNumDeleted); if (m_deGotoQueue.size() == 0) SetBoolParameter(BP_DASHER_PAUSED, true); return true; } void CDasherModel::OneStepTowards(myint miMousex, myint miMousey, unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { DASHER_ASSERT(!GetBoolParameter(BP_DASHER_PAUSED)); myint iNewMin, iNewMax; // works out next viewpoint Get_new_root_coords(miMousex, miMousey, iNewMin, iNewMax, iTime); UpdateBounds(iNewMin, iNewMax, iTime, pAdded, pNumDeleted); } void CDasherModel::UpdateBounds(myint iNewMin, myint iNewMax, unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { m_dTotalNats += log((iNewMax - iNewMin) / static_cast<double>(m_Rootmax - m_Rootmin)); // Now actually zoom to the new location NewGoTo(iNewMin, iNewMax, pAdded, pNumDeleted); // Check whether new nodes need to be created ExpandNode(Get_node_under_crosshair()); // This'll get done again when we render the frame, later, but we use NF_SEEN // (set here) to ensure the node under the cursor can never be collapsed // (even when the node budget is exceeded) when we do the rendering... HandleOutput(pAdded, pNumDeleted); } void CDasherModel::RecordFrame(unsigned long Time) { CFrameRate::RecordFrame(Time); ///GAME MODE TEMP///Pass new frame events onto our teacher GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher(); if(m_bGameMode && pTeacher) pTeacher->NewFrame(Time); } void CDasherModel::RecursiveOutput(CDasherNode *pNode, Dasher::VECTOR_SYMBOL_PROB* pAdded) { if(pNode->Parent()) { if (!pNode->Parent()->GetFlag(NF_SEEN)) RecursiveOutput(pNode->Parent(), pAdded); pNode->Parent()->Leave(); } pNode->Enter(); m_pLastOutput = pNode; pNode->SetFlag(NF_SEEN, true); pNode->Output(pAdded, GetLongParameter(LP_NORMALIZATION)); // If the node we are outputting is the last one in a game target sentence, then // notify the game mode teacher. if(m_bGameMode) if(pNode->GetFlag(NF_END_GAME)) GameMode::CDasherGameMode::GetTeacher()->SentenceFinished(); } void CDasherModel::NewGoTo(myint newRootmin, myint newRootmax, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { // Update the max and min of the root node to make iTargetMin and // iTargetMax the edges of the viewport. if(newRootmin + m_iDisplayOffset > (myint)GetLongParameter(LP_MAX_Y) / 2 - 1) newRootmin = (myint)GetLongParameter(LP_MAX_Y) / 2 - 1 - m_iDisplayOffset; if(newRootmax + m_iDisplayOffset < (myint)GetLongParameter(LP_MAX_Y) / 2 + 1) newRootmax = (myint)GetLongParameter(LP_MAX_Y) / 2 + 1 - m_iDisplayOffset; // Check that we haven't drifted too far. The rule is that we're not // allowed to let the root max and min cross the midpoint of the // screen. if(newRootmax < m_Rootmax_max && newRootmin > m_Rootmin_min) { // Only update if we're not making things big enough to risk // overflow. (Otherwise, forcibly choose a new root node, below) if ((newRootmax - newRootmin) > (myint)GetLongParameter(LP_MAX_Y) / 4) { // Also don't allow the update if it will result in making the // root too small. We should have re-generated a deeper root // before now already, but the original root is an exception. m_Rootmax = newRootmax; m_Rootmin = newRootmin; } //else, we just stop - this prevents the user from zooming too far back //outside the root node (when we can't generate an older root). m_iDisplayOffset = (m_iDisplayOffset * 90) / 100; } else { // can't make existing root any bigger because of overflow. So force a new root // to be chosen (so that Dasher doesn't just stop!)... //pick _child_ covering crosshair... const myint iWidth(m_Rootmax-m_Rootmin); for (CDasherNode::ChildMap::const_iterator it = m_Root->GetChildren().begin(), E = m_Root->GetChildren().end(); it!=E; it++) { CDasherNode *pChild(*it); DASHER_ASSERT(m_Rootmin + ((pChild->Lbnd() * iWidth) / GetLongParameter(LP_NORMALIZATION)) <= GetLongParameter(LP_OY)); if (m_Rootmin + ((pChild->Hbnd() * iWidth) / GetLongParameter(LP_NORMALIZATION)) > GetLongParameter(LP_OY)) { //proceed only if new root is on the game path. If the user's strayed // that far off the game path, having Dasher stop seems reasonable! if (!m_bGameMode || !pChild->GetFlag(NF_GAME)) { //make pChild the root node...but put (newRootmin,newRootmax) somewhere there'll be converted: SGotoItem temp; temp.iN1 = newRootmin; temp.iN2 = newRootmax; m_deGotoQueue.push_back(temp); m_Root->DeleteNephews(pChild); RecursiveMakeRoot(pChild); temp=m_deGotoQueue.back(); m_deGotoQueue.pop_back(); // std::cout << "NewGoto Recursing - was (" << newRootmin << "," << newRootmax << "), now (" << temp.iN1 << "," << temp.iN2 << ")" << std::endl; NewGoTo(temp.iN1, temp.iN2, pAdded,pNumDeleted); } return; } } DASHER_ASSERT(false); //did not find a child covering crosshair...?! } } void CDasherModel::HandleOutput(Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { CDasherNode *pNewNode = Get_node_under_crosshair(); DASHER_ASSERT(pNewNode != NULL); // std::cout << "HandleOutput: " << m_pLastOutput << " => " << pNewNode << std::endl; CDasherNode *pLastSeen = pNewNode; while (pLastSeen && !pLastSeen->GetFlag(NF_SEEN)) pLastSeen = pLastSeen->Parent(); while (m_pLastOutput != pLastSeen) { - m_pLastOutput->Undo(); + m_pLastOutput->Undo(pNumDeleted); m_pLastOutput->Leave(); //Should we? I think so, but the old code didn't...? m_pLastOutput->SetFlag(NF_SEEN, false); - // TODO: Is this the right place to trap output? - if(pNumDeleted != NULL) - (*pNumDeleted) += m_pLastOutput->m_iNumSymbols; m_pLastOutput = m_pLastOutput->Parent(); if (m_pLastOutput) m_pLastOutput->Enter(); } if(!pNewNode->GetFlag(NF_SEEN)) { RecursiveOutput(pNewNode, pAdded); } } void CDasherModel::ExpandNode(CDasherNode *pNode) { DASHER_ASSERT(pNode != NULL); // TODO: Is NF_ALLCHILDREN any more useful/efficient than reading the map size? if(pNode->GetFlag(NF_ALLCHILDREN)) { DASHER_ASSERT(pNode->GetChildren().size() > 0); return; } // TODO: Do we really need to delete all of the children at this point? pNode->Delete_children(); // trial commented out - pconlon #ifdef DEBUG unsigned int iExpect = pNode->ExpectedNumChildren(); #endif pNode->PopulateChildren(); #ifdef DEBUG if (iExpect != pNode->GetChildren().size()) { std::cout << "(Note: expected " << iExpect << " children, actually created " << pNode->GetChildren().size() << ")" << std::endl; } #endif pNode->SetFlag(NF_ALLCHILDREN, true); // We get here if all our children (groups) and grandchildren (symbols) are created. // So lets find the correct letters. ///GAME MODE TEMP/////////// // If we are in GameMode, then we do a bit of cooperation with the teacher object when we create // new children. GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher(); if(m_bGameMode && pNode->GetFlag(NF_GAME) && pTeacher ) { std::string strTargetUtf8Char(pTeacher->GetSymbolAtOffset(pNode->m_iOffset + 1)); // Check if this is the last node in the sentence... if(strTargetUtf8Char == "GameEnd") pNode->SetFlag(NF_END_GAME, true); else if (!pNode->GameSearchChildren(strTargetUtf8Char)) { // Target character not found - not in our current alphabet?!?! // Let's give up! pNode->SetFlag(NF_END_GAME, true); } } //////////////////////////// } bool CDasherModel::RenderToView(CDasherView *pView, CExpansionPolicy &policy) { DASHER_ASSERT(pView != NULL); DASHER_ASSERT(m_Root != NULL); // XXX we HandleOutput in RenderToView // DASHER_ASSERT(Get_node_under_crosshair() == m_pLastOutput); bool bReturnValue = false; // The Render routine will fill iGameTargetY with the Dasher Coordinate of the // youngest node with NF_GAME set. The model is responsible for setting NF_GAME on // the appropriate Nodes. pView->Render(m_Root, m_Rootmin + m_iDisplayOffset, m_Rootmax + m_iDisplayOffset, policy, true); /////////GAME MODE TEMP////////////// if(m_bGameMode) if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) { //ACL 27/10/09 I note the following vector: std::vector<std::pair<myint,bool> > vGameTargetY; //was declared earlier and passed to pView->Render, above; but pView->Render //would never do _anything_ to it. Hence the below seems a bit redundant too, //but leaving around for now as a reminder that Game Mode generally is a TODO. pTeacher->SetTargetY(vGameTargetY); } ////////////////////////////////////// // TODO: Fix up stats // TODO: Is this the right way to handle this? HandleOutput(NULL, NULL); //ACL Off-screen nodes (zero collapse cost) will have been collapsed already. //Hence, this acts to maintain the node budget....or whatever the queue's policy is! if (policy.apply(m_pNodeCreationManager,this)) bReturnValue=true; return bReturnValue; } bool CDasherModel::CheckForNewRoot(CDasherView *pView) { DASHER_ASSERT(m_Root != NULL); // TODO: pView is redundant here #ifdef DEBUG CDasherNode *pOldNode = Get_node_under_crosshair(); #endif CDasherNode *root(m_Root); if(!(m_Root->GetFlag(NF_SUPER))) { Reparent_root(); return(m_Root != root); } CDasherNode *pNewRoot = NULL; for (CDasherNode::ChildMap::const_iterator it = m_Root->GetChildren().begin(); it != m_Root->GetChildren().end(); it++) { if ((*it)->GetFlag(NF_SUPER)) { //at most one child should have NF_SUPER set... DASHER_ASSERT(pNewRoot == NULL); pNewRoot = *it; #ifndef DEBUG break; #endif } } ////GAME MODE TEMP - only change the root if it is on the game path///////// if (pNewRoot && (!m_bGameMode || pNewRoot->GetFlag(NF_GAME))) { m_Root->DeleteNephews(pNewRoot); RecursiveMakeRoot(pNewRoot); } DASHER_ASSERT(Get_node_under_crosshair() == pOldNode); return false; } void CDasherModel::ScheduleZoom(long time, dasherint X, dasherint Y, int iMaxZoom) { // 1 = min, 2 = max. y1, y2 is the length we select from Y1, Y2. With // that ratio we calculate the new root{min,max} r1, r2 from current R1, R2. const int nsteps = GetLongParameter(LP_ZOOMSTEPS); const int safety = GetLongParameter(LP_S); // over safety_denom gives % const int safety_denom = 1024; const int ymax = GetLongParameter(LP_MAX_Y); const int scale = ymax; // (0,1) -> (ymin=0,ymax) // (X,Y) is mouse position in dasher coordinates // Prevent clicking too far to the right => y1 <> y2 see below if (X < 2) X = 2; // Lines with gradient +/- 1 passing through (X,Y) intersect y-axis at dasherint y1 = Y - X; // y = x + (Y - X) dasherint y2 = Y + X; // y = -x + (Y + X) // Rename for readability. const dasherint Y1 = 0; const dasherint Y2 = ymax; const dasherint R1 = m_Rootmin; const dasherint R2 = m_Rootmax; // So, want to zoom (y1 - safety/2, y2 + safety/2) -> (Y1, Y2) // Adjust y1, y2 for safety margin dasherint ds = (safety * scale) / (2 * safety_denom); y1 -= ds; y2 += ds; dasherint C, r1, r2; // If |(y1,y2)| = |(Y1,Y2)|, the "zoom factor" is 1, so we just translate. // y2 - y1 == Y2 - Y1 => y1 - Y1 == y2 - Y2 C = y1 - Y1; if (C == y2 - Y2) { r1 = R1 + C; r2 = R2 + C; } else { // There is a point C on the y-axis such the ratios (y1-C):(Y1-C) and // (y2-C):(Y2-C) are equal. (Obvious when drawn on separate parallel axes.) C = (y1 * Y2 - y2 * Y1) / (y1 + Y2 - y2 - Y1); // So another point r's zoomed y coordinate R, has the same ratio (r-C):(R-C) if (y1 != C) { r1 = ((R1 - C) * (Y1 - C)) / (y1 - C) + C; r2 = ((R2 - C) * (Y1 - C)) / (y1 - C) + C; } else if (y2 != C) { r1 = ((R1 - C) * (Y2 - C)) / (y2 - C) + C; r2 = ((R2 - C) * (Y2 - C)) / (y2 - C) + C; } else { // implies y1 = y2 std::cerr << "Impossible geometry in CDasherModel::ScheduleZoom\n"; } // iMaxZoom seems to be in tenths if (iMaxZoom != 0 && 10 * (r2 - r1) > iMaxZoom * (R2 - R1)) { r1 = ((R1 - C) * iMaxZoom) / 10 + C; r2 = ((R2 - C) * iMaxZoom) / 10 + C; } } // sNewItem seems to contain a list of root{min,max} for the frames of the // zoom, so split r -> R into n steps, with accurate R m_deGotoQueue.clear(); for (int s = nsteps - 1; s >= 0; --s) { SGotoItem sNewItem; sNewItem.iN1 = r1 - (s * (r1 - R1)) / nsteps; sNewItem.iN2 = r2 - (s * (r2 - R2)) / nsteps; m_deGotoQueue.push_back(sNewItem); } //steps having been scheduled, we're gonna start moving accordingly... m_pDasherInterface->Unpause(time); } void CDasherModel::ClearScheduledSteps() { m_deGotoQueue.clear(); } void CDasherModel::Offset(int iOffset) { m_Rootmin += iOffset; m_Rootmax += iOffset; if (GetBoolParameter(BP_SMOOTH_OFFSET)) m_iDisplayOffset -= iOffset; } void CDasherModel::AbortOffset() { m_Rootmin += m_iDisplayOffset; m_Rootmax += m_iDisplayOffset; m_iDisplayOffset = 0; } void CDasherModel::LimitRoot(int iMaxWidth) { m_Rootmin = GetLongParameter(LP_MAX_Y) / 2 - iMaxWidth / 2; m_Rootmax = GetLongParameter(LP_MAX_Y) / 2 + iMaxWidth / 2; } void CDasherModel::SetOffset(int iLocation, CDasherView *pView) { if(iLocation == m_iOffset) return; // We're already there // std::cout << "Initialising at offset: " << iLocation << std::endl; // TODO: Special cases, ie this can be done without rebuilding the // model m_iOffset = iLocation; // Now actually rebuild the model InitialiseAtOffset(iLocation, pView); } void CDasherModel::SetControlOffset(int iOffset) { // This is a hack, making many dubious assumptions which happen to // work right now. CDasherNode *pNode = Get_node_under_crosshair(); pNode->SetControlOffset(iOffset); } diff --git a/Src/DasherCore/DasherNode.cpp b/Src/DasherCore/DasherNode.cpp index 229f529..ab5ed2f 100644 --- a/Src/DasherCore/DasherNode.cpp +++ b/Src/DasherCore/DasherNode.cpp @@ -1,213 +1,212 @@ // DasherNode.cpp // // Copyright (c) 2007 David Ward // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" // #include "AlphabetManager.h" - doesnt seem to be required - pconlon #include "DasherInterfaceBase.h" using namespace Dasher; using namespace Opts; using namespace std; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif static int iNumNodes = 0; int Dasher::currentNumNodeObjects() {return iNumNodes;} //TODO this used to be inline - should we make it so again? CDasherNode::CDasherNode(CDasherNode *pParent, unsigned int iLbnd, unsigned int iHbnd, SDisplayInfo *pDisplayInfo) { // TODO: Check that these are disabled for debug builds, and that we're not shipping such a build DASHER_ASSERT(iHbnd >= iLbnd); DASHER_ASSERT(pDisplayInfo != NULL); m_pParent = pParent; if (pParent) { DASHER_ASSERT(!pParent->GetFlag(NF_ALLCHILDREN)); pParent->Children().push_back(this); } m_iLbnd = iLbnd; m_iHbnd = iHbnd; m_pDisplayInfo = pDisplayInfo; onlyChildRendered = NULL; // Default flags (make a definition somewhere, pass flags to constructor?) m_iFlags = 0; m_iRefCount = 0; - m_iNumSymbols = 0; iNumNodes++; } // TODO: put this back to being inlined CDasherNode::~CDasherNode() { // std::cout << "Deleting node: " << this << std::endl; // Release any storage that the node manager has allocated, // unreference ref counted stuff etc. Delete_children(); // std::cout << "done." << std::endl; delete m_pDisplayInfo; iNumNodes--; } void CDasherNode::Trace() const { /* TODO sort out dchar out[256]; if (m_Symbol) wsprintf(out,TEXT("%7x %3c %7x %5d %7x %5d %8x %8x \n"),this,m_Symbol,m_iGroup,m_context,m_Children,m_Cscheme,m_iLbnd,m_iHbnd); else wsprintf(out,TEXT("%7x %7x %5d %7x %5d %8x %8x \n"),this,m_iGroup,m_context,m_Children,m_Cscheme,m_iLbnd,m_iHbnd); OutputDebugString(out); if (m_Children) { unsigned int i; for (i=1;i<m_iChars;i++) m_Children[i]->Dump_node(); } */ } void CDasherNode::GetContext(CDasherInterfaceBase *pInterface, vector<symbol> &vContextSymbols, int iOffset, int iLength) { if (!GetFlag(NF_SEEN)) { DASHER_ASSERT(m_pParent); if (m_pParent) m_pParent->GetContext(pInterface, vContextSymbols, iOffset,iLength); } else { std::string strContext = pInterface->GetContext(iOffset, iLength); pInterface->GetAlphabet()->GetSymbols(vContextSymbols, strContext); } } CDasherNode *const CDasherNode::Get_node_under(int iNormalization, myint miY1, myint miY2, myint miMousex, myint miMousey) { myint miRange = miY2 - miY1; ChildMap::const_iterator i; for(i = GetChildren().begin(); i != GetChildren().end(); i++) { CDasherNode *pChild = *i; myint miNewy1 = miY1 + (miRange * pChild->m_iLbnd) / iNormalization; myint miNewy2 = miY1 + (miRange * pChild->m_iHbnd) / iNormalization; if(miMousey < miNewy2 && miMousey > miNewy1 && miMousex < miNewy2 - miNewy1) return pChild->Get_node_under(iNormalization, miNewy1, miNewy2, miMousex, miMousey); } return this; } // kill ourselves and all other children except for the specified // child // FIXME this probably shouldn't be called after history stuff is working void CDasherNode::OrphanChild(CDasherNode *pChild) { DASHER_ASSERT(ChildCount() > 0); ChildMap::const_iterator i; for(i = GetChildren().begin(); i != GetChildren().end(); i++) { if((*i) != pChild) { (*i)->Delete_children(); delete (*i); } } pChild->m_pParent=NULL; Children().clear(); SetFlag(NF_ALLCHILDREN, false); } // Delete nephews of the child which has the specified symbol // TODO: Need to allow for subnode void CDasherNode::DeleteNephews(CDasherNode *pChild) { DASHER_ASSERT(Children().size() > 0); ChildMap::iterator i; for(i = Children().begin(); i != Children().end(); i++) { if(*i != pChild) { (*i)->Delete_children(); } } } // TODO: Need to allow for subnodes // TODO: Incorporate into above routine void CDasherNode::Delete_children() { // CAlphabetManager::SAlphabetData *pParentUserData(static_cast<CAlphabetManager::SAlphabetData *>(m_pUserData)); // if((GetDisplayInfo()->strDisplayText)[0] == 'e') // std::cout << "ed: " << this << " " << pParentUserData->iContext << " " << pParentUserData->iOffset << std::endl; // std::cout << "Start: " << this << std::endl; ChildMap::iterator i; for(i = Children().begin(); i != Children().end(); i++) { // std::cout << "CNM: " << (*i)->MgrID() << (*i) << " " << (*i)->Parent() << std::endl; delete (*i); } Children().clear(); // std::cout << "NM: " << MgrID() << std::endl; SetFlag(NF_ALLCHILDREN, false); } void CDasherNode::SetFlag(int iFlag, bool bValue) { if(bValue) m_iFlags = m_iFlags | iFlag; else m_iFlags = m_iFlags & (~iFlag); } void CDasherNode::SetParent(CDasherNode *pNewParent) { DASHER_ASSERT(pNewParent); DASHER_ASSERT(!pNewParent->GetFlag(NF_ALLCHILDREN)); m_pParent = pNewParent; pNewParent->Children().push_back(this); } int CDasherNode::MostProbableChild() { int iMax(0); int iCurrent; for(ChildMap::iterator it(m_mChildren.begin()); it != m_mChildren.end(); ++it) { iCurrent = (*it)->Range(); if(iCurrent > iMax) iMax = iCurrent; } return iMax; } bool CDasherNode::GameSearchChildren(string strTargetUtf8Char) { for (ChildMap::iterator i = Children().begin(); i != Children().end(); i++) { if ((*i)->GameSearchNode(strTargetUtf8Char)) return true; } return false; } diff --git a/Src/DasherCore/DasherNode.h b/Src/DasherCore/DasherNode.h index 0d16529..8aebecb 100644 --- a/Src/DasherCore/DasherNode.h +++ b/Src/DasherCore/DasherNode.h @@ -1,342 +1,339 @@ // DasherNode.h // // Copyright (c) 2007 David Ward // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #ifndef __DasherNode_h__ #define __DasherNode_h__ #include "../Common/Common.h" #include "../Common/NoClones.h" #include "LanguageModelling/LanguageModel.h" #include "DasherTypes.h" #include "NodeManager.h" namespace Dasher { class CDasherNode; class CDasherInterfaceBase; }; #include <deque> #include <iostream> #include <vector> // Node flag constants #define NF_COMMITTED 1 #define NF_SEEN 2 #define NF_CONVERTED 4 #define NF_GAME 8 #define NF_ALLCHILDREN 16 #define NF_SUPER 32 #define NF_END_GAME 64 /// \ingroup Model /// @{ /// @brief A node in the Dasher model /// /// The Dasher node represents a box drawn on the display. This class /// contains the information required to render the node, as well as /// navigation within the model (parents and children /// etc.). Additional information is stored in m_pUserData, which is /// interpreted by the node manager associated with this class. Any /// logic specific to a particular node manager should be stored here. /// /// @todo Encapsulate presentation data in a structure? /// @todo Check that all methods respect the pseudochild attribute class Dasher::CDasherNode:private NoClones { public: /// Display attributes of this node, used for rendering. struct SDisplayInfo { int iColour; bool bShove; bool bVisible; std::string strDisplayText; }; CDasherNode *onlyChildRendered; //cache that only one child was rendered (as it filled the screen) /// Container type for storing children. Note that it's worth /// optimising this as lookup happens a lot typedef std::deque<CDasherNode*> ChildMap; /// @brief Constructor /// /// @param pParent Parent of the new node /// @param iLbnd Lower bound of node within parent /// @param iHbnd Upper bound of node within parent /// @param pDisplayInfo Struct containing information on how to display the node /// CDasherNode(CDasherNode *pParent, unsigned int iLbnd, unsigned int iHbnd, SDisplayInfo *pDisplayInfo); /// @brief Destructor /// virtual ~CDasherNode(); void Trace() const; // diagnostic /// Return display information for this node inline const SDisplayInfo *GetDisplayInfo() const; /// @name Routines for manipulating node status /// @{ /// @brief Set a node flag /// /// Set various flags corresponding to the state of the node. The following flags are defined: /// /// NF_COMMITTED - Node is 'above' the root, so corresponding symbol /// has been added to text box, language model trained etc /// /// NF_SEEN - Node has already been output /// /// NF_CONVERTED - Node has been converted (eg Japanese mode) /// /// NF_GAME - Node is on the path in game mode /// /// NF_ALLCHILDREN - Node has all children (TODO: obsolete?) /// /// NF_SUPER - Node covers entire visible area /// /// NF_END_GAME - Node is the last one of the phrase in game mode /// /// /// @param iFlag The flag to set /// @param bValue The new value of the flag /// virtual void SetFlag(int iFlag, bool bValue); /// @brief Get the value of a flag for this node /// /// @param iFlag The flag to get /// /// @return The current value of the flag /// inline bool GetFlag(int iFlag) const; /// @} /// @name Routines relating to the size of the node /// @{ // Lower and higher bounds, and the range /// @brief Get the lower bound of a node /// /// @return The lower bound /// inline unsigned int Lbnd() const; /// @brief Get the upper bound of a node /// /// @return The upper bound /// inline unsigned int Hbnd() const; /// @brief Get the range of a node (upper - lower bound) /// /// @return The range /// /// @todo Should this be here (trivial arithmethic of existing methods) /// inline unsigned int Range() const; /// @brief Reset the range of a node /// /// @param iLower New lower bound /// @param iUpper New upper bound /// inline void SetRange(unsigned int iLower, unsigned int iUpper); /// @brief Get the size of the most probable child /// /// @return The size /// int MostProbableChild(); /// @} /// @name Routines for manipulating relatives /// @{ inline const ChildMap & GetChildren() const; inline unsigned int ChildCount() const; inline CDasherNode *Parent() const; void SetParent(CDasherNode *pNewParent); // TODO: Should this be here? CDasherNode *const Get_node_under(int, myint y1, myint y2, myint smousex, myint smousey); // find node under given co-ords /// @brief Orphan a child of this node /// /// Deletes all other children, and the node itself /// /// @param pChild The child to keep /// void OrphanChild(CDasherNode * pChild); /// @brief Delete the nephews of a given child /// /// @param pChild The child to keep /// void DeleteNephews(CDasherNode *pChild); /// @brief Delete the children of this node /// /// void Delete_children(); /// @} /// /// Sees if a *child* / descendant of the specified node (not that node itself) /// represents the specified character. If so, set the child & intervening nodes' /// NF_GAME flag, and return true; otherwise, return false. /// bool GameSearchChildren(std::string strTargetUtf8Char); /// @name Management routines (once accessed via NodeManager) /// @{ /// Gets the node manager for this object. Meaning defined by subclasses, /// which should override and refine the return type appropriately; /// the main use is to provide runtime type info to check casting! virtual CNodeManager *mgr() = 0; /// /// Provide children for the supplied node /// virtual void PopulateChildren() = 0; /// The number of children which a call to PopulateChildren can be expected to generate. /// (This is not required to be 100% accurate, but any discrepancies will likely cause /// the node budgetting algorithm to behave sub-optimally) virtual int ExpectedNumChildren() = 0; /// /// Called whenever a node belonging to this manager first /// moves under the crosshair /// virtual void Output(Dasher::VECTOR_SYMBOL_PROB* pAdded, int iNormalization) {}; - virtual void Undo() {}; + virtual void Undo(int *pNumDeleted) {}; virtual void Enter() {}; virtual void Leave() {}; virtual CDasherNode *RebuildParent() { return 0; }; /// /// Get as many symbols of context, up to the _end_ of the specified range, /// as possible from this node and its uncommitted ancestors /// virtual void GetContext(CDasherInterfaceBase *pInterface, std::vector<symbol> &vContextSymbols, int iOffset, int iLength); virtual void SetControlOffset(int iOffset) {}; /// /// See if this node represents the specified alphanumeric character; if so, set it's NF_GAME flag and /// return true; otherwise, return false. /// virtual bool GameSearchNode(std::string strTargetUtf8Char) {return false;} /// Clone the context of the specified node, if it's an alphabet node; /// else return an empty context. (Used by ConversionManager) virtual CLanguageModel::Context CloneAlphContext(CLanguageModel *pLanguageModel) { return pLanguageModel->CreateEmptyContext(); }; virtual symbol GetAlphSymbol() { throw "Hack for pre-MandarinDasher ConversionManager::BuildTree method, needs to access CAlphabetManager-private struct"; } /// @} int m_iOffset; - // A hack, to allow this node to be tied to a particular number of symbols; - int m_iNumSymbols; - private: inline ChildMap &Children(); SDisplayInfo *m_pDisplayInfo; unsigned int m_iLbnd; unsigned int m_iHbnd; // the cumulative lower and upper bound prob relative to parent int m_iRefCount; // reference count if ancestor of (or equal to) root node ChildMap m_mChildren; // pointer to array of children CDasherNode *m_pParent; // pointer to parent // Binary flags representing the state of the node int m_iFlags; }; /// @} namespace Dasher { /// Return the number of CDasherNode objects currently in existence. int currentNumNodeObjects(); } ///////////////////////////////////////////////////////////////////////////// // Inline functions ///////////////////////////////////////////////////////////////////////////// namespace Dasher { inline const CDasherNode::SDisplayInfo *CDasherNode::GetDisplayInfo() const { return m_pDisplayInfo; } inline unsigned int CDasherNode::Lbnd() const { return m_iLbnd; } inline unsigned int CDasherNode::Hbnd() const { return m_iHbnd; } inline unsigned int CDasherNode::Range() const { return m_iHbnd - m_iLbnd; } inline CDasherNode::ChildMap &CDasherNode::Children() { return m_mChildren; } inline const CDasherNode::ChildMap &CDasherNode::GetChildren() const { return m_mChildren; } inline unsigned int CDasherNode::ChildCount() const { return m_mChildren.size(); } inline bool CDasherNode::GetFlag(int iFlag) const { return ((m_iFlags & iFlag) != 0); } inline CDasherNode *CDasherNode::Parent() const { return m_pParent; } inline void CDasherNode::SetRange(unsigned int iLower, unsigned int iUpper) { m_iLbnd = iLower; m_iHbnd = iUpper; } } #endif /* #ifndef __DasherNode_h__ */
rgee/HFOSS-Dasher
d86356169c28256cdccdb01427f3dc93f3e81315
Always Leave() nodes we Enter() - inc. in InitialiseAtOffset & ~CDasherModel
diff --git a/Src/DasherCore/DasherModel.cpp b/Src/DasherCore/DasherModel.cpp index 133f696..7d08ddb 100644 --- a/Src/DasherCore/DasherModel.cpp +++ b/Src/DasherCore/DasherModel.cpp @@ -1,798 +1,799 @@ // DasherModel.cpp // // Copyright (c) 2008 The Dasher Team // // This file is part of Dasher. // // Dasher is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // Dasher is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with Dasher; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #include "../Common/Common.h" #include <iostream> #include <cstring> #include "../Common/Random.h" #include "DasherModel.h" #include "DasherView.h" #include "Parameters.h" #include "Event.h" #include "DasherInterfaceBase.h" #include "NodeCreationManager.h" #include "DasherGameMode.h" #include "AlphabetManager.h" using namespace Dasher; using namespace std; // Track memory leaks on Windows to the line that new'd the memory #ifdef _WIN32 #ifdef _DEBUG_MEMLEAKS #define DEBUG_NEW new( _NORMAL_BLOCK, THIS_FILE, __LINE__ ) #define new DEBUG_NEW #undef THIS_FILE static char THIS_FILE[] = __FILE__; #endif #endif // FIXME - need to get node deletion working properly and implement reference counting // CDasherModel CDasherModel::CDasherModel(CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CNodeCreationManager *pNCManager, CDasherInterfaceBase *pDasherInterface, CDasherView *pView, int iOffset) : CFrameRate(pEventHandler, pSettingsStore) { m_pNodeCreationManager = pNCManager; m_pDasherInterface = pDasherInterface; m_bGameMode = GetBoolParameter(BP_GAME_MODE); m_iOffset = iOffset; // TODO: Set through build routine DASHER_ASSERT(m_pNodeCreationManager != NULL); DASHER_ASSERT(m_pDasherInterface != NULL); - m_Root = NULL; + m_pLastOutput = m_Root = NULL; m_Rootmin = 0; m_Rootmax = 0; m_iDisplayOffset = 0; m_dTotalNats = 0.0; // TODO: Need to rationalise the require conversion methods #ifdef JAPANESE m_bRequireConversion = true; #else m_bRequireConversion = false; #endif SetBoolParameter(BP_CONVERSION_MODE, m_bRequireConversion); m_dAddProb = 0.003; int iNormalization = GetLongParameter(LP_NORMALIZATION); m_Rootmin_min = int64_min / iNormalization / 2; m_Rootmax_max = int64_max / iNormalization / 2; InitialiseAtOffset(iOffset, pView); } CDasherModel::~CDasherModel() { + if (m_pLastOutput) m_pLastOutput->Leave(); + if(oldroots.size() > 0) { delete oldroots[0]; oldroots.clear(); // At this point we have also deleted the root - so better NULL pointer m_Root = NULL; - } - - if(m_Root) { + } else { delete m_Root; m_Root = NULL; } } void CDasherModel::HandleEvent(Dasher::CEvent *pEvent) { CFrameRate::HandleEvent(pEvent); if(pEvent->m_iEventType == EV_PARAM_NOTIFY) { Dasher::CParameterNotificationEvent * pEvt(static_cast < Dasher::CParameterNotificationEvent * >(pEvent)); switch (pEvt->m_iParameter) { case BP_CONTROL_MODE: // Rebuild the model if control mode is switched on/off RebuildAroundCrosshair(); break; case BP_SMOOTH_OFFSET: if (!GetBoolParameter(BP_SMOOTH_OFFSET)) //smoothing has just been turned off. End any transition/jump currently // in progress at it's current point AbortOffset(); break; case BP_DASHER_PAUSED: if(GetBoolParameter(BP_SLOW_START)) TriggerSlowdown(); //else, leave m_iStartTime as is - will result in no slow start break; case BP_GAME_MODE: m_bGameMode = GetBoolParameter(BP_GAME_MODE); // Maybe reload something here to begin game mode? break; default: break; } } else if(pEvent->m_iEventType == EV_EDIT) { // Keep track of where we are in the buffer CEditEvent *pEditEvent(static_cast < CEditEvent * >(pEvent)); if(pEditEvent->m_iEditType == 1) { m_iOffset += pEditEvent->m_sText.size(); } else if(pEditEvent->m_iEditType == 2) { m_iOffset -= pEditEvent->m_sText.size(); } } } void CDasherModel::Make_root(CDasherNode *pNewRoot) { // std::cout << "Make root" << std::endl; DASHER_ASSERT(pNewRoot != NULL); DASHER_ASSERT(pNewRoot->Parent() == m_Root); m_Root->SetFlag(NF_COMMITTED, true); // TODO: Is the stack necessary at all? We may as well just keep the // existing data structure? oldroots.push_back(m_Root); // TODO: tidy up conditional while((oldroots.size() > 10) && (!m_bRequireConversion || (oldroots[0]->GetFlag(NF_CONVERTED)))) { oldroots[0]->OrphanChild(oldroots[1]); delete oldroots[0]; oldroots.pop_front(); } m_Root = pNewRoot; // Update the root coordinates, as well as any currently scheduled locations const myint range = m_Rootmax - m_Rootmin; m_Rootmax = m_Rootmin + (range * m_Root->Hbnd()) / GetLongParameter(LP_NORMALIZATION); m_Rootmin = m_Rootmin + (range * m_Root->Lbnd()) / GetLongParameter(LP_NORMALIZATION); for(std::deque<SGotoItem>::iterator it(m_deGotoQueue.begin()); it != m_deGotoQueue.end(); ++it) { const myint r = it->iN2 - it->iN1; it->iN2 = it->iN1 + (r * m_Root->Hbnd()) / GetLongParameter(LP_NORMALIZATION); it->iN1 = it->iN1 + (r * m_Root->Lbnd()) / GetLongParameter(LP_NORMALIZATION); } } void CDasherModel::RecursiveMakeRoot(CDasherNode *pNewRoot) { DASHER_ASSERT(pNewRoot != NULL); DASHER_ASSERT(m_Root != NULL); if(pNewRoot == m_Root) return; // TODO: we really ought to check that pNewRoot is actually a // descendent of the root, although that should be guaranteed if(pNewRoot->Parent() != m_Root) RecursiveMakeRoot(pNewRoot->Parent()); Make_root(pNewRoot); } // only used when BP_CONTROL changes, so not very often. void CDasherModel::RebuildAroundCrosshair() { CDasherNode *pNode = Get_node_under_crosshair(); DASHER_ASSERT(pNode != NULL); DASHER_ASSERT(pNode == m_pLastOutput); RecursiveMakeRoot(pNode); DASHER_ASSERT(m_Root == pNode); ClearRootQueue(); m_Root->Delete_children(); m_Root->PopulateChildren(); } void CDasherModel::Reparent_root() { DASHER_ASSERT(m_Root != NULL); // Change the root node to the parent of the existing node. We need // to recalculate the coordinates for the "new" root as the user may // have moved around within the current root CDasherNode *pNewRoot; if(oldroots.size() == 0) { pNewRoot = m_Root->RebuildParent(); // Return if there's no existing parent and no way of recreating one if(pNewRoot == NULL) return; } else { pNewRoot = oldroots.back(); oldroots.pop_back(); } pNewRoot->SetFlag(NF_COMMITTED, false); DASHER_ASSERT(m_Root->Parent() == pNewRoot); const myint lower(m_Root->Lbnd()), upper(m_Root->Hbnd()); const myint iRange(upper-lower); myint iRootWidth(m_Rootmax - m_Rootmin); // Fail if the new root is bigger than allowed by normalisation if(((myint((GetLongParameter(LP_NORMALIZATION) - upper)) / static_cast<double>(iRange)) > (m_Rootmax_max - m_Rootmax)/static_cast<double>(iRootWidth)) || ((myint(lower) / static_cast<double>(iRange)) > (m_Rootmin - m_Rootmin_min) / static_cast<double>(iRootWidth))) { //but cache the (currently-unusable) root node - else we'll keep recreating (and deleting) it on every frame... oldroots.push_back(pNewRoot); return; } //Update the root coordinates to reflect the new root m_Root = pNewRoot; m_Rootmax = m_Rootmax + ((GetLongParameter(LP_NORMALIZATION) - upper) * iRootWidth) / iRange; m_Rootmin = m_Rootmin - (lower * iRootWidth) / iRange; for(std::deque<SGotoItem>::iterator it(m_deGotoQueue.begin()); it != m_deGotoQueue.end(); ++it) { iRootWidth = it->iN2 - it->iN1; it->iN2 = it->iN2 + (myint((GetLongParameter(LP_NORMALIZATION) - upper)) * iRootWidth / iRange); it->iN1 = it->iN1 - (myint(lower) * iRootWidth / iRange); } } void CDasherModel::ClearRootQueue() { while(oldroots.size() > 0) { if(oldroots.size() > 1) { oldroots[0]->OrphanChild(oldroots[1]); } else { oldroots[0]->OrphanChild(m_Root); } delete oldroots[0]; oldroots.pop_front(); } } CDasherNode *CDasherModel::Get_node_under_crosshair() { DASHER_ASSERT(m_Root != NULL); return m_Root->Get_node_under(GetLongParameter(LP_NORMALIZATION), m_Rootmin + m_iDisplayOffset, m_Rootmax + m_iDisplayOffset, GetLongParameter(LP_OX), GetLongParameter(LP_OY)); } void CDasherModel::DeleteTree() { ClearRootQueue(); delete m_Root; m_Root = NULL; } void CDasherModel::InitialiseAtOffset(int iOffset, CDasherView *pView) { + if (m_pLastOutput) m_pLastOutput->Leave(); DeleteTree(); m_Root = m_pNodeCreationManager->GetAlphRoot(NULL, 0,GetLongParameter(LP_NORMALIZATION), iOffset!=0, iOffset); m_pLastOutput = (m_Root->GetFlag(NF_SEEN)) ? m_Root : NULL; // Create children of the root... ExpandNode(m_Root); // Set the root coordinates so that the root node is an appropriate // size and we're not in any of the children double dFraction( 1 - (1 - m_Root->MostProbableChild() / static_cast<double>(GetLongParameter(LP_NORMALIZATION))) / 2.0 ); int iWidth( static_cast<int>( (GetLongParameter(LP_MAX_Y) / (2.0*dFraction)) ) ); m_Rootmin = GetLongParameter(LP_MAX_Y) / 2 - iWidth / 2; m_Rootmax = GetLongParameter(LP_MAX_Y) / 2 + iWidth / 2; m_iDisplayOffset = 0; //now (re)create parents, while they show on the screen if(pView) { while(pView->IsNodeVisible(m_Rootmin,m_Rootmax)) { CDasherNode *pOldRoot = m_Root; Reparent_root(); if(m_Root == pOldRoot) break; } } // TODO: See if this is better positioned elsewhere m_pDasherInterface->ScheduleRedraw(); } void CDasherModel::Get_new_root_coords(dasherint X, dasherint Y, dasherint &r1, dasherint &r2, unsigned long iTime) { DASHER_ASSERT(m_Root != NULL); if(m_iStartTime == 0) m_iStartTime = iTime; int iSteps = Steps(); double dFactor; if(GetBoolParameter(BP_SLOW_START) && ((iTime - m_iStartTime) < GetLongParameter(LP_SLOW_START_TIME))) dFactor = 0.1 * (1 + 9 * ((iTime - m_iStartTime) / static_cast<double>(GetLongParameter(LP_SLOW_START_TIME)))); else dFactor = 1.0; iSteps = static_cast<int>(iSteps / dFactor); // Avoid X == 0, as this corresponds to infinite zoom if (X <= 0) X = 1; // If X is too large we risk overflow errors, so limit it dasherint iMaxX = (1 << 29) / iSteps; if (X > iMaxX) X = iMaxX; // Mouse coords X, Y // new root{min,max} r1,r2, old root{min,max} R1,R2 const dasherint R1 = m_Rootmin; const dasherint R2 = m_Rootmax; // const dasherint Y1 = 0; dasherint Y2(GetLongParameter(LP_MAX_Y)); dasherint iOX(GetLongParameter(LP_OX)); dasherint iOY(GetLongParameter(LP_OY)); // Calculate what the extremes of the viewport will be when the // point under the cursor is at the cross-hair. This is where // we want to be in iSteps updates dasherint y1(Y - (Y2 * X) / (2 * iOX)); dasherint y2(Y + (Y2 * X) / (2 * iOY)); // iSteps is the number of update steps we need to get the point // under the cursor over to the cross hair. Calculated in order to // keep a constant bit-rate. DASHER_ASSERT(iSteps > 0); // Calculate the new values of y1 and y2 required to perform a single update // step. dasherint newy1, newy2, denom; denom = Y2 + (iSteps - 1) * (y2 - y1); newy1 = y1 * Y2 / denom; newy2 = ((y2 * iSteps - y1 * (iSteps - 1)) * Y2) / denom; y1 = newy1; y2 = newy2; // Calculate the minimum size of the viewport corresponding to the // maximum zoom. dasherint iMinSize(MinSize(Y2, dFactor)); if((y2 - y1) < iMinSize) { newy1 = y1 * (Y2 - iMinSize) / (Y2 - (y2 - y1)); newy2 = newy1 + iMinSize; y1 = newy1; y2 = newy2; } // If |(0,Y2)| = |(y1,y2)|, the "zoom factor" is 1, so we just translate. if (Y2 == y2 - y1) { r1 = R1 - y1; r2 = R2 - y1; return; } // There is a point C on the y-axis such the ratios (y1-C):(Y1-C) and // (y2-C):(Y2-C) are equal. (Obvious when drawn on separate parallel axes.) const dasherint C = (y1 * Y2) / (y1 + Y2 - y2); r1 = ((R1 - C) * Y2) / (y2 - y1) + C; r2 = ((R2 - C) * Y2) / (y2 - y1) + C; } bool CDasherModel::NextScheduledStep(unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB *pAdded, int *pNumDeleted) { DASHER_ASSERT (!GetBoolParameter(BP_DASHER_PAUSED) || m_deGotoQueue.size()==0); if (m_deGotoQueue.size() == 0) return false; myint iNewMin, iNewMax; iNewMin = m_deGotoQueue.front().iN1; iNewMax = m_deGotoQueue.front().iN2; m_deGotoQueue.pop_front(); UpdateBounds(iNewMin, iNewMax, iTime, pAdded, pNumDeleted); if (m_deGotoQueue.size() == 0) SetBoolParameter(BP_DASHER_PAUSED, true); return true; } void CDasherModel::OneStepTowards(myint miMousex, myint miMousey, unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { DASHER_ASSERT(!GetBoolParameter(BP_DASHER_PAUSED)); myint iNewMin, iNewMax; // works out next viewpoint Get_new_root_coords(miMousex, miMousey, iNewMin, iNewMax, iTime); UpdateBounds(iNewMin, iNewMax, iTime, pAdded, pNumDeleted); } void CDasherModel::UpdateBounds(myint iNewMin, myint iNewMax, unsigned long iTime, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { m_dTotalNats += log((iNewMax - iNewMin) / static_cast<double>(m_Rootmax - m_Rootmin)); // Now actually zoom to the new location NewGoTo(iNewMin, iNewMax, pAdded, pNumDeleted); // Check whether new nodes need to be created ExpandNode(Get_node_under_crosshair()); // This'll get done again when we render the frame, later, but we use NF_SEEN // (set here) to ensure the node under the cursor can never be collapsed // (even when the node budget is exceeded) when we do the rendering... HandleOutput(pAdded, pNumDeleted); } void CDasherModel::RecordFrame(unsigned long Time) { CFrameRate::RecordFrame(Time); ///GAME MODE TEMP///Pass new frame events onto our teacher GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher(); if(m_bGameMode && pTeacher) pTeacher->NewFrame(Time); } void CDasherModel::RecursiveOutput(CDasherNode *pNode, Dasher::VECTOR_SYMBOL_PROB* pAdded) { if(pNode->Parent()) { if (!pNode->Parent()->GetFlag(NF_SEEN)) RecursiveOutput(pNode->Parent(), pAdded); pNode->Parent()->Leave(); } pNode->Enter(); m_pLastOutput = pNode; pNode->SetFlag(NF_SEEN, true); pNode->Output(pAdded, GetLongParameter(LP_NORMALIZATION)); // If the node we are outputting is the last one in a game target sentence, then // notify the game mode teacher. if(m_bGameMode) if(pNode->GetFlag(NF_END_GAME)) GameMode::CDasherGameMode::GetTeacher()->SentenceFinished(); } void CDasherModel::NewGoTo(myint newRootmin, myint newRootmax, Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { // Update the max and min of the root node to make iTargetMin and // iTargetMax the edges of the viewport. if(newRootmin + m_iDisplayOffset > (myint)GetLongParameter(LP_MAX_Y) / 2 - 1) newRootmin = (myint)GetLongParameter(LP_MAX_Y) / 2 - 1 - m_iDisplayOffset; if(newRootmax + m_iDisplayOffset < (myint)GetLongParameter(LP_MAX_Y) / 2 + 1) newRootmax = (myint)GetLongParameter(LP_MAX_Y) / 2 + 1 - m_iDisplayOffset; // Check that we haven't drifted too far. The rule is that we're not // allowed to let the root max and min cross the midpoint of the // screen. if(newRootmax < m_Rootmax_max && newRootmin > m_Rootmin_min) { // Only update if we're not making things big enough to risk // overflow. (Otherwise, forcibly choose a new root node, below) if ((newRootmax - newRootmin) > (myint)GetLongParameter(LP_MAX_Y) / 4) { // Also don't allow the update if it will result in making the // root too small. We should have re-generated a deeper root // before now already, but the original root is an exception. m_Rootmax = newRootmax; m_Rootmin = newRootmin; } //else, we just stop - this prevents the user from zooming too far back //outside the root node (when we can't generate an older root). m_iDisplayOffset = (m_iDisplayOffset * 90) / 100; } else { // can't make existing root any bigger because of overflow. So force a new root // to be chosen (so that Dasher doesn't just stop!)... //pick _child_ covering crosshair... const myint iWidth(m_Rootmax-m_Rootmin); for (CDasherNode::ChildMap::const_iterator it = m_Root->GetChildren().begin(), E = m_Root->GetChildren().end(); it!=E; it++) { CDasherNode *pChild(*it); DASHER_ASSERT(m_Rootmin + ((pChild->Lbnd() * iWidth) / GetLongParameter(LP_NORMALIZATION)) <= GetLongParameter(LP_OY)); if (m_Rootmin + ((pChild->Hbnd() * iWidth) / GetLongParameter(LP_NORMALIZATION)) > GetLongParameter(LP_OY)) { //proceed only if new root is on the game path. If the user's strayed // that far off the game path, having Dasher stop seems reasonable! if (!m_bGameMode || !pChild->GetFlag(NF_GAME)) { //make pChild the root node...but put (newRootmin,newRootmax) somewhere there'll be converted: SGotoItem temp; temp.iN1 = newRootmin; temp.iN2 = newRootmax; m_deGotoQueue.push_back(temp); m_Root->DeleteNephews(pChild); RecursiveMakeRoot(pChild); temp=m_deGotoQueue.back(); m_deGotoQueue.pop_back(); // std::cout << "NewGoto Recursing - was (" << newRootmin << "," << newRootmax << "), now (" << temp.iN1 << "," << temp.iN2 << ")" << std::endl; NewGoTo(temp.iN1, temp.iN2, pAdded,pNumDeleted); } return; } } DASHER_ASSERT(false); //did not find a child covering crosshair...?! } } void CDasherModel::HandleOutput(Dasher::VECTOR_SYMBOL_PROB* pAdded, int* pNumDeleted) { CDasherNode *pNewNode = Get_node_under_crosshair(); DASHER_ASSERT(pNewNode != NULL); // std::cout << "HandleOutput: " << m_pLastOutput << " => " << pNewNode << std::endl; CDasherNode *pLastSeen = pNewNode; while (pLastSeen && !pLastSeen->GetFlag(NF_SEEN)) pLastSeen = pLastSeen->Parent(); while (m_pLastOutput != pLastSeen) { m_pLastOutput->Undo(); m_pLastOutput->Leave(); //Should we? I think so, but the old code didn't...? m_pLastOutput->SetFlag(NF_SEEN, false); // TODO: Is this the right place to trap output? if(pNumDeleted != NULL) (*pNumDeleted) += m_pLastOutput->m_iNumSymbols; m_pLastOutput = m_pLastOutput->Parent(); if (m_pLastOutput) m_pLastOutput->Enter(); } if(!pNewNode->GetFlag(NF_SEEN)) { RecursiveOutput(pNewNode, pAdded); } } void CDasherModel::ExpandNode(CDasherNode *pNode) { DASHER_ASSERT(pNode != NULL); // TODO: Is NF_ALLCHILDREN any more useful/efficient than reading the map size? if(pNode->GetFlag(NF_ALLCHILDREN)) { DASHER_ASSERT(pNode->GetChildren().size() > 0); return; } // TODO: Do we really need to delete all of the children at this point? pNode->Delete_children(); // trial commented out - pconlon #ifdef DEBUG unsigned int iExpect = pNode->ExpectedNumChildren(); #endif pNode->PopulateChildren(); #ifdef DEBUG if (iExpect != pNode->GetChildren().size()) { std::cout << "(Note: expected " << iExpect << " children, actually created " << pNode->GetChildren().size() << ")" << std::endl; } #endif pNode->SetFlag(NF_ALLCHILDREN, true); // We get here if all our children (groups) and grandchildren (symbols) are created. // So lets find the correct letters. ///GAME MODE TEMP/////////// // If we are in GameMode, then we do a bit of cooperation with the teacher object when we create // new children. GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher(); if(m_bGameMode && pNode->GetFlag(NF_GAME) && pTeacher ) { std::string strTargetUtf8Char(pTeacher->GetSymbolAtOffset(pNode->m_iOffset + 1)); // Check if this is the last node in the sentence... if(strTargetUtf8Char == "GameEnd") pNode->SetFlag(NF_END_GAME, true); else if (!pNode->GameSearchChildren(strTargetUtf8Char)) { // Target character not found - not in our current alphabet?!?! // Let's give up! pNode->SetFlag(NF_END_GAME, true); } } //////////////////////////// } bool CDasherModel::RenderToView(CDasherView *pView, CExpansionPolicy &policy) { DASHER_ASSERT(pView != NULL); DASHER_ASSERT(m_Root != NULL); // XXX we HandleOutput in RenderToView // DASHER_ASSERT(Get_node_under_crosshair() == m_pLastOutput); bool bReturnValue = false; // The Render routine will fill iGameTargetY with the Dasher Coordinate of the // youngest node with NF_GAME set. The model is responsible for setting NF_GAME on // the appropriate Nodes. pView->Render(m_Root, m_Rootmin + m_iDisplayOffset, m_Rootmax + m_iDisplayOffset, policy, true); /////////GAME MODE TEMP////////////// if(m_bGameMode) if(GameMode::CDasherGameMode* pTeacher = GameMode::CDasherGameMode::GetTeacher()) { //ACL 27/10/09 I note the following vector: std::vector<std::pair<myint,bool> > vGameTargetY; //was declared earlier and passed to pView->Render, above; but pView->Render //would never do _anything_ to it. Hence the below seems a bit redundant too, //but leaving around for now as a reminder that Game Mode generally is a TODO. pTeacher->SetTargetY(vGameTargetY); } ////////////////////////////////////// // TODO: Fix up stats // TODO: Is this the right way to handle this? HandleOutput(NULL, NULL); //ACL Off-screen nodes (zero collapse cost) will have been collapsed already. //Hence, this acts to maintain the node budget....or whatever the queue's policy is! if (policy.apply(m_pNodeCreationManager,this)) bReturnValue=true; return bReturnValue; } bool CDasherModel::CheckForNewRoot(CDasherView *pView) { DASHER_ASSERT(m_Root != NULL); // TODO: pView is redundant here #ifdef DEBUG CDasherNode *pOldNode = Get_node_under_crosshair(); #endif CDasherNode *root(m_Root); if(!(m_Root->GetFlag(NF_SUPER))) { Reparent_root(); return(m_Root != root); } CDasherNode *pNewRoot = NULL; for (CDasherNode::ChildMap::const_iterator it = m_Root->GetChildren().begin(); it != m_Root->GetChildren().end(); it++) { if ((*it)->GetFlag(NF_SUPER)) { //at most one child should have NF_SUPER set... DASHER_ASSERT(pNewRoot == NULL); pNewRoot = *it; #ifndef DEBUG break; #endif } } ////GAME MODE TEMP - only change the root if it is on the game path///////// if (pNewRoot && (!m_bGameMode || pNewRoot->GetFlag(NF_GAME))) { m_Root->DeleteNephews(pNewRoot); RecursiveMakeRoot(pNewRoot); } DASHER_ASSERT(Get_node_under_crosshair() == pOldNode); return false; } void CDasherModel::ScheduleZoom(long time, dasherint X, dasherint Y, int iMaxZoom) { // 1 = min, 2 = max. y1, y2 is the length we select from Y1, Y2. With // that ratio we calculate the new root{min,max} r1, r2 from current R1, R2. const int nsteps = GetLongParameter(LP_ZOOMSTEPS); const int safety = GetLongParameter(LP_S); // over safety_denom gives % const int safety_denom = 1024; const int ymax = GetLongParameter(LP_MAX_Y); const int scale = ymax; // (0,1) -> (ymin=0,ymax) // (X,Y) is mouse position in dasher coordinates // Prevent clicking too far to the right => y1 <> y2 see below if (X < 2) X = 2; // Lines with gradient +/- 1 passing through (X,Y) intersect y-axis at dasherint y1 = Y - X; // y = x + (Y - X) dasherint y2 = Y + X; // y = -x + (Y + X) // Rename for readability. const dasherint Y1 = 0; const dasherint Y2 = ymax; const dasherint R1 = m_Rootmin; const dasherint R2 = m_Rootmax; // So, want to zoom (y1 - safety/2, y2 + safety/2) -> (Y1, Y2) // Adjust y1, y2 for safety margin dasherint ds = (safety * scale) / (2 * safety_denom); y1 -= ds; y2 += ds; dasherint C, r1, r2; // If |(y1,y2)| = |(Y1,Y2)|, the "zoom factor" is 1, so we just translate. // y2 - y1 == Y2 - Y1 => y1 - Y1 == y2 - Y2 C = y1 - Y1; if (C == y2 - Y2) { r1 = R1 + C; r2 = R2 + C; } else { // There is a point C on the y-axis such the ratios (y1-C):(Y1-C) and // (y2-C):(Y2-C) are equal. (Obvious when drawn on separate parallel axes.) C = (y1 * Y2 - y2 * Y1) / (y1 + Y2 - y2 - Y1); // So another point r's zoomed y coordinate R, has the same ratio (r-C):(R-C) if (y1 != C) { r1 = ((R1 - C) * (Y1 - C)) / (y1 - C) + C; r2 = ((R2 - C) * (Y1 - C)) / (y1 - C) + C; } else if (y2 != C) { r1 = ((R1 - C) * (Y2 - C)) / (y2 - C) + C; r2 = ((R2 - C) * (Y2 - C)) / (y2 - C) + C; } else { // implies y1 = y2 std::cerr << "Impossible geometry in CDasherModel::ScheduleZoom\n"; } // iMaxZoom seems to be in tenths if (iMaxZoom != 0 && 10 * (r2 - r1) > iMaxZoom * (R2 - R1)) { r1 = ((R1 - C) * iMaxZoom) / 10 + C; r2 = ((R2 - C) * iMaxZoom) / 10 + C; } } // sNewItem seems to contain a list of root{min,max} for the frames of the // zoom, so split r -> R into n steps, with accurate R m_deGotoQueue.clear(); for (int s = nsteps - 1; s >= 0; --s) { SGotoItem sNewItem; sNewItem.iN1 = r1 - (s * (r1 - R1)) / nsteps; sNewItem.iN2 = r2 - (s * (r2 - R2)) / nsteps; m_deGotoQueue.push_back(sNewItem); } //steps having been scheduled, we're gonna start moving accordingly... m_pDasherInterface->Unpause(time); } void CDasherModel::ClearScheduledSteps() { m_deGotoQueue.clear(); } void CDasherModel::Offset(int iOffset) { m_Rootmin += iOffset; m_Rootmax += iOffset; if (GetBoolParameter(BP_SMOOTH_OFFSET)) m_iDisplayOffset -= iOffset; } void CDasherModel::AbortOffset() { m_Rootmin += m_iDisplayOffset; m_Rootmax += m_iDisplayOffset; m_iDisplayOffset = 0; } void CDasherModel::LimitRoot(int iMaxWidth) { m_Rootmin = GetLongParameter(LP_MAX_Y) / 2 - iMaxWidth / 2; m_Rootmax = GetLongParameter(LP_MAX_Y) / 2 + iMaxWidth / 2; } void CDasherModel::SetOffset(int iLocation, CDasherView *pView) { if(iLocation == m_iOffset) return; // We're already there // std::cout << "Initialising at offset: " << iLocation << std::endl; // TODO: Special cases, ie this can be done without rebuilding the // model m_iOffset = iLocation;
rgee/HFOSS-Dasher
b445d26a634632ee1238043f2d6b4ba10190788c
Code tidy to StylusFilter, missed from 13563f987132a61ff53ae36c80054ce32e2e6be8
diff --git a/Src/DasherCore/StylusFilter.cpp b/Src/DasherCore/StylusFilter.cpp index 1232f91..aa83b1a 100644 --- a/Src/DasherCore/StylusFilter.cpp +++ b/Src/DasherCore/StylusFilter.cpp @@ -1,46 +1,42 @@ #include "../Common/Common.h" #include "StylusFilter.h" #include "DasherInterfaceBase.h" #include "Event.h" using namespace Dasher; CStylusFilter::CStylusFilter(Dasher::CEventHandler *pEventHandler, CSettingsStore *pSettingsStore, CDasherInterfaceBase *pInterface, ModuleID_t iID, const char *szName) : CDefaultFilter(pEventHandler, pSettingsStore, pInterface, iID, szName) { } bool CStylusFilter::Timer(int iTime, CDasherView *pView, CDasherModel *pModel, Dasher::VECTOR_SYMBOL_PROB *pAdded, int *pNumDeleted, CExpansionPolicy **pol) { - if (pModel->NextScheduledStep(iTime, pAdded, pNumDeleted)) - return true; - return CDefaultFilter::Timer(iTime, pView, pModel, pAdded, pNumDeleted, pol); - if (GetBoolParameter(BP_DASHER_PAUSED)) - { - //continue any zoom scheduled by a previous click... - return pModel->NextScheduledStep(iTime, pAdded, pNumDeleted); + //First, try to continue any zoom scheduled by a previous click... + if (pModel->NextScheduledStep(iTime, pAdded, pNumDeleted)) { //note that this skips the rest of CDefaultFilter::Timer; //however, given we're paused, this is only the Start Handler, //which we're not using anyway. + return true; } return CDefaultFilter::Timer(iTime, pView, pModel, pAdded, pNumDeleted, pol); } void CStylusFilter::KeyDown(int iTime, int iId, CDasherView *pView, CDasherModel *pModel, CUserLogBase *pUserLog) { if(iId == 100) { pModel->ClearScheduledSteps(); m_pInterface->Unpause(iTime); m_iKeyDownTime = iTime; } } void CStylusFilter::KeyUp(int iTime, int iId, CDasherView *pView, CDasherModel *pModel) { if(iId == 100) { if (iTime - m_iKeyDownTime < GetLongParameter(LP_TAP_TIME)) { myint iDasherX, iDasherY; pView->GetCoordinates(iDasherX, iDasherY); pModel->ScheduleZoom(iTime, iDasherX, iDasherY, GetLongParameter(LP_MAXZOOM)); } else { m_pInterface->Pause(); } } }
rgee/HFOSS-Dasher
578d5f151ef0e705f4d52908e30439c20593aa21
Fix remaining GSEAL_ENABLE issues (#614995). Remove CCanvas' copy of DasherScreen's width and height.
diff --git a/Src/Gtk2/Canvas.cpp b/Src/Gtk2/Canvas.cpp index 65b5dc3..11d4a00 100644 --- a/Src/Gtk2/Canvas.cpp +++ b/Src/Gtk2/Canvas.cpp @@ -1,528 +1,526 @@ #include "../Common/Common.h" #include "Canvas.h" #include "DasherControl.h" #include "../DasherCore/DasherTypes.h" using namespace Dasher; -CCanvas::CCanvas(GtkWidget *pCanvas, CPangoCache *pPangoCache) - : CDasherScreen(pCanvas->allocation.width, pCanvas->allocation.height) { +CCanvas::CCanvas(GtkWidget *pCanvas, CPangoCache *pPangoCache, + screenint iWidth, screenint iHeight) + : CDasherScreen(iWidth, iHeight) { #if WITH_CAIRO cairo_colours = 0; #else colours = 0; #endif m_pCanvas = pCanvas; m_pPangoCache = pPangoCache; - m_iWidth = m_pCanvas->allocation.width; - m_iHeight = m_pCanvas->allocation.height; - // Construct the buffer pixmaps // FIXME - only allocate without cairo #if WITH_CAIRO m_pDisplaySurface = cairo_image_surface_create(CAIRO_FORMAT_RGB24, m_iWidth, m_iHeight); m_pDecorationSurface = cairo_image_surface_create(CAIRO_FORMAT_RGB24, m_iWidth, m_iHeight); //m_pOnscreenSurface = cairo_image_surface_create(CAIRO_FORMAT_RGB24, m_iWidth, m_iHeight); #else //m_pDummyBuffer = gdk_pixmap_new(pCanvas->window, m_iWidth, m_iHeight, -1); m_pDisplayBuffer = gdk_pixmap_new(pCanvas->window, m_iWidth, m_iHeight, -1); m_pDecorationBuffer = gdk_pixmap_new(pCanvas->window, m_iWidth, m_iHeight, -1); //m_pOnscreenBuffer = gdk_pixmap_new(pCanvas->window, m_iWidth, m_iHeight, -1); // Set the display buffer to be current m_pOffscreenBuffer = m_pDisplayBuffer; #endif #if WITH_CAIRO // The lines between origin and pointer is draw here decoration_cr = cairo_create(m_pDecorationSurface); cr = decoration_cr; cairo_set_line_cap(cr, CAIRO_LINE_CAP_SQUARE); cairo_set_line_width(cr, 1.0); // Base stuff are drawn here display_cr = cairo_create(m_pDisplaySurface); cr = display_cr; cairo_set_line_cap(cr, CAIRO_LINE_CAP_SQUARE); cairo_set_line_width(cr, 1.0); //onscreen_cr = cairo_create(m_pOnscreenSurface); #endif m_pPangoInk = new PangoRectangle; gtk_widget_add_events(m_pCanvas, GDK_ALL_EVENTS_MASK); } CCanvas::~CCanvas() { // Free the buffer pixmaps #if WITH_CAIRO cr = NULL; cairo_surface_destroy(m_pDisplaySurface); cairo_surface_destroy(m_pDecorationSurface); //cairo_surface_destroy(m_pOnscreenSurface); cairo_destroy(display_cr); cairo_destroy(decoration_cr); //cairo_destroy(onscreen_cr); #else //g_object_unref(m_pDummyBuffer); g_object_unref(m_pDisplayBuffer); g_object_unref(m_pDecorationBuffer); //g_object_unref(m_pOnscreenBuffer); #endif #if WITH_CAIRO delete[] cairo_colours; #endif delete m_pPangoInk; } void CCanvas::Blank() { // FIXME - this is replicated throughout this file - do something // about that #if WITH_CAIRO #else GdkGC *graphics_context; GdkColormap *colormap; graphics_context = m_pCanvas->style->fg_gc[GTK_WIDGET_STATE(m_pCanvas)]; colormap = gdk_colormap_get_system(); #endif BEGIN_DRAWING; SET_COLOR(0); #if WITH_CAIRO cairo_paint(cr); #else gdk_draw_rectangle(m_pOffscreenBuffer, graphics_context, TRUE, 0, 0, m_iWidth, m_iHeight); #endif END_DRAWING; } void CCanvas::Display() { // FIXME - Some of this stuff is probably not needed // GdkRectangle update_rect; #if WITH_CAIRO #else GdkGC *graphics_context; GdkColormap *colormap; graphics_context = m_pCanvas->style->fg_gc[GTK_WIDGET_STATE(m_pCanvas)]; colormap = gdk_colormap_get_system(); #endif BEGIN_DRAWING; SET_COLOR(0); // Copy the offscreen buffer into the onscreen buffer // TODO: Reimplement (kind of important!) // gdk_draw_drawable(m_pOnscreenBuffer, m_pCanvas->style->fg_gc[GTK_WIDGET_STATE(m_pCanvas)], m_pOffscreenBuffer, 0, 0, 0, 0, m_iWidth, m_iHeight); // BEGIN_DRAWING; // cairo_set_source_surface(onscreen_cr, m_pDecorationSurface, 0, 0); // cairo_rectangle(onscreen_cr, 0, 0, m_iWidth, m_iHeight); // cairo_fill(onscreen_cr); // END_DRAWING; // Blank the offscreen buffer (?) // gdk_draw_rectangle(m_pOffscreenBuffer, graphics_context, TRUE, 0, 0, m_iWidth, m_iHeight); // Invalidate the full canvas to force it to be redrawn on-screen // update_rect.x = 0; // update_rect.y = 0; // update_rect.width = m_iWidth; // update_rect.height = m_iHeight; // gdk_window_invalidate_rect(m_pCanvas->window, &update_rect, FALSE); // BEGIN_DRAWING; // GdkRectangle sRect = {0, 0, m_iWidth, m_iHeight}; // gdk_window_begin_paint_rect(m_pCanvas->window, &sRect); #if WITH_CAIRO cairo_t *widget_cr; #if GTK_CHECK_VERSION (2,14,0) widget_cr = gdk_cairo_create(gtk_widget_get_window(m_pCanvas)); #else widget_cr = gdk_cairo_create(m_pCanvas->window); #endif cairo_set_source_surface(widget_cr, m_pDecorationSurface, 0, 0); cairo_rectangle(widget_cr, 0, 0, m_iWidth, m_iHeight); cairo_fill(widget_cr); cairo_destroy(widget_cr); #else gdk_draw_drawable(m_pCanvas->window, m_pCanvas->style->fg_gc[GTK_WIDGET_STATE(m_pCanvas)], m_pDecorationBuffer, 0, 0, 0, 0, m_iWidth, m_iHeight); #endif // gdk_window_end_paint(m_pCanvas->window); // Restore original graphics context (colours) END_DRAWING; // gtk_main_iteration_do(0); } void CCanvas::DrawRectangle(screenint x1, screenint y1, screenint x2, screenint y2, int Color, int iOutlineColour, Opts::ColorSchemes ColorScheme, int iThickness) { // std::cout << "Raw Rectangle, (" << x1 << ", " << y1 << ") - (" << x2 << ", " << y2 << ")" << std::endl; #if WITH_CAIRO #else GdkGC *graphics_context; GdkColormap *colormap; graphics_context = m_pCanvas->style->fg_gc[GTK_WIDGET_STATE(m_pCanvas)]; colormap = gdk_colormap_get_system(); #endif BEGIN_DRAWING; int iLeft; int iTop; int iWidth; int iHeight; if( x2 > x1 ) { iLeft = x1; iWidth = x2 - x1; } else { iLeft = x2; iWidth = x1 - x2; } if( y2 > y1 ) { iTop = y1; iHeight = y2 - y1; } else { iTop = y2; iHeight = y1 - y2; } // std::cout << bFill << " " << Color << " " << iLeft << " " << iTop << " " << iWidth << " " << iHeight << std::endl; if(Color!=-1) { SET_COLOR(Color); #if WITH_CAIRO //cairo_set_line_width(cr, iThickness); //outline done below cairo_rectangle(cr, iLeft, iTop, iWidth, iHeight); cairo_fill(cr); #else gdk_draw_rectangle(m_pOffscreenBuffer, graphics_context, TRUE, iLeft, iTop, iWidth + 1, iHeight + 1); #endif } if(iThickness>0) { if( iOutlineColour == -1 ) SET_COLOR(3); else SET_COLOR(iOutlineColour); // TODO: There's a known issue here when the start of one box and // the end of the other map to the same pixel. This generally // results in box outlines being truncated. #if WITH_CAIRO cairo_set_line_width(cr, iThickness); cairo_rectangle(cr, iLeft + 0.5, iTop + 0.5, iWidth, iHeight); cairo_stroke(cr); #else gdk_gc_set_line_attributes(graphics_context, iThickness, GDK_LINE_SOLID, GDK_CAP_ROUND, GDK_JOIN_ROUND ); gdk_draw_rectangle(m_pOffscreenBuffer, graphics_context, FALSE, iLeft, iTop, iWidth, iHeight); #endif } END_DRAWING; } void CCanvas::DrawCircle(screenint iCX, screenint iCY, screenint iR, int iColour, int iFillColour, int iThickness, bool bFill) { #if WITH_CAIRO #else if(iThickness == 1) // This is to make it work propely on Windows iThickness = 0; GdkGC *graphics_context; GdkColormap *colormap; graphics_context = m_pCanvas->style->fg_gc[GTK_WIDGET_STATE(m_pCanvas)]; colormap = gdk_colormap_get_system(); #endif BEGIN_DRAWING; if(bFill) { SET_COLOR(iFillColour); #if WITH_CAIRO cairo_arc(cr, iCX, iCY, iR, 0, 2*M_PI); cairo_fill(cr); #else gdk_draw_arc(m_pOffscreenBuffer, graphics_context, true, iCX - iR, iCY - iR, 2*iR, 2*iR, 0, 23040); #endif } SET_COLOR(iColour); #if WITH_CAIRO cairo_set_line_width(cr, iThickness); cairo_arc(cr, iCX, iCY, iR, 0, 2*M_PI); cairo_stroke(cr); #else gdk_gc_set_line_attributes(graphics_context, iThickness, GDK_LINE_SOLID, GDK_CAP_ROUND, GDK_JOIN_ROUND ); gdk_draw_arc(m_pOffscreenBuffer, graphics_context, false, iCX - iR, iCY - iR, 2*iR, 2*iR, 0, 23040); #endif END_DRAWING; } void CCanvas::Polygon(Dasher::CDasherScreen::point *Points, int Number, int fillColour, int outlineColour, int iWidth) { //(ACL) commenting out, we now deal with fill & outline separately. However, // TODO: find a windows box on which this actually applies and test it //if(iWidth == 1) // This is to make it work properly on Windows // iWidth = 0; #if WITH_CAIRO #else GdkGC *graphics_context; GdkColormap *colormap; graphics_context = m_pCanvas->style->fg_gc[GTK_WIDGET_STATE(m_pCanvas)]; colormap = gdk_colormap_get_system(); #endif BEGIN_DRAWING; #if WITH_CAIRO cairo_move_to(cr, Points[0].x, Points[0].y); for (int i=1; i < Number; i++) cairo_line_to(cr, Points[i].x, Points[i].y); cairo_close_path(cr); if (fillColour!=-1) { SET_COLOR(fillColour); if (iWidth<=0) { cairo_fill(cr); //fill only, no outline } else { cairo_fill_preserve(cr); //leave path defined for cairo_stroke, below } } if (iWidth>0) { SET_COLOR(outlineColour==-1 ? 3 : outlineColour); cairo_stroke(cr); } #else GdkPoint *gdk_points; gdk_points = (GdkPoint *) g_malloc(Number * sizeof(GdkPoint)); for(int i = 0; i < Number; i++) { gdk_points[i].x = Points[i].x; gdk_points[i].y = Points[i].y; } if (fillColour != -1) { SET_COLOR(fillColour); gdk_gc_set_line_attributes(graphics_context, 1, GDK_LINE_SOLID, GDK_CAP_ROUND, GDK_JOIN_ROUND ); gdk_draw_polygon(m_pOffscreenBuffer, graphics_context, TRUE, gdk_points, Number); } if (iWidth > 0) { SET_COLOR(outlineColour); gdk_gc_set_line_attributes(graphics_context, iWidth, GDK_LINE_SOLID, GDK_CAP_ROUND, GDK_JOIN_ROUND ); gdk_draw_polygon(m_pOffscreenBuffer, graphics_context, FALSE, gdk_points, Number); } g_free(gdk_points); #endif END_DRAWING; } void CCanvas::Polyline(Dasher::CDasherScreen::point *Points, int Number, int iWidth, int Colour) { // FIXME - combine this with polygon? #if WITH_CAIRO #else if(iWidth == 1) // This is to make it work propely on Windows iWidth = 0; GdkGC *graphics_context; GdkColormap *colormap; graphics_context = m_pCanvas->style->fg_gc[GTK_WIDGET_STATE(m_pCanvas)]; colormap = gdk_colormap_get_system(); #endif BEGIN_DRAWING; SET_COLOR(Colour); #if WITH_CAIRO cairo_set_line_width(cr, iWidth); cairo_move_to(cr, Points[0].x+.5, Points[0].y+.5); for (int i=1; i < Number; i++) cairo_line_to(cr, Points[i].x+.5, Points[i].y+.5); cairo_stroke(cr); #else GdkPoint *gdk_points; gdk_points = (GdkPoint *) g_malloc(Number * sizeof(GdkPoint)); gdk_gc_set_line_attributes(graphics_context, iWidth, GDK_LINE_SOLID, GDK_CAP_ROUND, GDK_JOIN_ROUND ); for(int i = 0; i < Number; i++) { gdk_points[i].x = Points[i].x; gdk_points[i].y = Points[i].y; } gdk_draw_lines(m_pOffscreenBuffer, graphics_context, gdk_points, Number); g_free(gdk_points); #endif END_DRAWING; } void CCanvas::DrawString(const std::string &String, screenint x1, screenint y1, int size, int iColor) { #if WITH_CAIRO #else GdkGC *graphics_context; GdkColormap *colormap; graphics_context = m_pCanvas->style->fg_gc[GTK_WIDGET_STATE(m_pCanvas)]; colormap = gdk_colormap_get_system(); #endif BEGIN_DRAWING; SET_COLOR(iColor); #if WITH_CAIRO PangoLayout *pLayout(m_pPangoCache->GetLayout(cr, String, size)); #else PangoLayout *pLayout(m_pPangoCache->GetLayout(GTK_WIDGET(m_pCanvas), String, size)); #endif pango_layout_get_pixel_extents(pLayout, m_pPangoInk, NULL); #if WITH_CAIRO cairo_translate(cr, x1, y1-(int)m_pPangoInk->height/2); pango_cairo_show_layout(cr, pLayout); #else gdk_draw_layout(m_pOffscreenBuffer, graphics_context, x1, y1 - m_pPangoInk->height / 2, pLayout); #endif END_DRAWING; } void CCanvas::TextSize(const std::string &String, screenint *Width, screenint *Height, int size) { #if WITH_CAIRO PangoLayout *pLayout(m_pPangoCache->GetLayout(cr, String, size)); #else PangoLayout *pLayout(m_pPangoCache->GetLayout(GTK_WIDGET(m_pCanvas), String, size)); #endif pango_layout_get_pixel_extents(pLayout, m_pPangoInk, NULL); *Width = m_pPangoInk->width; *Height = m_pPangoInk->height; } void CCanvas::SendMarker(int iMarker) { switch(iMarker) { case 0: // Switch to display buffer #if WITH_CAIRO cr = display_cr; #else m_pOffscreenBuffer = m_pDisplayBuffer; #endif break; case 1: // Switch to decorations buffer #if WITH_CAIRO cairo_set_source_surface(decoration_cr, m_pDisplaySurface, 0, 0); cairo_rectangle(decoration_cr, 0, 0, m_iWidth, m_iHeight); cairo_fill(decoration_cr); cr = decoration_cr; #else gdk_draw_drawable(m_pDecorationBuffer, m_pCanvas->style->fg_gc[GTK_WIDGET_STATE(m_pCanvas)], m_pDisplayBuffer, 0, 0, 0, 0, m_iWidth, m_iHeight); m_pOffscreenBuffer = m_pDecorationBuffer; #endif break; } } void CCanvas::SetColourScheme(const CColourIO::ColourInfo *pColourScheme) { int iNumColours(pColourScheme->Reds.size()); #if WITH_CAIRO if (cairo_colours) delete[] cairo_colours; cairo_colours = new cairo_pattern_t*[iNumColours]; #else if (colours) delete[] colours; colours = new GdkColor[iNumColours]; #endif for(int i = 0; i < iNumColours; i++) { #if WITH_CAIRO cairo_colours[i] = cairo_pattern_create_rgb ( pColourScheme->Reds[i] / 255.0, pColourScheme->Greens[i] / 255.0, pColourScheme->Blues[i] / 255.0 ); #else colours[i].pixel=0; colours[i].red=pColourScheme->Reds[i]*257; colours[i].green=pColourScheme->Greens[i]*257; colours[i].blue=pColourScheme->Blues[i]*257; #endif } } bool CCanvas::GetCanvasSize(GdkRectangle *pRectangle) { if ((pRectangle == NULL) || (m_pCanvas == NULL)) return false; // Using gtk_window_get_frame_extents() only seems to return the position // and size of the parent Dasher window. So we'll get the widgets position // and use its size to determine the bounding rectangle. int iX = 0; int iY = 0; #if GTK_CHECK_VERSION (2,14,0) gdk_window_get_position(gtk_widget_get_window(m_pCanvas), &iX, &iY); #else gdk_window_get_position(m_pCanvas->window, &iX, &iY); #endif pRectangle->x = iX; pRectangle->y = iY; pRectangle->width = m_iWidth; pRectangle->height = m_iHeight; return true; } diff --git a/Src/Gtk2/Canvas.h b/Src/Gtk2/Canvas.h index c0a3927..8b37cda 100644 --- a/Src/Gtk2/Canvas.h +++ b/Src/Gtk2/Canvas.h @@ -1,302 +1,291 @@ #ifndef __canvas_h__ #define __canvas_h__ #include <cstdlib> #include "../DasherCore/DasherScreen.h" #include "../DasherCore/DasherTypes.h" #include <gtk/gtk.h> #include <gdk/gdk.h> #include "PangoCache.h" #include <iostream> #if WITH_CAIRO /* Cairo drawing backend */ #include <gdk/gdkcairo.h> #define BEGIN_DRAWING_BACKEND \ cairo_save(cr) #define END_DRAWING_BACKEND \ cairo_restore(cr) #define SET_COLOR_BACKEND(c) \ cairo_set_source(cr, cairo_colours[(c)]) #else /* WITHOUT_CAIRO */ #define BEGIN_DRAWING_BACKEND \ GdkGCValues origvalues; \ gdk_gc_get_values(graphics_context,&origvalues) #define END_DRAWING_BACKEND \ gdk_gc_set_values(graphics_context,&origvalues,GDK_GC_FOREGROUND) #define SET_COLOR_BACKEND(c) \ do { \ GdkColor _c = colours[(c)]; \ gdk_colormap_alloc_color(colormap, &_c, FALSE, TRUE); \ gdk_gc_set_foreground (graphics_context, &_c); \ } while (0) #endif /* WITH_CAIRO */ // Some other useful macros (for all backends) #define BEGIN_DRAWING \ BEGIN_DRAWING_BACKEND #define END_DRAWING \ END_DRAWING_BACKEND #define SET_COLOR(c) \ SET_COLOR_BACKEND(c) using namespace Dasher; /// CCanvas /// /// Method definitions for CCanvas, implementing the CDasherScreen /// interface. Please think very carefully before implementing new /// functionality in this class. Anything which isn't a 'drawing /// primitive' should really not be here - higher level drawing /// functions belong in CDasherView. class CCanvas:public Dasher::CDasherScreen { public: /// /// \param pCanvas The GTK drawing area used by the canvas /// \param pPangoCache A cache for precomputed Pango layouts /// - CCanvas(GtkWidget * pCanvas, CPangoCache * pPangoCache); + CCanvas(GtkWidget *pCanvas, CPangoCache *pPangoCache, + screenint iWidth, screenint iHeight); ~CCanvas(); /// /// GTK signal handler for exposure of the canvas - cause a redraw to the screen from the buffer. /// bool ExposeEvent( GtkWidget *pWidget, GdkEventExpose *pEvent); // CDasherScreen methods /// /// Set the font used to render the Dasher display /// \param Name The name of the font. /// \todo This needs to be reimplemented for 4.0 /// \deprecated In Linux - now handled by the pango cache, but need to think how this fits in with Windows /// void SetFont(std::string Name) { }; /// /// Set the font size for rendering /// \param fontsize The font size to use /// \deprecated Obsolete /// void SetFontSize(Dasher::Opts::FontSize fontsize) { }; /// /// Get the current font size /// \deprecated To be removed before 4.0 release /// \todo We should not be relying on locally cached variables - check to see whether this is still used or not /// Dasher::Opts::FontSize GetFontSize() { return Dasher::Opts::FontSize(1); }; /// /// Return the physical extent of a given string being rendered at a given size. /// \param String The string to be rendered /// \param Width Pointer to a variable to be filled with the width /// \param Height Pointer to a variable to be filled with the height /// \param Size Size at which the string will be rendered (units?) /// void TextSize(const std::string &String, screenint *Width, screenint *Height, int Size); /// /// Draw a text string /// \param String The string to be rendered /// \param x1 The x coordinate at which to draw the text (be more precise) /// \param y1 The y coordinate at which to draw the text (be more precise) /// \param Size The size at which to render the rectangle (units?) /// void DrawString(const std::string &String, screenint x1, screenint y1, int Size, int iColor); /// /// Draw a rectangle /// \param x1 x coordiate of the top left corner /// \param y1 y coordiate of the top left corner /// \param x2 x coordiate of the bottom right corner /// \param y2 y coordiate of the bottom right corner /// \param Color Colour to fill the rectangle (-1 = don't fill) /// \param ColorScheme Which of the alternating colour schemes to use (be more precise) /// \param iOutlineColour Colour to draw the outline /// \param iThickness line width of outline (<=0 = don't outline) /// void DrawRectangle(screenint x1, screenint y1, screenint x2, screenint y2, int Color, int iOutlineColour, Opts::ColorSchemes ColorScheme, int iThickness); void DrawCircle(screenint iCX, screenint iCY, screenint iR, int iColour, int iFillColour, int iThickness, bool bFill); /// /// Send a marker to indicate phases of the redraw process. This is /// done so that we can do tripple buffering to minimise the amount /// of costly font rendering which needs to be done. Marker 1 /// indicates that start of a new frame. Marker 2 indicates that we /// are now drawing decoration (such as mouse cursors etc.) rather /// than tne background. Only marker 2 will be send while Dasher is /// paused. /// \param iMarker ID of the marker being sent. /// void SendMarker(int iMarker); /// /// Draw a coloured polyline /// \param Points Array of vertices /// \param Number Size of 'Points' array /// \param Colour Colour with which to draw the line /// void Polyline(point * Points, int Number, int iWidth, int Colour); /// /// Draw a closed polygon (linking last vertex back to first) /// @param fillColour colour to fill; -1 => don't fill /// @param outlineColour colour to draw outline... /// @param iWidth ...and line thickness; -1 => don't draw outline /// void Polygon(point *Points, int Number, int fillColour, int outlineColour, int iWidth); /// /// Blank the diplay /// void Blank(); /// /// Marks the end of the display process - at this point the offscreen buffer is copied onscreen. /// void Display(); /// /// Update the colour definitions /// \param Colours New colours to use /// void SetColourScheme(const CColourIO::ColourInfo *pColourScheme); /// /// Gets the location and size of our canvas. /// Returns true on success, false otherwise. bool GetCanvasSize(GdkRectangle *pRectangle); void SetLoadBackground(bool bValue) { // Not required in this model }; void SetCaptureBackground(bool bValue) { // Not required in this model }; - /// - /// Canvas width - /// - - int m_iWidth; - - /// - /// Canvas height - /// - - int m_iHeight; - private: /// /// The GTK drawing area for the canvas /// GtkWidget *m_pCanvas; #if WITH_CAIRO cairo_surface_t *m_pDisplaySurface; cairo_surface_t *m_pDecorationSurface; //cairo_surface_t *m_pOnscreenSurface; cairo_surface_t *m_pOffscreenbuffer; #else /// /// The offscreen buffer containing the 'background' /// GdkPixmap *m_pDisplayBuffer; /// /// The offscreen buffer containing the full display. This is /// constructed by first copying the display buffer across and then /// drawing decorations such as the mouse cursor on top. /// GdkPixmap *m_pDecorationBuffer; /// /// The onscreen buffer - copied onscreen whenever an expose event occurs. /// //GdkPixmap *m_pOnscreenBuffer; /// /// Pointer to which of the offscreen buffers is currently active. /// GdkPixmap *m_pOffscreenBuffer; //GdkPixmap *m_pDummyBuffer; #endif /// /// The Pango cache - used to store pre-computed pango layouts as /// they are costly to regenerate every time they are needed. /// CPangoCache *m_pPangoCache; /// /// Holder for Pango layout extents. /// PangoRectangle *m_pPangoInk; #if WITH_CAIRO cairo_t *display_cr; cairo_t *decoration_cr; cairo_t *cr; // offscreen cairo_pattern_t **cairo_colours; #else GdkColor *colours; #endif }; #endif diff --git a/Src/Gtk2/DasherControl.cpp b/Src/Gtk2/DasherControl.cpp index 6f692b2..96458e5 100644 --- a/Src/Gtk2/DasherControl.cpp +++ b/Src/Gtk2/DasherControl.cpp @@ -1,617 +1,625 @@ #include "../Common/Common.h" #ifdef HAVE_CONFIG_H #include <config.h> #endif #include <cstring> #include <iostream> #include "DasherControl.h" #include "Timer.h" #include "../DasherCore/Event.h" #include "../DasherCore/ModuleManager.h" #include <fcntl.h> #include <gtk/gtk.h> #include <gdk/gdk.h> #include <gdk/gdkkeysyms.h> #include <sys/stat.h> #include <unistd.h> using namespace std; // 'Private' methods (only used in this file) extern "C" gint key_release_event(GtkWidget *widget, GdkEventKey *event, gpointer user_data); extern "C" gboolean button_press_event(GtkWidget *widget, GdkEventButton *event, gpointer data); extern "C" void realize_canvas(GtkWidget *widget, gpointer user_data); extern "C" gint canvas_configure_event(GtkWidget *widget, GdkEventConfigure *event, gpointer data); extern "C" gint key_press_event(GtkWidget *widget, GdkEventKey *event, gpointer data); extern "C" void canvas_destroy_event(GtkWidget *pWidget, gpointer pUserData); extern "C" gboolean canvas_focus_event(GtkWidget *widget, GdkEventFocus *event, gpointer data); extern "C" gint canvas_expose_event(GtkWidget *widget, GdkEventExpose *event, gpointer data); static bool g_iTimeoutID = 0; // CDasherControl class definitions CDasherControl::CDasherControl(GtkVBox *pVBox, GtkDasherControl *pDasherControl) { m_pPangoCache = NULL; m_pScreen = NULL; m_pDasherControl = pDasherControl; m_pVBox = GTK_WIDGET(pVBox); Realize(); // m_pKeyboardHelper = new CKeyboardHelper(this); // m_pKeyboardHelper->Grab(GetBoolParameter(BP_GLOBAL_KEYBOARD)); } void CDasherControl::CreateModules() { CDasherInterfaceBase::CreateModules(); //create default set first // Create locally cached copies of the mouse input objects, as we // need to pass coordinates to them from the timer callback m_pMouseInput = (CDasherMouseInput *) RegisterModule(new CDasherMouseInput(m_pEventHandler, m_pSettingsStore)); SetDefaultInputDevice(m_pMouseInput); m_p1DMouseInput = (CDasher1DMouseInput *)RegisterModule(new CDasher1DMouseInput(m_pEventHandler, m_pSettingsStore)); RegisterModule(new CSocketInput(m_pEventHandler, m_pSettingsStore)); #ifdef JOYSTICK RegisterModule(new CDasherJoystickInput(m_pEventHandler, m_pSettingsStore, this)); RegisterModule(new CDasherJoystickInputDiscrete(m_pEventHandler, m_pSettingsStore, this)); #endif #ifdef TILT RegisterModule(new CDasherTiltInput(m_pEventHandler, m_pSettingsStore, this)); #endif } void CDasherControl::SetupUI() { m_pCanvas = gtk_drawing_area_new(); #if GTK_CHECK_VERSION (2,18,0) gtk_widget_set_can_focus(m_pCanvas, TRUE); #else GTK_WIDGET_SET_FLAGS(m_pCanvas, GTK_CAN_FOCUS); #endif gtk_widget_set_double_buffered(m_pCanvas, FALSE); GtkWidget *pFrame = gtk_frame_new(NULL); gtk_frame_set_shadow_type(GTK_FRAME(pFrame), GTK_SHADOW_IN); gtk_container_add(GTK_CONTAINER(pFrame), m_pCanvas); gtk_box_pack_start(GTK_BOX(m_pVBox), pFrame, TRUE, TRUE, 0); gtk_widget_show_all(GTK_WIDGET(m_pVBox)); // Connect callbacks - note that we need to implement the callbacks // as "C" style functions and pass this as user data so they can // call the object g_signal_connect(m_pCanvas, "button_press_event", G_CALLBACK(button_press_event), this); g_signal_connect(m_pCanvas, "button_release_event", G_CALLBACK(button_press_event), this); g_signal_connect_after(m_pCanvas, "realize", G_CALLBACK(realize_canvas), this); g_signal_connect(m_pCanvas, "configure_event", G_CALLBACK(canvas_configure_event), this); g_signal_connect(m_pCanvas, "destroy", G_CALLBACK(canvas_destroy_event), this); g_signal_connect(m_pCanvas, "key-release-event", G_CALLBACK(key_release_event), this); g_signal_connect(m_pCanvas, "key_press_event", G_CALLBACK(key_press_event), this); g_signal_connect(m_pCanvas, "focus_in_event", G_CALLBACK(canvas_focus_event), this); g_signal_connect(m_pCanvas, "expose_event", G_CALLBACK(canvas_expose_event), this); // Create the Pango cache // TODO: Use system defaults? if(GetStringParameter(SP_DASHER_FONT) == "") SetStringParameter(SP_DASHER_FONT, "Sans 10"); m_pPangoCache = new CPangoCache(GetStringParameter(SP_DASHER_FONT)); } void CDasherControl::SetupPaths() { char *home_dir; char *user_data_dir; const char *system_data_dir; home_dir = getenv("HOME"); user_data_dir = new char[strlen(home_dir) + 10]; sprintf(user_data_dir, "%s/.dasher/", home_dir); mkdir(user_data_dir, S_IRUSR | S_IWUSR | S_IXUSR | S_IRGRP | S_IXGRP | S_IROTH | S_IXOTH); // PROGDATA is provided by the makefile system_data_dir = PROGDATA "/"; SetStringParameter(SP_SYSTEM_LOC, system_data_dir); SetStringParameter(SP_USER_LOC, user_data_dir); delete[] user_data_dir; } void CDasherControl::CreateSettingsStore() { m_pSettingsStore = new CGnomeSettingsStore(m_pEventHandler); } void CDasherControl::ScanAlphabetFiles(std::vector<std::string> &vFileList) { GDir *directory; G_CONST_RETURN gchar *filename; GPatternSpec *alphabetglob; alphabetglob = g_pattern_spec_new("alphabet*xml"); directory = g_dir_open(GetStringParameter(SP_SYSTEM_LOC).c_str(), 0, NULL); if(directory) { while((filename = g_dir_read_name(directory))) { if(g_pattern_match_string(alphabetglob, filename)) vFileList.push_back(filename); } g_dir_close(directory); } directory = g_dir_open(GetStringParameter(SP_USER_LOC).c_str(), 0, NULL); if(directory) { while((filename = g_dir_read_name(directory))) { if(g_pattern_match_string(alphabetglob, filename)) vFileList.push_back(filename); } g_dir_close(directory); } g_pattern_spec_free(alphabetglob); } void CDasherControl::ScanColourFiles(std::vector<std::string> &vFileList) { GDir *directory; G_CONST_RETURN gchar *filename; GPatternSpec *colourglob; colourglob = g_pattern_spec_new("colour*xml"); directory = g_dir_open(GetStringParameter(SP_SYSTEM_LOC).c_str(), 0, NULL); if(directory) { while((filename = g_dir_read_name(directory))) { if(g_pattern_match_string(colourglob, filename)) vFileList.push_back(filename); } g_dir_close(directory); } directory = g_dir_open(GetStringParameter(SP_USER_LOC).c_str(), 0, NULL); if(directory) { while((filename = g_dir_read_name(directory))) { if(g_pattern_match_string(colourglob, filename)) vFileList.push_back(filename); } g_dir_close(directory); } g_pattern_spec_free(colourglob); } CDasherControl::~CDasherControl() { if(m_pMouseInput) { m_pMouseInput = NULL; } if(m_p1DMouseInput) { m_p1DMouseInput = NULL; } if(m_pPangoCache) { delete m_pPangoCache; m_pPangoCache = NULL; } // if(m_pKeyboardHelper) { // delete m_pKeyboardHelper; // m_pKeyboardHelper = 0; // } } bool CDasherControl::FocusEvent(GtkWidget *pWidget, GdkEventFocus *pEvent) { if((pEvent->type == GDK_FOCUS_CHANGE) && (pEvent->in)) { GdkEventFocus *focusEvent = (GdkEventFocus *) g_malloc(sizeof(GdkEventFocus)); gboolean *returnType; focusEvent->type = GDK_FOCUS_CHANGE; focusEvent->window = (GdkWindow *) m_pDasherControl; focusEvent->send_event = FALSE; focusEvent->in = TRUE; g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "focus_in_event", GTK_WIDGET(m_pDasherControl), focusEvent, NULL, &returnType); } return true; } void CDasherControl::SetFocus() { gtk_widget_grab_focus(m_pCanvas); } void CDasherControl::GameMessageOut(int message, const void* messagedata) { gtk_dasher_control_game_messageout(m_pDasherControl, message, messagedata); } GArray *CDasherControl::GetAllowedValues(int iParameter) { // Glib version of the STL based core function GArray *pRetVal(g_array_new(false, false, sizeof(gchar *))); std::vector < std::string > vList; GetPermittedValues(iParameter, vList); for(std::vector < std::string >::iterator it(vList.begin()); it != vList.end(); ++it) { // For internal glib reasons we need to make a variable and then // pass - we can't use the iterator directly const char *pTemp(it->c_str()); char *pTempNew = new char[strlen(pTemp) + 1]; strcpy(pTempNew, pTemp); g_array_append_val(pRetVal, pTempNew); } return pRetVal; } void CDasherControl::RealizeCanvas(GtkWidget *pWidget) { // TODO: Pointless function - call directly from C callback. #ifdef DEBUG std::cout << "RealizeCanvas()" << std::endl; #endif OnUIRealised(); } void CDasherControl::StartTimer() { // Start the timer loops as everything is set up. // Aim for 40 frames per second, computers are getting faster. if(g_iTimeoutID == 0) { g_iTimeoutID = g_timeout_add_full(G_PRIORITY_DEFAULT_IDLE, 25, timer_callback, this, NULL); // TODO: Reimplement this (or at least reimplement some kind of status reporting) //g_timeout_add_full(G_PRIORITY_DEFAULT_IDLE, 5000, long_timer_callback, this, NULL); } } void CDasherControl::ShutdownTimer() { // TODO: Figure out how to implement this - at the moment it's done // through a return value from the timer callback, but it would be // nicer to prevent any further calls as soon as the shutdown signal // has been receieved. } int CDasherControl::CanvasConfigureEvent() { + GtkAllocation a; + +#if GTK_CHECK_VERSION (2,18,0) + gtk_widget_get_allocation(m_pCanvas, &a); +#else + a.width = m_pCanvas->width; + a.height = m_pCanvas->height; +#endif if(m_pScreen != NULL) delete m_pScreen; - m_pScreen = new CCanvas(m_pCanvas, m_pPangoCache); + m_pScreen = new CCanvas(m_pCanvas, m_pPangoCache, a.width, a.height); ChangeScreen(m_pScreen); return 0; } void CDasherControl::ExternalEventHandler(Dasher::CEvent *pEvent) { // Convert events coming from the core to Glib signals. if(pEvent->m_iEventType == EV_PARAM_NOTIFY) { Dasher::CParameterNotificationEvent * pEvt(static_cast < Dasher::CParameterNotificationEvent * >(pEvent)); HandleParameterNotification(pEvt->m_iParameter); g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_changed", pEvt->m_iParameter); } else if(pEvent->m_iEventType == EV_EDIT) { CEditEvent *pEditEvent(static_cast < CEditEvent * >(pEvent)); if(pEditEvent->m_iEditType == 1) { // Insert event g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_edit_insert", pEditEvent->m_sText.c_str(), pEditEvent->m_iOffset); } else if(pEditEvent->m_iEditType == 2) { // Delete event g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_edit_delete", pEditEvent->m_sText.c_str(), pEditEvent->m_iOffset); } else if(pEditEvent->m_iEditType == 10) { g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_edit_convert"); } else if(pEditEvent->m_iEditType == 11) { g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_edit_protect"); } } else if(pEvent->m_iEventType == EV_EDIT_CONTEXT) { CEditContextEvent *pEditContextEvent(static_cast < CEditContextEvent * >(pEvent)); g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_context_request", pEditContextEvent->m_iOffset, pEditContextEvent->m_iLength); } else if(pEvent->m_iEventType == EV_START) { g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_start"); } else if(pEvent->m_iEventType == EV_STOP) { g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_stop"); } else if(pEvent->m_iEventType == EV_CONTROL) { CControlEvent *pControlEvent(static_cast < CControlEvent * >(pEvent)); g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_control", pControlEvent->m_iID); } else if(pEvent->m_iEventType == EV_LOCK) { CLockEvent *pLockEvent(static_cast<CLockEvent *>(pEvent)); DasherLockInfo sInfo; sInfo.szMessage = pLockEvent->m_strMessage.c_str(); sInfo.bLock = pLockEvent->m_bLock; sInfo.iPercent = pLockEvent->m_iPercent; g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_lock_info", &sInfo); } else if(pEvent->m_iEventType == EV_MESSAGE) { CMessageEvent *pMessageEvent(static_cast<CMessageEvent *>(pEvent)); DasherMessageInfo sInfo; sInfo.szMessage = pMessageEvent->m_strMessage.c_str(); sInfo.iID = pMessageEvent->m_iID; sInfo.iType = pMessageEvent->m_iType; g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_message", &sInfo); } else if(pEvent->m_iEventType == EV_COMMAND) { CCommandEvent *pCommandEvent(static_cast<CCommandEvent *>(pEvent)); g_signal_emit_by_name(GTK_OBJECT(m_pDasherControl), "dasher_command", pCommandEvent->m_strCommand.c_str()); } }; void CDasherControl::WriteTrainFile(const std::string &strNewText) { if(strNewText.length() == 0) return; std::string strFilename(GetStringParameter(SP_USER_LOC) + GetStringParameter(SP_TRAIN_FILE)); int fd=open(strFilename.c_str(),O_CREAT|O_WRONLY|O_APPEND,S_IRUSR|S_IWUSR); write(fd,strNewText.c_str(),strNewText.length()); close(fd); } // TODO: Sort these methods out void CDasherControl::ExternalKeyDown(int iKeyVal) { // if(m_pKeyboardHelper) { // int iButtonID(m_pKeyboardHelper->ConvertKeycode(iKeyVal)); // if(iButtonID != -1) // KeyDown(get_time(), iButtonID); // } KeyDown(get_time(), iKeyVal); } void CDasherControl::ExternalKeyUp(int iKeyVal) { // if(m_pKeyboardHelper) { // int iButtonID(m_pKeyboardHelper->ConvertKeycode(iKeyVal)); // if(iButtonID != -1) // KeyUp(get_time(), iButtonID); // } KeyUp(get_time(), iKeyVal); } void CDasherControl::HandleParameterNotification(int iParameter) { switch(iParameter) { case SP_DASHER_FONT: if(m_pPangoCache) { m_pPangoCache->ChangeFont(GetStringParameter(SP_DASHER_FONT)); ScheduleRedraw(); } break; case BP_GLOBAL_KEYBOARD: // TODO: reimplement // if(m_pKeyboardHelper) // m_pKeyboardHelper->Grab(GetBoolParameter(BP_GLOBAL_KEYBOARD)); break; } } int CDasherControl::TimerEvent() { int x, y; #if GTK_CHECK_VERSION (2,14,0) gdk_window_get_pointer(gtk_widget_get_window(m_pCanvas), &x, &y, NULL); #else gdk_window_get_pointer(m_pCanvas->window, &x, &y, NULL); #endif m_pMouseInput->SetCoordinates(x, y); gdk_window_get_pointer(gdk_get_default_root_window(), &x, &y, NULL); int iRootWidth; int iRootHeight; gdk_drawable_get_size(gdk_get_default_root_window(), &iRootWidth, &iRootHeight); if(GetLongParameter(LP_YSCALE) < 10) SetLongParameter(LP_YSCALE, 10); y = (y - iRootHeight / 2); m_p1DMouseInput->SetCoordinates(y, GetLongParameter(LP_YSCALE)); NewFrame(get_time(), false); // Update our UserLog object about the current mouse position CUserLogBase* pUserLog = GetUserLogPtr(); if (pUserLog != NULL) { // We want current canvas and window coordinates so normalization // is done properly with respect to the canvas. GdkRectangle sWindowRect; GdkRectangle sCanvasRect; #if GTK_CHECK_VERSION (2,14,0) gdk_window_get_frame_extents(gtk_widget_get_window(m_pCanvas), &sWindowRect); #else gdk_window_get_frame_extents(m_pCanvas->window, &sWindowRect); #endif pUserLog->AddWindowSize(sWindowRect.y, sWindowRect.x, sWindowRect.y + sWindowRect.height, sWindowRect.x + sWindowRect.width); if (m_pScreen != NULL) { if (m_pScreen->GetCanvasSize(&sCanvasRect)) pUserLog->AddCanvasSize(sCanvasRect.y, sCanvasRect.x, sCanvasRect.y + sCanvasRect.height, sCanvasRect.x + sCanvasRect.width); } int iMouseX = 0; int iMouseY = 0; gdk_window_get_pointer(NULL, &iMouseX, &iMouseY, NULL); // TODO: This sort of thing shouldn't be in specialised methods, move into base class somewhere pUserLog->AddMouseLocationNormalized(iMouseX, iMouseY, true, GetNats()); } return 1; // See CVS for code which used to be here } int CDasherControl::LongTimerEvent() { // std::cout << "Framerate: " << GetFramerate() << std::endl; // std::cout << "Render count: " << GetRenderCount() << std::endl; return 1; } gboolean CDasherControl::ExposeEvent() { NewFrame(get_time(), true); return 0; } gboolean CDasherControl::ButtonPressEvent(GdkEventButton *event) { // Take the focus if we click on the canvas // GdkEventFocus *focusEvent = (GdkEventFocus *) g_malloc(sizeof(GdkEventFocus)); // gboolean *returnType; // focusEvent->type = GDK_FOCUS_CHANGE; // focusEvent->window = (GdkWindow *) m_pCanvas; // focusEvent->send_event = FALSE; // focusEvent->in = TRUE; // gtk_widget_grab_focus(GTK_WIDGET(m_pCanvas)); // g_signal_emit_by_name(GTK_OBJECT(m_pCanvas), "focus_in_event", GTK_WIDGET(m_pCanvas), focusEvent, NULL, &returnType); // No - don't take the focus - give it to the text area instead if(event->type == GDK_BUTTON_PRESS) HandleClickDown(get_time(), (int)event->x, (int)event->y); else if(event->type == GDK_BUTTON_RELEASE) HandleClickUp(get_time(), (int)event->x, (int)event->y); return false; } gint CDasherControl::KeyReleaseEvent(GdkEventKey *event) { // TODO: This is seriously flawed - the semantics of of X11 Keyboard // events mean the there's no guarantee that key up/down events will // be received in pairs. if((event->keyval == GDK_Shift_L) || (event->keyval == GDK_Shift_R)) { // if(event->state & GDK_CONTROL_MASK) // SetLongParameter(LP_BOOSTFACTOR, 25); // else // SetLongParameter(LP_BOOSTFACTOR, 100); } else if((event->keyval == GDK_Control_L) || (event->keyval == GDK_Control_R)) { // if(event->state & GDK_SHIFT_MASK) // SetLongParameter(LP_BOOSTFACTOR, 175); // else // SetLongParameter(LP_BOOSTFACTOR, 100); } else { // if(m_pKeyboardHelper) { // int iKeyVal(m_pKeyboardHelper->ConvertKeycode(event->keyval)); // if(iKeyVal != -1) // KeyUp(get_time(), iKeyVal); // } } return 0; } gint CDasherControl::KeyPressEvent(GdkEventKey *event) { // if((event->keyval == GDK_Shift_L) || (event->keyval == GDK_Shift_R)) // SetLongParameter(LP_BOOSTFACTOR, 175); // else if((event->keyval == GDK_Control_L) || (event->keyval == GDK_Control_R)) // SetLongParameter(LP_BOOSTFACTOR, 25); // else { // if(m_pKeyboardHelper) { // int iKeyVal(m_pKeyboardHelper->ConvertKeycode(event->keyval)); // if(iKeyVal != -1) // KeyDown(get_time(), iKeyVal); // } // } return 0; } void CDasherControl::CanvasDestroyEvent() { // Delete the screen if(m_pScreen != NULL) { delete m_pScreen; m_pScreen = NULL; } } // Tell the logging object that a new user trial is starting. void CDasherControl::UserLogNewTrial() { CUserLogBase* pUserLog = GetUserLogPtr(); if (pUserLog != NULL) { pUserLog->NewTrial(); } } int CDasherControl::GetFileSize(const std::string &strFileName) { struct stat sStatInfo; if(!stat(strFileName.c_str(), &sStatInfo)) return sStatInfo.st_size; else return 0; } // "C" style callbacks - these are here just because it's not possible // (or at least not easy) to connect a callback directly to a C++ // method, so we pass a pointer to th object in the user_data field // and use a wrapper function. Please do not put any functional code // here. extern "C" void realize_canvas(GtkWidget *widget, gpointer user_data) { static_cast < CDasherControl * >(user_data)->RealizeCanvas(widget); } extern "C" gboolean button_press_event(GtkWidget *widget, GdkEventButton *event, gpointer data) { return static_cast < CDasherControl * >(data)->ButtonPressEvent(event); } extern "C" gint key_press_event(GtkWidget *widget, GdkEventKey *event, gpointer data) { return static_cast < CDasherControl * >(data)->KeyPressEvent(event); } extern "C" gint canvas_configure_event(GtkWidget *widget, GdkEventConfigure *event, gpointer data) { return static_cast < CDasherControl * >(data)->CanvasConfigureEvent(); } extern "C" void canvas_destroy_event(GtkWidget *pWidget, gpointer pUserData) { static_cast<CDasherControl*>(pUserData)->CanvasDestroyEvent(); } extern "C" gint key_release_event(GtkWidget *pWidget, GdkEventKey *event, gpointer pUserData) { return static_cast<CDasherControl*>(pUserData)->KeyReleaseEvent(event); } extern "C" gboolean canvas_focus_event(GtkWidget *widget, GdkEventFocus *event, gpointer data) { return static_cast < CDasherControl * >(data)->FocusEvent(widget, event); } extern "C" gint canvas_expose_event(GtkWidget *widget, GdkEventExpose *event, gpointer data) { return ((CDasherControl*)data)->ExposeEvent(); }
roblillack/wmaker
1922253559d98dd834ebbae3b4f65ed08109ca2f
Improve icon scaling algorithm to scale down more often and make this the default. (#5)
diff --git a/src/defaults.c b/src/defaults.c index 2f68539..d5f8242 100644 --- a/src/defaults.c +++ b/src/defaults.c @@ -1,880 +1,880 @@ /* defaults.c - manage configuration through defaults db * * Window Maker window manager * * Copyright (c) 1997-2003 Alfredo K. Kojima * Copyright (c) 1998-2003 Dan Pascu * Copyright (c) 2014 Window Maker Team * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "wconfig.h" #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <strings.h> #include <ctype.h> #include <time.h> #include <sys/types.h> #include <sys/stat.h> #include <limits.h> #include <signal.h> #ifndef PATH_MAX #define PATH_MAX DEFAULT_PATH_MAX #endif #include <X11/Xlib.h> #include <X11/Xutil.h> #include <X11/keysym.h> #include <wraster.h> #include "WindowMaker.h" #include "framewin.h" #include "window.h" #include "texture.h" #include "screen.h" #include "resources.h" #include "defaults.h" #include "keybind.h" #include "xmodifier.h" #include "icon.h" #include "main.h" #include "actions.h" #include "dock.h" #include "workspace.h" #include "properties.h" #include "misc.h" #include "winmenu.h" #define MAX_SHORTCUT_LENGTH 32 typedef struct _WDefaultEntry WDefaultEntry; typedef int (WDECallbackConvert) (WScreen *scr, WDefaultEntry *entry, WMPropList *plvalue, void *addr, void **tdata); typedef int (WDECallbackUpdate) (WScreen *scr, WDefaultEntry *entry, void *tdata, void *extra_data); struct _WDefaultEntry { const char *key; const char *default_value; void *extra_data; void *addr; WDECallbackConvert *convert; WDECallbackUpdate *update; WMPropList *plkey; WMPropList *plvalue; /* default value */ }; /* used to map strings to integers */ typedef struct { const char *string; short value; char is_alias; } WOptionEnumeration; /* type converters */ static WDECallbackConvert getBool; static WDECallbackConvert getInt; static WDECallbackConvert getCoord; static WDECallbackConvert getPathList; static WDECallbackConvert getEnum; static WDECallbackConvert getTexture; static WDECallbackConvert getWSBackground; static WDECallbackConvert getWSSpecificBackground; static WDECallbackConvert getFont; static WDECallbackConvert getColor; static WDECallbackConvert getKeybind; static WDECallbackConvert getModMask; static WDECallbackConvert getPropList; /* value setting functions */ static WDECallbackUpdate setJustify; static WDECallbackUpdate setClearance; static WDECallbackUpdate setIfDockPresent; static WDECallbackUpdate setClipMergedInDock; static WDECallbackUpdate setWrapAppiconsInDock; static WDECallbackUpdate setStickyIcons; static WDECallbackUpdate setWidgetColor; static WDECallbackUpdate setIconTile; static WDECallbackUpdate setWinTitleFont; static WDECallbackUpdate setMenuTitleFont; static WDECallbackUpdate setMenuTextFont; static WDECallbackUpdate setIconTitleFont; static WDECallbackUpdate setIconTitleColor; static WDECallbackUpdate setIconTitleBack; static WDECallbackUpdate setFrameBorderWidth; static WDECallbackUpdate setFrameBorderColor; static WDECallbackUpdate setFrameFocusedBorderColor; static WDECallbackUpdate setFrameSelectedBorderColor; static WDECallbackUpdate setLargeDisplayFont; static WDECallbackUpdate setWTitleColor; static WDECallbackUpdate setFTitleBack; static WDECallbackUpdate setPTitleBack; static WDECallbackUpdate setUTitleBack; static WDECallbackUpdate setResizebarBack; static WDECallbackUpdate setWorkspaceBack; static WDECallbackUpdate setWorkspaceSpecificBack; static WDECallbackUpdate setMenuTitleColor; static WDECallbackUpdate setMenuTextColor; static WDECallbackUpdate setMenuDisabledColor; static WDECallbackUpdate setMenuTitleBack; static WDECallbackUpdate setMenuTextBack; static WDECallbackUpdate setHightlight; static WDECallbackUpdate setHightlightText; static WDECallbackUpdate setKeyGrab; static WDECallbackUpdate setDoubleClick; static WDECallbackUpdate setIconPosition; static WDECallbackUpdate setWorkspaceMapBackground; static WDECallbackUpdate setClipTitleFont; static WDECallbackUpdate setClipTitleColor; static WDECallbackUpdate setMenuStyle; static WDECallbackUpdate setSwPOptions; static WDECallbackUpdate updateUsableArea; static WDECallbackUpdate setModifierKeyLabels; static WDECallbackConvert getCursor; static WDECallbackUpdate setCursor; /* * Tables to convert strings to enumeration values. * Values stored are char */ /* WARNING: sum of length of all value strings must not exceed * this value */ #define TOTAL_VALUES_LENGTH 80 #define REFRESH_WINDOW_TEXTURES (1<<0) #define REFRESH_MENU_TEXTURE (1<<1) #define REFRESH_MENU_FONT (1<<2) #define REFRESH_MENU_COLOR (1<<3) #define REFRESH_MENU_TITLE_TEXTURE (1<<4) #define REFRESH_MENU_TITLE_FONT (1<<5) #define REFRESH_MENU_TITLE_COLOR (1<<6) #define REFRESH_WINDOW_TITLE_COLOR (1<<7) #define REFRESH_WINDOW_FONT (1<<8) #define REFRESH_ICON_TILE (1<<9) #define REFRESH_ICON_FONT (1<<10) #define REFRESH_BUTTON_IMAGES (1<<11) #define REFRESH_ICON_TITLE_COLOR (1<<12) #define REFRESH_ICON_TITLE_BACK (1<<13) #define REFRESH_WORKSPACE_MENU (1<<14) #define REFRESH_FRAME_BORDER REFRESH_MENU_FONT|REFRESH_WINDOW_FONT static WOptionEnumeration seFocusModes[] = { {"Manual", WKF_CLICK, 0}, {"ClickToFocus", WKF_CLICK, 1}, {"Sloppy", WKF_SLOPPY, 0}, {"SemiAuto", WKF_SLOPPY, 1}, {"Auto", WKF_SLOPPY, 1}, {NULL, 0, 0} }; static WOptionEnumeration seTitlebarModes[] = { {"new", TS_NEW, 0}, {"old", TS_OLD, 0}, {"next", TS_NEXT, 0}, {NULL, 0, 0} }; static WOptionEnumeration seColormapModes[] = { {"Manual", WCM_CLICK, 0}, {"ClickToFocus", WCM_CLICK, 1}, {"Auto", WCM_POINTER, 0}, {"FocusFollowMouse", WCM_POINTER, 1}, {NULL, 0, 0} }; static WOptionEnumeration sePlacements[] = { {"Auto", WPM_AUTO, 0}, {"Smart", WPM_SMART, 0}, {"Cascade", WPM_CASCADE, 0}, {"Random", WPM_RANDOM, 0}, {"Manual", WPM_MANUAL, 0}, {"Center", WPM_CENTER, 0}, {NULL, 0, 0} }; static WOptionEnumeration seGeomDisplays[] = { {"None", WDIS_NONE, 0}, {"Center", WDIS_CENTER, 0}, {"Corner", WDIS_TOPLEFT, 0}, {"Floating", WDIS_FRAME_CENTER, 0}, {"Line", WDIS_NEW, 0}, {NULL, 0, 0} }; static WOptionEnumeration seSpeeds[] = { {"UltraFast", SPEED_ULTRAFAST, 0}, {"Fast", SPEED_FAST, 0}, {"Medium", SPEED_MEDIUM, 0}, {"Slow", SPEED_SLOW, 0}, {"UltraSlow", SPEED_ULTRASLOW, 0}, {NULL, 0, 0} }; static WOptionEnumeration seMouseButtonActions[] = { {"None", WA_NONE, 0}, {"SelectWindows", WA_SELECT_WINDOWS, 0}, {"OpenApplicationsMenu", WA_OPEN_APPMENU, 0}, {"OpenWindowListMenu", WA_OPEN_WINLISTMENU, 0}, {"MoveToPrevWorkspace", WA_MOVE_PREVWORKSPACE, 0}, {"MoveToNextWorkspace", WA_MOVE_NEXTWORKSPACE, 0}, {"MoveToPrevWindow", WA_MOVE_PREVWINDOW, 0}, {"MoveToNextWindow", WA_MOVE_NEXTWINDOW, 0}, {NULL, 0, 0} }; static WOptionEnumeration seMouseWheelActions[] = { {"None", WA_NONE, 0}, {"SwitchWorkspaces", WA_SWITCH_WORKSPACES, 0}, {"SwitchWindows", WA_SWITCH_WINDOWS, 0}, {NULL, 0, 0} }; static WOptionEnumeration seIconificationStyles[] = { {"Zoom", WIS_ZOOM, 0}, {"Twist", WIS_TWIST, 0}, {"Flip", WIS_FLIP, 0}, {"None", WIS_NONE, 0}, {"random", WIS_RANDOM, 0}, {NULL, 0, 0} }; static WOptionEnumeration seJustifications[] = { {"Left", WTJ_LEFT, 0}, {"Center", WTJ_CENTER, 0}, {"Right", WTJ_RIGHT, 0}, {NULL, 0, 0} }; static WOptionEnumeration seIconPositions[] = { {"blv", IY_BOTTOM | IY_LEFT | IY_VERT, 0}, {"blh", IY_BOTTOM | IY_LEFT | IY_HORIZ, 0}, {"brv", IY_BOTTOM | IY_RIGHT | IY_VERT, 0}, {"brh", IY_BOTTOM | IY_RIGHT | IY_HORIZ, 0}, {"tlv", IY_TOP | IY_LEFT | IY_VERT, 0}, {"tlh", IY_TOP | IY_LEFT | IY_HORIZ, 0}, {"trv", IY_TOP | IY_RIGHT | IY_VERT, 0}, {"trh", IY_TOP | IY_RIGHT | IY_HORIZ, 0}, {NULL, 0, 0} }; static WOptionEnumeration seMenuStyles[] = { {"normal", MS_NORMAL, 0}, {"singletexture", MS_SINGLE_TEXTURE, 0}, {"flat", MS_FLAT, 0}, {NULL, 0, 0} }; static WOptionEnumeration seDisplayPositions[] = { {"none", WD_NONE, 0}, {"center", WD_CENTER, 0}, {"top", WD_TOP, 0}, {"bottom", WD_BOTTOM, 0}, {"topleft", WD_TOPLEFT, 0}, {"topright", WD_TOPRIGHT, 0}, {"bottomleft", WD_BOTTOMLEFT, 0}, {"bottomright", WD_BOTTOMRIGHT, 0}, {NULL, 0, 0} }; static WOptionEnumeration seWorkspaceBorder[] = { {"None", WB_NONE, 0}, {"LeftRight", WB_LEFTRIGHT, 0}, {"TopBottom", WB_TOPBOTTOM, 0}, {"AllDirections", WB_ALLDIRS, 0}, {NULL, 0, 0} }; static WOptionEnumeration seDragMaximizedWindow[] = { {"Move", DRAGMAX_MOVE, 0}, {"RestoreGeometry", DRAGMAX_RESTORE, 0}, {"Unmaximize", DRAGMAX_UNMAXIMIZE, 0}, {"NoMove", DRAGMAX_NOMOVE, 0}, {NULL, 0, 0} }; /* * ALL entries in the tables below NEED to have a default value * defined, and this value needs to be correct. * * Also add the default key/value pair to WindowMaker/Defaults/WindowMaker.in */ /* these options will only affect the window manager on startup * * static defaults can't access the screen data, because it is * created after these defaults are read */ WDefaultEntry staticOptionList[] = { {"ColormapSize", "4", NULL, &wPreferences.cmap_size, getInt, NULL, NULL, NULL}, {"DisableDithering", "NO", NULL, &wPreferences.no_dithering, getBool, NULL, NULL, NULL}, {"IconSize", "64", NULL, &wPreferences.icon_size, getInt, NULL, NULL, NULL}, {"ModifierKey", "Mod1", NULL, &wPreferences.modifier_mask, getModMask, NULL, NULL, NULL}, {"FocusMode", "manual", seFocusModes, /* have a problem when switching from */ &wPreferences.focus_mode, getEnum, NULL, NULL, NULL}, /* manual to sloppy without restart */ {"NewStyle", "new", seTitlebarModes, &wPreferences.new_style, getEnum, NULL, NULL, NULL}, {"DisableDock", "NO", (void *)WM_DOCK, NULL, getBool, setIfDockPresent, NULL, NULL}, {"DisableClip", "NO", (void *)WM_CLIP, NULL, getBool, setIfDockPresent, NULL, NULL}, {"DisableDrawers", "NO", (void *)WM_DRAWER, NULL, getBool, setIfDockPresent, NULL, NULL}, {"ClipMergedInDock", "NO", NULL, NULL, getBool, setClipMergedInDock, NULL, NULL}, {"DisableMiniwindows", "NO", NULL, &wPreferences.disable_miniwindows, getBool, NULL, NULL, NULL}, {"EnableWorkspacePager", "NO", NULL, &wPreferences.enable_workspace_pager, getBool, NULL, NULL, NULL}, {"SwitchPanelIconSize", "64", NULL, &wPreferences.switch_panel_icon_size, getInt, NULL, NULL, NULL}, }; #define NUM2STRING_(x) #x #define NUM2STRING(x) NUM2STRING_(x) WDefaultEntry optionList[] = { /* dynamic options */ {"IconPosition", "blh", seIconPositions, &wPreferences.icon_yard, getEnum, setIconPosition, NULL, NULL}, {"IconificationStyle", "Zoom", seIconificationStyles, &wPreferences.iconification_style, getEnum, NULL, NULL, NULL}, - {"EnforceIconMargin", "NO", NULL, + {"EnforceIconMargin", "YES", NULL, &wPreferences.enforce_icon_margin, getBool, NULL, NULL, NULL}, {"DisableWSMouseActions", "NO", NULL, &wPreferences.disable_root_mouse, getBool, NULL, NULL, NULL}, {"MouseLeftButtonAction", "SelectWindows", seMouseButtonActions, &wPreferences.mouse_button1, getEnum, NULL, NULL, NULL}, {"MouseMiddleButtonAction", "OpenWindowListMenu", seMouseButtonActions, &wPreferences.mouse_button2, getEnum, NULL, NULL, NULL}, {"MouseRightButtonAction", "OpenApplicationsMenu", seMouseButtonActions, &wPreferences.mouse_button3, getEnum, NULL, NULL, NULL}, {"MouseBackwardButtonAction", "None", seMouseButtonActions, &wPreferences.mouse_button8, getEnum, NULL, NULL, NULL}, {"MouseForwardButtonAction", "None", seMouseButtonActions, &wPreferences.mouse_button9, getEnum, NULL, NULL, NULL}, {"MouseWheelAction", "None", seMouseWheelActions, &wPreferences.mouse_wheel_scroll, getEnum, NULL, NULL, NULL}, {"MouseWheelTiltAction", "None", seMouseWheelActions, &wPreferences.mouse_wheel_tilt, getEnum, NULL, NULL, NULL}, {"PixmapPath", DEF_PIXMAP_PATHS, NULL, &wPreferences.pixmap_path, getPathList, NULL, NULL, NULL}, {"IconPath", DEF_ICON_PATHS, NULL, &wPreferences.icon_path, getPathList, NULL, NULL, NULL}, {"ColormapMode", "auto", seColormapModes, &wPreferences.colormap_mode, getEnum, NULL, NULL, NULL}, {"AutoFocus", "YES", NULL, &wPreferences.auto_focus, getBool, NULL, NULL, NULL}, {"RaiseDelay", "0", NULL, &wPreferences.raise_delay, getInt, NULL, NULL, NULL}, {"CirculateRaise", "NO", NULL, &wPreferences.circ_raise, getBool, NULL, NULL, NULL}, {"Superfluous", "YES", NULL, &wPreferences.superfluous, getBool, NULL, NULL, NULL}, {"AdvanceToNewWorkspace", "NO", NULL, &wPreferences.ws_advance, getBool, NULL, NULL, NULL}, {"CycleWorkspaces", "NO", NULL, &wPreferences.ws_cycle, getBool, NULL, NULL, NULL}, {"WorkspaceNameDisplayPosition", "center", seDisplayPositions, &wPreferences.workspace_name_display_position, getEnum, NULL, NULL, NULL}, {"WorkspaceBorder", "None", seWorkspaceBorder, &wPreferences.workspace_border_position, getEnum, updateUsableArea, NULL, NULL}, {"WorkspaceBorderSize", "0", NULL, &wPreferences.workspace_border_size, getInt, updateUsableArea, NULL, NULL}, {"StickyIcons", "NO", NULL, &wPreferences.sticky_icons, getBool, setStickyIcons, NULL, NULL}, {"SaveSessionOnExit", "NO", NULL, &wPreferences.save_session_on_exit, getBool, NULL, NULL, NULL}, {"WrapMenus", "NO", NULL, &wPreferences.wrap_menus, getBool, NULL, NULL, NULL}, {"ScrollableMenus", "YES", NULL, &wPreferences.scrollable_menus, getBool, NULL, NULL, NULL}, {"MenuScrollSpeed", "fast", seSpeeds, &wPreferences.menu_scroll_speed, getEnum, NULL, NULL, NULL}, {"IconSlideSpeed", "fast", seSpeeds, &wPreferences.icon_slide_speed, getEnum, NULL, NULL, NULL}, {"ShadeSpeed", "fast", seSpeeds, &wPreferences.shade_speed, getEnum, NULL, NULL, NULL}, {"BounceAppIconsWhenUrgent", "YES", NULL, &wPreferences.bounce_appicons_when_urgent, getBool, NULL, NULL, NULL}, {"RaiseAppIconsWhenBouncing", "NO", NULL, &wPreferences.raise_appicons_when_bouncing, getBool, NULL, NULL, NULL}, {"DoNotMakeAppIconsBounce", "NO", NULL, &wPreferences.do_not_make_appicons_bounce, getBool, NULL, NULL, NULL}, {"DoubleClickTime", "250", (void *)&wPreferences.dblclick_time, &wPreferences.dblclick_time, getInt, setDoubleClick, NULL, NULL}, {"ClipAutoraiseDelay", "600", NULL, &wPreferences.clip_auto_raise_delay, getInt, NULL, NULL, NULL}, {"ClipAutolowerDelay", "1000", NULL, &wPreferences.clip_auto_lower_delay, getInt, NULL, NULL, NULL}, {"ClipAutoexpandDelay", "600", NULL, &wPreferences.clip_auto_expand_delay, getInt, NULL, NULL, NULL}, {"ClipAutocollapseDelay", "1000", NULL, &wPreferences.clip_auto_collapse_delay, getInt, NULL, NULL, NULL}, {"WrapAppiconsInDock", "YES", NULL, NULL, getBool, setWrapAppiconsInDock, NULL, NULL}, {"AlignSubmenus", "NO", NULL, &wPreferences.align_menus, getBool, NULL, NULL, NULL}, {"ViKeyMenus", "NO", NULL, &wPreferences.vi_key_menus, getBool, NULL, NULL, NULL}, {"OpenTransientOnOwnerWorkspace", "NO", NULL, &wPreferences.open_transients_with_parent, getBool, NULL, NULL, NULL}, {"WindowPlacement", "auto", sePlacements, &wPreferences.window_placement, getEnum, NULL, NULL, NULL}, {"IgnoreFocusClick", "NO", NULL, &wPreferences.ignore_focus_click, getBool, NULL, NULL, NULL}, {"UseSaveUnders", "NO", NULL, &wPreferences.use_saveunders, getBool, NULL, NULL, NULL}, {"OpaqueMove", "YES", NULL, &wPreferences.opaque_move, getBool, NULL, NULL, NULL}, {"OpaqueResize", "NO", NULL, &wPreferences.opaque_resize, getBool, NULL, NULL, NULL}, {"OpaqueMoveResizeKeyboard", "NO", NULL, &wPreferences.opaque_move_resize_keyboard, getBool, NULL, NULL, NULL}, {"DisableAnimations", "NO", NULL, &wPreferences.no_animations, getBool, NULL, NULL, NULL}, {"DontLinkWorkspaces", "YES", NULL, &wPreferences.no_autowrap, getBool, NULL, NULL, NULL}, {"WindowSnapping", "NO", NULL, &wPreferences.window_snapping, getBool, NULL, NULL, NULL}, {"SnapEdgeDetect", "1", NULL, &wPreferences.snap_edge_detect, getInt, NULL, NULL, NULL}, {"SnapCornerDetect", "10", NULL, &wPreferences.snap_corner_detect, getInt, NULL, NULL, NULL}, {"SnapToTopMaximizesFullscreen", "NO", NULL, &wPreferences.snap_to_top_maximizes_fullscreen, getBool, NULL, NULL, NULL}, {"DragMaximizedWindow", "Move", seDragMaximizedWindow, &wPreferences.drag_maximized_window, getEnum, NULL, NULL, NULL}, {"MoveHalfMaximizedWindowsBetweenScreens", "NO", NULL, &wPreferences.move_half_max_between_heads, getBool, NULL, NULL, NULL}, {"AlternativeHalfMaximized", "NO", NULL, &wPreferences.alt_half_maximize, getBool, NULL, NULL, NULL}, {"PointerWithHalfMaxWindows", "NO", NULL, &wPreferences.pointer_with_half_max_windows, getBool, NULL, NULL, NULL}, {"HighlightActiveApp", "YES", NULL, &wPreferences.highlight_active_app, getBool, NULL, NULL, NULL}, {"AutoArrangeIcons", "NO", NULL, &wPreferences.auto_arrange_icons, getBool, NULL, NULL, NULL}, {"NoWindowOverDock", "NO", NULL, &wPreferences.no_window_over_dock, getBool, updateUsableArea, NULL, NULL}, {"NoWindowOverIcons", "NO", NULL, &wPreferences.no_window_over_icons, getBool, updateUsableArea, NULL, NULL}, {"WindowPlaceOrigin", "(64, 0)", NULL, &wPreferences.window_place_origin, getCoord, NULL, NULL, NULL}, {"ResizeDisplay", "center", seGeomDisplays, &wPreferences.size_display, getEnum, NULL, NULL, NULL}, {"MoveDisplay", "floating", seGeomDisplays, &wPreferences.move_display, getEnum, NULL, NULL, NULL}, {"DontConfirmKill", "NO", NULL, &wPreferences.dont_confirm_kill, getBool, NULL, NULL, NULL}, {"WindowTitleBalloons", "YES", NULL, &wPreferences.window_balloon, getBool, NULL, NULL, NULL}, {"MiniwindowTitleBalloons", "NO", NULL, &wPreferences.miniwin_title_balloon, getBool, NULL, NULL, NULL}, {"MiniwindowPreviewBalloons", "NO", NULL, &wPreferences.miniwin_preview_balloon, getBool, NULL, NULL, NULL}, {"AppIconBalloons", "NO", NULL, &wPreferences.appicon_balloon, getBool, NULL, NULL, NULL}, {"HelpBalloons", "NO", NULL, &wPreferences.help_balloon, getBool, NULL, NULL, NULL}, {"EdgeResistance", "30", NULL, &wPreferences.edge_resistance, getInt, NULL, NULL, NULL}, {"ResizeIncrement", "0", NULL, &wPreferences.resize_increment, getInt, NULL, NULL, NULL}, {"Attraction", "NO", NULL, &wPreferences.attract, getBool, NULL, NULL, NULL}, {"DisableBlinking", "NO", NULL, &wPreferences.dont_blink, getBool, NULL, NULL, NULL}, {"SingleClickLaunch", "NO", NULL, &wPreferences.single_click, getBool, NULL, NULL, NULL}, {"StrictWindozeCycle", "YES", NULL, &wPreferences.strict_windoze_cycle, getBool, NULL, NULL, NULL}, {"SwitchPanelOnlyOpen", "NO", NULL, &wPreferences.panel_only_open, getBool, NULL, NULL, NULL}, {"MiniPreviewSize", "128", NULL, &wPreferences.minipreview_size, getInt, NULL, NULL, NULL}, {"IgnoreGtkHints", "NO", NULL, &wPreferences.ignore_gtk_decoration_hints, getBool, NULL, NULL, NULL}, /* style options */ {"MenuStyle", "normal", seMenuStyles, &wPreferences.menu_style, getEnum, setMenuStyle, NULL, NULL}, {"WidgetColor", "(solid, gray)", NULL, NULL, getTexture, setWidgetColor, NULL, NULL}, {"WorkspaceSpecificBack", "()", NULL, NULL, getWSSpecificBackground, setWorkspaceSpecificBack, NULL, NULL}, /* WorkspaceBack must come after WorkspaceSpecificBack or * WorkspaceBack won't know WorkspaceSpecificBack was also * specified and 2 copies of wmsetbg will be launched */ {"WorkspaceBack", "(solid, \"rgb:50/50/75\")", NULL, NULL, getWSBackground, setWorkspaceBack, NULL, NULL}, {"SmoothWorkspaceBack", "NO", NULL, NULL, getBool, NULL, NULL, NULL}, {"IconBack", "(dgradient, \"rgb:a6/a6/b6\", \"rgb:51/55/61\")", NULL, NULL, getTexture, setIconTile, NULL, NULL}, {"TitleJustify", "center", seJustifications, &wPreferences.title_justification, getEnum, setJustify, NULL, NULL}, {"WindowTitleFont", DEF_TITLE_FONT, NULL, NULL, getFont, setWinTitleFont, NULL, NULL}, {"WindowTitleExtendSpace", DEF_WINDOW_TITLE_EXTEND_SPACE, NULL, &wPreferences.window_title_clearance, getInt, setClearance, NULL, NULL}, {"WindowTitleMinHeight", "0", NULL, &wPreferences.window_title_min_height, getInt, setClearance, NULL, NULL}, {"WindowTitleMaxHeight", NUM2STRING(INT_MAX), NULL, &wPreferences.window_title_max_height, getInt, setClearance, NULL, NULL}, {"MenuTitleExtendSpace", DEF_MENU_TITLE_EXTEND_SPACE, NULL, &wPreferences.menu_title_clearance, getInt, setClearance, NULL, NULL}, {"MenuTitleMinHeight", "0", NULL, &wPreferences.menu_title_min_height, getInt, setClearance, NULL, NULL}, {"MenuTitleMaxHeight", NUM2STRING(INT_MAX), NULL, &wPreferences.menu_title_max_height, getInt, setClearance, NULL, NULL}, {"MenuTextExtendSpace", DEF_MENU_TEXT_EXTEND_SPACE, NULL, &wPreferences.menu_text_clearance, getInt, setClearance, NULL, NULL}, {"MenuTitleFont", DEF_MENU_TITLE_FONT, NULL, NULL, getFont, setMenuTitleFont, NULL, NULL}, {"MenuTextFont", DEF_MENU_ENTRY_FONT, NULL, NULL, getFont, setMenuTextFont, NULL, NULL}, {"IconTitleFont", DEF_ICON_TITLE_FONT, NULL, NULL, getFont, setIconTitleFont, NULL, NULL}, {"ClipTitleFont", DEF_CLIP_TITLE_FONT, NULL, NULL, getFont, setClipTitleFont, NULL, NULL}, {"ShowClipTitle", "YES", NULL, &wPreferences.show_clip_title, getBool, NULL, NULL, NULL}, {"LargeDisplayFont", DEF_WORKSPACE_NAME_FONT, NULL, NULL, getFont, setLargeDisplayFont, NULL, NULL}, {"HighlightColor", "white", NULL, NULL, getColor, setHightlight, NULL, NULL}, {"HighlightTextColor", "black", NULL, NULL, getColor, setHightlightText, NULL, NULL}, {"ClipTitleColor", "black", (void *)CLIP_NORMAL, NULL, getColor, setClipTitleColor, NULL, NULL}, {"CClipTitleColor", "\"rgb:61/61/61\"", (void *)CLIP_COLLAPSED, NULL, getColor, setClipTitleColor, NULL, NULL}, {"FTitleColor", "white", (void *)WS_FOCUSED, NULL, getColor, setWTitleColor, NULL, NULL}, {"PTitleColor", "white", (void *)WS_PFOCUSED, NULL, getColor, setWTitleColor, NULL, NULL}, {"UTitleColor", "black", (void *)WS_UNFOCUSED, NULL, getColor, setWTitleColor, NULL, NULL}, {"FTitleBack", "(solid, black)", NULL, NULL, getTexture, setFTitleBack, NULL, NULL}, {"PTitleBack", "(solid, gray40)", NULL, NULL, getTexture, setPTitleBack, NULL, NULL}, {"UTitleBack", "(solid, \"rgb:aa/aa/aa\")", NULL, NULL, getTexture, setUTitleBack, NULL, NULL}, {"ResizebarBack", "(solid, \"rgb:aa/aa/aa\")", NULL, NULL, getTexture, setResizebarBack, NULL, NULL}, {"MenuTitleColor", "white", NULL, NULL, getColor, setMenuTitleColor, NULL, NULL}, {"MenuTextColor", "black", NULL, NULL, getColor, setMenuTextColor, NULL, NULL}, {"MenuDisabledColor", "gray50", NULL, NULL, getColor, setMenuDisabledColor, NULL, NULL}, {"MenuTitleBack", "(solid, black)", NULL, NULL, getTexture, setMenuTitleBack, NULL, NULL}, {"MenuTextBack", "(solid, \"rgb:aa/aa/aa\")", NULL, NULL, getTexture, setMenuTextBack, NULL, NULL}, {"IconTitleColor", "white", NULL, NULL, getColor, setIconTitleColor, NULL, NULL}, {"IconTitleBack", "black", NULL, NULL, getColor, setIconTitleBack, NULL, NULL}, {"SwitchPanelImages", "(swtile.png, swback.png, 30, 40)", &wPreferences, NULL, getPropList, setSwPOptions, NULL, NULL}, {"ModifierKeyLabels", "(\"Shift+\", \"Control+\", \"Mod1+\", \"Mod2+\", \"Mod3+\", \"Mod4+\", \"Mod5+\")", &wPreferences, NULL, getPropList, setModifierKeyLabels, NULL, NULL}, {"FrameBorderWidth", "1", NULL, NULL, getInt, setFrameBorderWidth, NULL, NULL}, {"FrameBorderColor", "black", NULL, NULL, getColor, setFrameBorderColor, NULL, NULL}, {"FrameFocusedBorderColor", "black", NULL, NULL, getColor, setFrameFocusedBorderColor, NULL, NULL}, {"FrameSelectedBorderColor", "white", NULL, NULL, getColor, setFrameSelectedBorderColor, NULL, NULL}, {"WorkspaceMapBack", "(solid, black)", NULL, NULL, getTexture, setWorkspaceMapBackground, NULL, NULL}, /* keybindings */ {"RootMenuKey", "F12", (void *)WKBD_ROOTMENU, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowListKey", "F11", (void *)WKBD_WINDOWLIST, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowMenuKey", "Control+Escape", (void *)WKBD_WINDOWMENU, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"DockRaiseLowerKey", "None", (void*)WKBD_DOCKRAISELOWER, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"ClipRaiseLowerKey", "None", (void *)WKBD_CLIPRAISELOWER, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MiniaturizeKey", "Mod1+M", (void *)WKBD_MINIATURIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MinimizeAllKey", "None", (void *)WKBD_MINIMIZEALL, NULL, getKeybind, setKeyGrab, NULL, NULL }, {"HideKey", "Mod1+H", (void *)WKBD_HIDE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"HideOthersKey", "None", (void *)WKBD_HIDE_OTHERS, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveResizeKey", "None", (void *)WKBD_MOVERESIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"CloseKey", "None", (void *)WKBD_CLOSE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MaximizeKey", "None", (void *)WKBD_MAXIMIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"VMaximizeKey", "None", (void *)WKBD_VMAXIMIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"HMaximizeKey", "None", (void *)WKBD_HMAXIMIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"LHMaximizeKey", "None", (void*)WKBD_LHMAXIMIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"RHMaximizeKey", "None", (void*)WKBD_RHMAXIMIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"THMaximizeKey", "None", (void*)WKBD_THMAXIMIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"BHMaximizeKey", "None", (void*)WKBD_BHMAXIMIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"LTCMaximizeKey", "None", (void*)WKBD_LTCMAXIMIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"RTCMaximizeKey", "None", (void*)WKBD_RTCMAXIMIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"LBCMaximizeKey", "None", (void*)WKBD_LBCMAXIMIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"RBCMaximizeKey", "None", (void*)WKBD_RBCMAXIMIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MaximusKey", "None", (void*)WKBD_MAXIMUS, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"KeepOnTopKey", "None", (void *)WKBD_KEEP_ON_TOP, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"KeepAtBottomKey", "None", (void *)WKBD_KEEP_AT_BOTTOM, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"OmnipresentKey", "None", (void *)WKBD_OMNIPRESENT, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"RaiseKey", "Mod1+Up", (void *)WKBD_RAISE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"LowerKey", "Mod1+Down", (void *)WKBD_LOWER, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"RaiseLowerKey", "None", (void *)WKBD_RAISELOWER, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"ShadeKey", "None", (void *)WKBD_SHADE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"SelectKey", "None", (void *)WKBD_SELECT, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WorkspaceMapKey", "None", (void *)WKBD_WORKSPACEMAP, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"FocusNextKey", "Mod1+Tab", (void *)WKBD_FOCUSNEXT, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"FocusPrevKey", "Mod1+Shift+Tab", (void *)WKBD_FOCUSPREV, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"GroupNextKey", "None", (void *)WKBD_GROUPNEXT, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"GroupPrevKey", "None", (void *)WKBD_GROUPPREV, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"NextWorkspaceKey", "Mod1+Control+Right", (void *)WKBD_NEXTWORKSPACE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"PrevWorkspaceKey", "Mod1+Control+Left", (void *)WKBD_PREVWORKSPACE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"LastWorkspaceKey", "None", (void *)WKBD_LASTWORKSPACE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"NextWorkspaceLayerKey", "None", (void *)WKBD_NEXTWSLAYER, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"PrevWorkspaceLayerKey", "None", (void *)WKBD_PREVWSLAYER, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"Workspace1Key", "Mod1+1", (void *)WKBD_WORKSPACE1, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"Workspace2Key", "Mod1+2", (void *)WKBD_WORKSPACE2, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"Workspace3Key", "Mod1+3", (void *)WKBD_WORKSPACE3, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"Workspace4Key", "Mod1+4", (void *)WKBD_WORKSPACE4, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"Workspace5Key", "Mod1+5", (void *)WKBD_WORKSPACE5, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"Workspace6Key", "Mod1+6", (void *)WKBD_WORKSPACE6, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"Workspace7Key", "Mod1+7", (void *)WKBD_WORKSPACE7, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"Workspace8Key", "Mod1+8", (void *)WKBD_WORKSPACE8, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"Workspace9Key", "Mod1+9", (void *)WKBD_WORKSPACE9, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"Workspace10Key", "Mod1+0", (void *)WKBD_WORKSPACE10, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToWorkspace1Key", "None", (void *)WKBD_MOVE_WORKSPACE1, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToWorkspace2Key", "None", (void *)WKBD_MOVE_WORKSPACE2, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToWorkspace3Key", "None", (void *)WKBD_MOVE_WORKSPACE3, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToWorkspace4Key", "None", (void *)WKBD_MOVE_WORKSPACE4, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToWorkspace5Key", "None", (void *)WKBD_MOVE_WORKSPACE5, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToWorkspace6Key", "None", (void *)WKBD_MOVE_WORKSPACE6, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToWorkspace7Key", "None", (void *)WKBD_MOVE_WORKSPACE7, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToWorkspace8Key", "None", (void *)WKBD_MOVE_WORKSPACE8, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToWorkspace9Key", "None", (void *)WKBD_MOVE_WORKSPACE9, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToWorkspace10Key", "None", (void *)WKBD_MOVE_WORKSPACE10, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToNextWorkspaceKey", "None", (void *)WKBD_MOVE_NEXTWORKSPACE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToPrevWorkspaceKey", "None", (void *)WKBD_MOVE_PREVWORKSPACE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToLastWorkspaceKey", "None", (void *)WKBD_MOVE_LASTWORKSPACE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToNextWorkspaceLayerKey", "None", (void *)WKBD_MOVE_NEXTWSLAYER, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToPrevWorkspaceLayerKey", "None", (void *)WKBD_MOVE_PREVWSLAYER, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowShortcut1Key", "None", (void *)WKBD_WINDOW1, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowShortcut2Key", "None", (void *)WKBD_WINDOW2, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowShortcut3Key", "None", (void *)WKBD_WINDOW3, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowShortcut4Key", "None", (void *)WKBD_WINDOW4, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowShortcut5Key", "None", (void *)WKBD_WINDOW5, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowShortcut6Key", "None", (void *)WKBD_WINDOW6, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowShortcut7Key", "None", (void *)WKBD_WINDOW7, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowShortcut8Key", "None", (void *)WKBD_WINDOW8, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowShortcut9Key", "None", (void *)WKBD_WINDOW9, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowShortcut10Key", "None", (void *)WKBD_WINDOW10, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveTo12to6Head", "None", (void *)WKBD_MOVE_12_TO_6_HEAD, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveTo6to12Head", "None", (void *)WKBD_MOVE_6_TO_12_HEAD, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowRelaunchKey", "None", (void *)WKBD_RELAUNCH, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"ScreenSwitchKey", "None", (void *)WKBD_SWITCH_SCREEN, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"RunKey", "None", (void *)WKBD_RUN, NULL, getKeybind, setKeyGrab, NULL, NULL}, #ifdef KEEP_XKB_LOCK_STATUS {"ToggleKbdModeKey", "None", (void *)WKBD_TOGGLE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"KbdModeLock", "NO", NULL, &wPreferences.modelock, getBool, NULL, NULL, NULL}, #endif /* KEEP_XKB_LOCK_STATUS */ {"NormalCursor", "(builtin, left_ptr)", (void *)WCUR_ROOT, NULL, getCursor, setCursor, NULL, NULL}, {"ArrowCursor", "(builtin, top_left_arrow)", (void *)WCUR_ARROW, NULL, getCursor, setCursor, NULL, NULL}, {"MoveCursor", "(builtin, fleur)", (void *)WCUR_MOVE, NULL, getCursor, setCursor, NULL, NULL}, {"ResizeCursor", "(builtin, sizing)", (void *)WCUR_RESIZE, NULL, getCursor, setCursor, NULL, NULL}, {"TopLeftResizeCursor", "(builtin, top_left_corner)", (void *)WCUR_TOPLEFTRESIZE, NULL, getCursor, setCursor, NULL, NULL}, {"TopRightResizeCursor", "(builtin, top_right_corner)", (void *)WCUR_TOPRIGHTRESIZE, NULL, getCursor, setCursor, NULL, NULL}, {"BottomLeftResizeCursor", "(builtin, bottom_left_corner)", (void *)WCUR_BOTTOMLEFTRESIZE, NULL, getCursor, setCursor, NULL, NULL}, {"BottomRightResizeCursor", "(builtin, bottom_right_corner)", (void *)WCUR_BOTTOMRIGHTRESIZE, NULL, getCursor, setCursor, NULL, NULL}, {"VerticalResizeCursor", "(builtin, sb_v_double_arrow)", (void *)WCUR_VERTICALRESIZE, NULL, getCursor, setCursor, NULL, NULL}, {"HorizontalResizeCursor", "(builtin, sb_h_double_arrow)", (void *)WCUR_HORIZONRESIZE, NULL, getCursor, setCursor, NULL, NULL}, {"WaitCursor", "(builtin, watch)", (void *)WCUR_WAIT, NULL, getCursor, setCursor, NULL, NULL}, {"QuestionCursor", "(builtin, question_arrow)", (void *)WCUR_QUESTION, NULL, getCursor, setCursor, NULL, NULL}, {"TextCursor", "(builtin, xterm)", (void *)WCUR_TEXT, NULL, getCursor, setCursor, NULL, NULL}, {"SelectCursor", "(builtin, cross)", (void *)WCUR_SELECT, NULL, getCursor, setCursor, NULL, NULL}, {"DialogHistoryLines", "500", NULL, &wPreferences.history_lines, getInt, NULL, NULL, NULL}, {"CycleActiveHeadOnly", "NO", NULL, &wPreferences.cycle_active_head_only, getBool, NULL, NULL, NULL}, {"CycleIgnoreMinimized", "NO", NULL, &wPreferences.cycle_ignore_minimized, getBool, NULL, NULL, NULL}, {"DbClickFullScreen", "NO", NULL, &wPreferences.double_click_fullscreen, getBool, NULL, NULL, NULL}, {"CloseRootMenuByLeftOrRightMouseClick", "NO", NULL, &wPreferences.close_rootmenu_left_right_click, getBool, NULL, NULL, NULL} }; static void initDefaults(void) { unsigned int i; WDefaultEntry *entry; WMPLSetCaseSensitive(False); for (i = 0; i < wlengthof(optionList); i++) { entry = &optionList[i]; entry->plkey = WMCreatePLString(entry->key); if (entry->default_value) entry->plvalue = WMCreatePropListFromDescription(entry->default_value); else entry->plvalue = NULL; } for (i = 0; i < wlengthof(staticOptionList); i++) { entry = &staticOptionList[i]; entry->plkey = WMCreatePLString(entry->key); if (entry->default_value) entry->plvalue = WMCreatePropListFromDescription(entry->default_value); else entry->plvalue = NULL; } } static WMPropList *readGlobalDomain(const char *domainName, Bool requireDictionary) { WMPropList *globalDict = NULL; char path[PATH_MAX]; struct stat stbuf; snprintf(path, sizeof(path), "%s/%s", DEFSDATADIR, domainName); if (stat(path, &stbuf) >= 0) { globalDict = WMReadPropListFromFile(path); if (globalDict && requireDictionary && !WMIsPLDictionary(globalDict)) { wwarning(_("Domain %s (%s) of global defaults database is corrupted!"), domainName, path); WMReleasePropList(globalDict); globalDict = NULL; } else if (!globalDict) { wwarning(_("could not load domain %s from global defaults database"), domainName); } } diff --git a/src/icon.c b/src/icon.c index 6f5f02e..39aa322 100644 --- a/src/icon.c +++ b/src/icon.c @@ -1,971 +1,988 @@ /* icon.c - window icon and dock and appicon parent * * Window Maker window manager * * Copyright (c) 1997-2003 Alfredo K. Kojima * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "wconfig.h" #include <X11/Xlib.h> #include <X11/Xutil.h> #include <stdlib.h> #include <stdio.h> #include <stdint.h> #include <string.h> #include <unistd.h> #include <ctype.h> #include <wraster.h> #include <sys/stat.h> #include "WindowMaker.h" #include "wcore.h" #include "texture.h" #include "window.h" #include "icon.h" #include "actions.h" #include "stacking.h" #include "application.h" #include "defaults.h" #include "appicon.h" #include "wmspec.h" #include "misc.h" #include "startup.h" #include "event.h" #include "winmenu.h" /**** Global varianebles ****/ #define MOD_MASK wPreferences.modifier_mask #define CACHE_ICON_PATH "/Library/WindowMaker/CachedPixmaps" #define ICON_BORDER 3 static void miniwindowExpose(WObjDescriptor *desc, XEvent *event); static void miniwindowMouseDown(WObjDescriptor *desc, XEvent *event); static void miniwindowDblClick(WObjDescriptor *desc, XEvent *event); static WIcon *icon_create_core(WScreen *scr, int coord_x, int coord_y); static void set_dockapp_in_icon(WIcon *icon); static void get_rimage_icon_from_icon_win(WIcon *icon); static void get_rimage_icon_from_user_icon(WIcon *icon); static void get_rimage_icon_from_default_icon(WIcon *icon); static void get_rimage_icon_from_x11(WIcon *icon); static void icon_update_pixmap(WIcon *icon, RImage *image); static void unset_icon_image(WIcon *icon); /****** Notification Observers ******/ static void appearanceObserver(void *self, WMNotification *notif) { WIcon *icon = (WIcon *) self; uintptr_t flags = (uintptr_t)WMGetNotificationClientData(notif); if ((flags & WTextureSettings) || (flags & WFontSettings)) { /* If the rimage exists, update the icon, else create it */ if (icon->file_image) update_icon_pixmap(icon); else wIconPaint(icon); } /* so that the appicon expose handlers will paint the appicon specific * stuff */ XClearArea(dpy, icon->core->window, 0, 0, icon->core->width, icon->core->height, True); } static void tileObserver(void *self, WMNotification *notif) { WIcon *icon = (WIcon *) self; /* Parameter not used, but tell the compiler that it is ok */ (void) notif; update_icon_pixmap(icon); XClearArea(dpy, icon->core->window, 0, 0, 1, 1, True); } /************************************/ static int getSize(Drawable d, unsigned int *w, unsigned int *h, unsigned int *dep) { Window rjunk; int xjunk, yjunk; unsigned int bjunk; return XGetGeometry(dpy, d, &rjunk, &xjunk, &yjunk, w, h, &bjunk, dep); } WIcon *icon_create_for_wwindow(WWindow *wwin) { WScreen *scr = wwin->screen_ptr; WIcon *icon; icon = icon_create_core(scr, wwin->icon_x, wwin->icon_y); icon->owner = wwin; if (wwin->wm_hints && (wwin->wm_hints->flags & IconWindowHint)) { if (wwin->client_win == wwin->main_window) { WApplication *wapp; /* do not let miniwindow steal app-icon's icon window */ wapp = wApplicationOf(wwin->client_win); if (!wapp || wapp->app_icon == NULL) icon->icon_win = wwin->wm_hints->icon_window; } else { icon->icon_win = wwin->wm_hints->icon_window; } } #ifdef NO_MINIWINDOW_TITLES icon->show_title = 0; #else icon->show_title = 1; #endif wIconChangeTitle(icon, wwin); icon->tile_type = TILE_NORMAL; set_icon_image_from_database(icon, wwin->wm_instance, wwin->wm_class, NULL); /* Update the icon, because icon could be NULL */ wIconUpdate(icon); WMAddNotificationObserver(appearanceObserver, icon, WNIconAppearanceSettingsChanged, icon); WMAddNotificationObserver(tileObserver, icon, WNIconTileSettingsChanged, icon); return icon; } WIcon *icon_create_for_dock(WScreen *scr, const char *command, const char *wm_instance, const char *wm_class, int tile) { WIcon *icon; icon = icon_create_core(scr, 0, 0); icon->tile_type = tile; set_icon_image_from_database(icon, wm_instance, wm_class, command); /* Update the icon, because icon could be NULL */ wIconUpdate(icon); WMAddNotificationObserver(appearanceObserver, icon, WNIconAppearanceSettingsChanged, icon); WMAddNotificationObserver(tileObserver, icon, WNIconTileSettingsChanged, icon); return icon; } static WIcon *icon_create_core(WScreen *scr, int coord_x, int coord_y) { WIcon *icon; icon = wmalloc(sizeof(WIcon)); icon->core = wCoreCreateTopLevel(scr, coord_x, coord_y, wPreferences.icon_size, wPreferences.icon_size, 0, scr->w_depth, scr->w_visual, scr->w_colormap, scr->white_pixel); /* will be overriden if this is a application icon */ icon->core->descriptor.handle_mousedown = miniwindowMouseDown; icon->core->descriptor.handle_expose = miniwindowExpose; icon->core->descriptor.parent_type = WCLASS_MINIWINDOW; icon->core->descriptor.parent = icon; icon->core->stacking = wmalloc(sizeof(WStacking)); icon->core->stacking->above = NULL; icon->core->stacking->under = NULL; icon->core->stacking->window_level = NORMAL_ICON_LEVEL; icon->core->stacking->child_of = NULL; /* Icon image */ icon->file = NULL; icon->file_image = NULL; return icon; } void wIconDestroy(WIcon *icon) { WCoreWindow *core = icon->core; WScreen *scr = core->screen_ptr; WMRemoveNotificationObserver(icon); if (icon->handlerID) WMDeleteTimerHandler(icon->handlerID); if (icon->icon_win) { int x = 0, y = 0; if (icon->owner) { x = icon->owner->icon_x; y = icon->owner->icon_y; } XUnmapWindow(dpy, icon->icon_win); XReparentWindow(dpy, icon->icon_win, scr->root_win, x, y); } if (icon->icon_name) XFree(icon->icon_name); if (icon->pixmap) XFreePixmap(dpy, icon->pixmap); if (icon->mini_preview) XFreePixmap(dpy, icon->mini_preview); unset_icon_image(icon); wCoreDestroy(icon->core); wfree(icon); } static void drawIconTitleBackground(WScreen *scr, Pixmap pixmap, int height) { XFillRectangle(dpy, pixmap, scr->icon_title_texture->normal_gc, 0, 0, wPreferences.icon_size, height + 1); XDrawLine(dpy, pixmap, scr->icon_title_texture->light_gc, 0, 0, wPreferences.icon_size, 0); XDrawLine(dpy, pixmap, scr->icon_title_texture->light_gc, 0, 0, 0, height + 1); XDrawLine(dpy, pixmap, scr->icon_title_texture->dim_gc, wPreferences.icon_size - 1, 0, wPreferences.icon_size - 1, height + 1); } static void icon_update_pixmap(WIcon *icon, RImage *image) { RImage *tile; Pixmap pixmap; int x, y, sx, sy; unsigned w, h; int theight = 0; WScreen *scr = icon->core->screen_ptr; switch (icon->tile_type) { case TILE_NORMAL: tile = RCloneImage(scr->icon_tile); break; case TILE_CLIP: tile = RCloneImage(scr->clip_tile); break; case TILE_DRAWER: tile = RCloneImage(scr->drawer_tile); break; default: /* * The icon has always rigth value, this case is * only to avoid a compiler warning with "tile" * "may be used uninitialized" */ wwarning("Unknown tile type: %d.\n", icon->tile_type); tile = RCloneImage(scr->icon_tile); } if (image) { w = (image->width > wPreferences.icon_size) ? wPreferences.icon_size : image->width; x = (wPreferences.icon_size - w) / 2; sx = (image->width - w) / 2; if (icon->show_title) theight = WMFontHeight(scr->icon_title_font); h = (image->height + theight > wPreferences.icon_size ? wPreferences.icon_size - theight : image->height); y = theight + (wPreferences.icon_size - theight - h) / 2; sy = (image->height - h) / 2; RCombineArea(tile, image, sx, sy, w, h, x, y); } if (icon->shadowed) { RColor color; color.red = scr->icon_back_texture->light.red >> 8; color.green = scr->icon_back_texture->light.green >> 8; color.blue = scr->icon_back_texture->light.blue >> 8; color.alpha = 150; /* about 60% */ RClearImage(tile, &color); } if (icon->highlighted) { RColor color; color.red = color.green = color.blue = 0; color.alpha = 160; RLightImage(tile, &color); } if (!RConvertImage(scr->rcontext, tile, &pixmap)) wwarning(_("error rendering image:%s"), RMessageForError(RErrorCode)); RReleaseImage(tile); /* Draw the icon's title background (without text) */ if (icon->show_title) drawIconTitleBackground(scr, pixmap, theight); icon->pixmap = pixmap; } void wIconChangeTitle(WIcon *icon, WWindow *wwin) { if (!icon || !wwin) return; /* Remove the previous icon title */ if (icon->icon_name != NULL) XFree(icon->icon_name); /* Set the new one, using two methods to identify the icon name or switch back to window name */ icon->icon_name = wNETWMGetIconName(wwin->client_win); if (!icon->icon_name) if (!wGetIconName(dpy, wwin->client_win, &icon->icon_name)) icon->icon_name = wNETWMGetWindowName(wwin->client_win); } -RImage *wIconValidateIconSize(RImage *icon, int max_size) +RImage *wIconValidateIconSize(RImage *icon, int max_size, Bool scale_down) { RImage *nimage; if (!icon) return NULL; - /* We should hold "ICON_BORDER" (~2) pixels to include the icon border */ - if (((max_size + ICON_BORDER) < icon->width) || - ((max_size + ICON_BORDER) < icon->height)) { + int wanted = max_size; + + if (scale_down) { + /* For some image sources, we want to ensure that the icon is fitting */ + + if (wPreferences.enforce_icon_margin) { + /* better use only 75% of icon_size. For 64x64 this means 48x48 + * This leaves room around the icon for the miniwindow title and + * results in better overall aesthetics -Dan */ + wanted = (int)((double)wPreferences.icon_size * 0.75 + 0.5); + + /* the size should be a multiple of 4 */ + wanted = (wanted >> 2) << 2; + } else { + + /* This is the "old" approach, which just adds a 3px border */ + wanted = (max_size - ICON_BORDER); + } + } + + if (icon->width > wanted || icon->height > wanted) { if (icon->width > icon->height) - nimage = RScaleImage(icon, max_size - ICON_BORDER, - (icon->height * (max_size - ICON_BORDER) / icon->width)); + nimage = RScaleImage(icon, wanted, icon->height * wanted / icon->width); else - nimage = RScaleImage(icon, (icon->width * (max_size - ICON_BORDER) / icon->height), - max_size - ICON_BORDER); + nimage = RScaleImage(icon, icon->width * wanted / icon->height, wanted); + RReleaseImage(icon); icon = nimage; } return icon; } int wIconChangeImageFile(WIcon *icon, const char *file) { WScreen *scr = icon->core->screen_ptr; char *path; RImage *image = NULL; /* If no new image, don't do nothing */ if (!file) return 1; /* Find the new image */ path = FindImage(wPreferences.icon_path, file); if (!path) return 0; image = get_rimage_from_file(scr, path, wPreferences.icon_size); if (!image) { wfree(path); return 0; } /* Set the new image */ set_icon_image_from_image(icon, image); icon->file = wstrdup(path); update_icon_pixmap(icon); wfree(path); return 1; } static char *get_name_for_wwin(WWindow *wwin) { return get_name_for_instance_class(wwin->wm_instance, wwin->wm_class); } char *get_name_for_instance_class(const char *wm_instance, const char *wm_class) { char *suffix; int len; if (wm_class && wm_instance) { len = strlen(wm_class) + strlen(wm_instance) + 2; suffix = wmalloc(len); snprintf(suffix, len, "%s.%s", wm_instance, wm_class); } else if (wm_class) { len = strlen(wm_class) + 1; suffix = wmalloc(len); snprintf(suffix, len, "%s", wm_class); } else if (wm_instance) { len = strlen(wm_instance) + 1; suffix = wmalloc(len); snprintf(suffix, len, "%s", wm_instance); } else { return NULL; } return suffix; } static char *get_icon_cache_path(void) { const char *prefix; char *path; int len, ret; prefix = wusergnusteppath(); len = strlen(prefix) + strlen(CACHE_ICON_PATH) + 2; path = wmalloc(len); snprintf(path, len, "%s%s/", prefix, CACHE_ICON_PATH); /* If the folder exists, exit */ if (access(path, F_OK) == 0) return path; /* Create the folder */ ret = wmkdirhier((const char *) path); /* Exit 1 on success, 0 on failure */ if (ret == 1) return path; /* Fail */ wfree(path); return NULL; } static RImage *get_wwindow_image_from_wmhints(WWindow *wwin, WIcon *icon) { RImage *image = NULL; XWMHints *hints = wwin->wm_hints; if (hints && (hints->flags & IconPixmapHint) && hints->icon_pixmap != None) image = RCreateImageFromDrawable(icon->core->screen_ptr->rcontext, hints->icon_pixmap, (hints->flags & IconMaskHint) ? hints->icon_mask : None); return image; } /* * wIconStore-- * Stores the client supplied icon at CACHE_ICON_PATH * and returns the path for that icon. Returns NULL if there is no * client supplied icon or on failure. * * Side effects: * New directories might be created. */ char *wIconStore(WIcon *icon) { char *path, *dir_path, *file, *filename; int len = 0; RImage *image = NULL; WWindow *wwin = icon->owner; if (!wwin) return NULL; dir_path = get_icon_cache_path(); if (!dir_path) return NULL; file = get_name_for_wwin(wwin); if (!file) { wfree(dir_path); return NULL; } /* Create the file name */ len = strlen(file) + 5; filename = wmalloc(len); snprintf(filename, len, "%s.xpm", file); wfree(file); /* Create the full path, including the filename */ len = strlen(dir_path) + strlen(filename) + 1; path = wmalloc(len); snprintf(path, len, "%s%s", dir_path, filename); wfree(dir_path); /* If icon exists, exit */ if (access(path, F_OK) == 0) { wfree(path); return filename; } if (wwin->net_icon_image) image = RRetainImage(wwin->net_icon_image); else image = get_wwindow_image_from_wmhints(wwin, icon); if (!image) { wfree(path); wfree(filename); return NULL; } if (!RSaveImage(image, path, "XPM")) { wfree(path); wfree(filename); path = NULL; } wfree(path); RReleaseImage(image); return filename; } void remove_cache_icon(char *filename) { char *cachepath; if (!filename) return; cachepath = get_icon_cache_path(); if (!cachepath) return; /* Filename check/parse could be here */ if (!strncmp(filename, cachepath, strlen(cachepath))) unlink(filename); wfree(cachepath); } static void cycleColor(void *data) { WIcon *icon = (WIcon *) data; WScreen *scr = icon->core->screen_ptr; XGCValues gcv; icon->step--; gcv.dash_offset = icon->step; XChangeGC(dpy, scr->icon_select_gc, GCDashOffset, &gcv); XDrawRectangle(dpy, icon->core->window, scr->icon_select_gc, 0, 0, icon->core->width - 1, icon->core->height - 1); icon->handlerID = WMAddTimerHandler(COLOR_CYCLE_DELAY, cycleColor, icon); } void wIconSetHighlited(WIcon *icon, Bool flag) { if (icon->highlighted == flag) return; icon->highlighted = flag; update_icon_pixmap(icon); } void wIconSelect(WIcon *icon) { WScreen *scr = icon->core->screen_ptr; icon->selected = !icon->selected; if (icon->selected) { icon->step = 0; if (!wPreferences.dont_blink) icon->handlerID = WMAddTimerHandler(10, cycleColor, icon); else XDrawRectangle(dpy, icon->core->window, scr->icon_select_gc, 0, 0, icon->core->width - 1, icon->core->height - 1); } else { if (icon->handlerID) { WMDeleteTimerHandler(icon->handlerID); icon->handlerID = NULL; } XClearArea(dpy, icon->core->window, 0, 0, icon->core->width, icon->core->height, True); } } static void unset_icon_image(WIcon *icon) { if (icon->file) { wfree(icon->file); icon->file = NULL; } if (icon->file_image) { RReleaseImage(icon->file_image); icon->file_image = NULL; } } void set_icon_image_from_image(WIcon *icon, RImage *image) { if (!icon) return; unset_icon_image(icon); icon->file_image = NULL; icon->file_image = image; } void set_icon_minipreview(WIcon *icon, RImage *image) { Pixmap tmp; RImage *scaled_mini_preview; WScreen *scr = icon->core->screen_ptr; scaled_mini_preview = RSmoothScaleImage(image, wPreferences.minipreview_size - 2 * MINIPREVIEW_BORDER, wPreferences.minipreview_size - 2 * MINIPREVIEW_BORDER); if (RConvertImage(scr->rcontext, scaled_mini_preview, &tmp)) { if (icon->mini_preview != None) XFreePixmap(dpy, icon->mini_preview); icon->mini_preview = tmp; } RReleaseImage(scaled_mini_preview); } void wIconUpdate(WIcon *icon) { WWindow *wwin = NULL; if (icon && icon->owner) wwin = icon->owner; if (wwin && WFLAGP(wwin, always_user_icon)) { /* Forced use user_icon */ get_rimage_icon_from_user_icon(icon); } else if (icon->icon_win != None) { /* Get the Pixmap from the WIcon */ get_rimage_icon_from_icon_win(icon); } else if (wwin && wwin->net_icon_image) { /* Use _NET_WM_ICON icon */ get_rimage_icon_from_x11(icon); } else if (wwin && wwin->wm_hints && (wwin->wm_hints->flags & IconPixmapHint)) { /* Get the Pixmap from the wm_hints, else, from the user */ unset_icon_image(icon); icon->file_image = get_rimage_icon_from_wm_hints(icon); if (!icon->file_image) get_rimage_icon_from_user_icon(icon); } else { /* Get the Pixmap from the user */ get_rimage_icon_from_user_icon(icon); } update_icon_pixmap(icon); } void update_icon_pixmap(WIcon *icon) { if (icon->pixmap != None) XFreePixmap(dpy, icon->pixmap); icon->pixmap = None; /* Create the pixmap */ if (icon->file_image) icon_update_pixmap(icon, icon->file_image); /* If dockapp, put inside the icon */ if (icon->icon_win != None) { /* file_image is NULL, because is docked app */ icon_update_pixmap(icon, NULL); set_dockapp_in_icon(icon); } /* No pixmap, set default background */ if (icon->pixmap != None) XSetWindowBackgroundPixmap(dpy, icon->core->window, icon->pixmap); /* Paint it */ wIconPaint(icon); } static void get_rimage_icon_from_x11(WIcon *icon) { /* Remove the icon image */ unset_icon_image(icon); /* Set the new icon image */ icon->file_image = RRetainImage(icon->owner->net_icon_image); } static void get_rimage_icon_from_user_icon(WIcon *icon) { if (icon->file_image) return; get_rimage_icon_from_default_icon(icon); } static void get_rimage_icon_from_default_icon(WIcon *icon) { WScreen *scr = icon->core->screen_ptr; /* If the icon don't have image, we should use the default image. */ if (!scr->def_icon_rimage) scr->def_icon_rimage = get_default_image(scr); /* Remove the icon image */ unset_icon_image(icon); /* Set the new icon image */ icon->file_image = RRetainImage(scr->def_icon_rimage); } /* Get the RImage from the WIcon of the WWindow */ static void get_rimage_icon_from_icon_win(WIcon *icon) { RImage *image; /* Create the new RImage */ image = get_window_image_from_x11(icon->icon_win); /* Free the icon info */ unset_icon_image(icon); /* Set the new info */ icon->file_image = image; } /* Set the dockapp in the WIcon */ static void set_dockapp_in_icon(WIcon *icon) { XWindowAttributes attr; WScreen *scr = icon->core->screen_ptr; unsigned int w, h, d; /* Reparent the dock application to the icon */ /* We need the application size to center it * and show in the correct position */ getSize(icon->icon_win, &w, &h, &d); /* Set the background pixmap */ XSetWindowBackgroundPixmap(dpy, icon->core->window, scr->icon_tile_pixmap); /* Set the icon border */ XSetWindowBorderWidth(dpy, icon->icon_win, 0); /* Put the dock application in the icon */ XReparentWindow(dpy, icon->icon_win, icon->core->window, (wPreferences.icon_size - w) / 2, (wPreferences.icon_size - h) / 2); /* Show it and save */ XMapWindow(dpy, icon->icon_win); XAddToSaveSet(dpy, icon->icon_win); /* Needed to move the icon clicking on the application part */ if ((XGetWindowAttributes(dpy, icon->icon_win, &attr)) && (attr.all_event_masks & ButtonPressMask)) wHackedGrabButton(Button1, MOD_MASK, icon->core->window, True, ButtonPressMask, GrabModeSync, GrabModeAsync, None, wPreferences.cursor[WCUR_ARROW]); } /* Get the RImage from the XWindow wm_hints */ RImage *get_rimage_icon_from_wm_hints(WIcon *icon) { RImage *image = NULL; unsigned int w, h, d; WWindow *wwin; if ((!icon) || (!icon->owner)) return NULL; wwin = icon->owner; if (!getSize(wwin->wm_hints->icon_pixmap, &w, &h, &d)) { icon->owner->wm_hints->flags &= ~IconPixmapHint; return NULL; } image = get_wwindow_image_from_wmhints(wwin, icon); if (!image) return NULL; /* Resize the icon to the wPreferences.icon_size size */ - image = wIconValidateIconSize(image, wPreferences.icon_size); + image = wIconValidateIconSize(image, wPreferences.icon_size, True); return image; } /* This function updates in the screen the icon title */ static void update_icon_title(WIcon *icon) { WScreen *scr = icon->core->screen_ptr; int x, l, w; char *tmp; /* draw the icon title */ if (icon->show_title && icon->icon_name != NULL) { tmp = ShrinkString(scr->icon_title_font, icon->icon_name, wPreferences.icon_size - 4); w = WMWidthOfString(scr->icon_title_font, tmp, l = strlen(tmp)); if (w > icon->core->width - 4) x = (icon->core->width - 4) - w; else x = (icon->core->width - w) / 2; WMDrawString(scr->wmscreen, icon->core->window, scr->icon_title_color, scr->icon_title_font, x, 1, tmp, l); wfree(tmp); } } void wIconPaint(WIcon *icon) { if (!icon || !icon->core || !icon->core->screen_ptr) return; WScreen *scr = icon->core->screen_ptr; XClearWindow(dpy, icon->core->window); update_icon_title(icon); if (icon->selected) XDrawRectangle(dpy, icon->core->window, scr->icon_select_gc, 0, 0, icon->core->width - 1, icon->core->height - 1); } /******************************************************************/ static void miniwindowExpose(WObjDescriptor *desc, XEvent *event) { /* Parameter not used, but tell the compiler that it is ok */ (void) event; wIconPaint(desc->parent); } static void miniwindowDblClick(WObjDescriptor *desc, XEvent *event) { WIcon *icon = desc->parent; /* Parameter not used, but tell the compiler that it is ok */ (void) event; assert(icon->owner != NULL); wDeiconifyWindow(icon->owner); } static void miniwindowMouseDown(WObjDescriptor *desc, XEvent *event) { WIcon *icon = desc->parent; WWindow *wwin = icon->owner; XEvent ev; int x = wwin->icon_x, y = wwin->icon_y; int dx = event->xbutton.x, dy = event->xbutton.y; int grabbed = 0; int clickButton = event->xbutton.button; Bool hasMoved = False; if (WCHECK_STATE(WSTATE_MODAL)) return; if (IsDoubleClick(icon->core->screen_ptr, event)) { miniwindowDblClick(desc, event); return; } if (event->xbutton.button == Button1) { if (event->xbutton.state & MOD_MASK) wLowerFrame(icon->core); else wRaiseFrame(icon->core); if (event->xbutton.state & ShiftMask) { wIconSelect(icon); wSelectWindow(icon->owner, !wwin->flags.selected); } } else if (event->xbutton.button == Button3) { WObjDescriptor *desc; OpenMiniwindowMenu(wwin, event->xbutton.x_root, event->xbutton.y_root); /* allow drag select of menu */ desc = &wwin->screen_ptr->window_menu->menu->descriptor; event->xbutton.send_event = True; (*desc->handle_mousedown) (desc, event); return; } if (XGrabPointer(dpy, icon->core->window, False, ButtonMotionMask | ButtonReleaseMask | ButtonPressMask, GrabModeAsync, GrabModeAsync, None, None, CurrentTime) != GrabSuccess) { } while (1) { WMMaskEvent(dpy, PointerMotionMask | ButtonReleaseMask | ButtonPressMask | ButtonMotionMask | ExposureMask, &ev); switch (ev.type) { case Expose: WMHandleEvent(&ev); break; case MotionNotify: hasMoved = True; if (!grabbed) { if (abs(dx - ev.xmotion.x) >= MOVE_THRESHOLD || abs(dy - ev.xmotion.y) >= MOVE_THRESHOLD) { XChangeActivePointerGrab(dpy, ButtonMotionMask | ButtonReleaseMask | ButtonPressMask, wPreferences.cursor[WCUR_MOVE], CurrentTime); grabbed = 1; } else { break; } } x = ev.xmotion.x_root - dx; y = ev.xmotion.y_root - dy; XMoveWindow(dpy, icon->core->window, x, y); break; case ButtonPress: break; case ButtonRelease: if (ev.xbutton.button != clickButton) break; if (wwin->icon_x != x || wwin->icon_y != y) wwin->flags.icon_moved = 1; XMoveWindow(dpy, icon->core->window, x, y); wwin->icon_x = x; wwin->icon_y = y; XUngrabPointer(dpy, CurrentTime); if (wPreferences.auto_arrange_icons) wArrangeIcons(wwin->screen_ptr, True); if (wPreferences.single_click && !hasMoved) miniwindowDblClick(desc, event); return; } } } void set_icon_image_from_database(WIcon *icon, const char *wm_instance, const char *wm_class, const char *command) { char *file = NULL; file = get_icon_filename(wm_instance, wm_class, command, False); if (file) { icon->file = wstrdup(file); icon->file_image = get_rimage_from_file(icon->core->screen_ptr, icon->file, wPreferences.icon_size); wfree(file); } } diff --git a/src/icon.h b/src/icon.h index cccd7a8..49054a5 100644 --- a/src/icon.h +++ b/src/icon.h @@ -1,84 +1,84 @@ /* * Window Maker window manager * * Copyright (c) 1997-2003 Alfredo K. Kojima * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef WMICON_H_ #define WMICON_H_ #include "wcore.h" #include "window.h" #define TILE_NORMAL 0 #define TILE_CLIP 1 #define TILE_DRAWER 2 /* This is the border, in pixel, drawn around a Mini-Preview */ #define MINIPREVIEW_BORDER 1 typedef struct WIcon { WCoreWindow *core; WWindow *owner; /* owner window */ char *icon_name; /* the icon name hint */ Window icon_win; /* client suplied icon window */ char *file; /* the file with the icon image */ RImage *file_image; /* the image from the file */ unsigned int tile_type:4; unsigned int show_title:1; unsigned int selected:1; unsigned int step:3; /* selection cycle step */ unsigned int shadowed:1; /* If the icon is to be blured */ unsigned int mapped:1; unsigned int highlighted:1; Pixmap pixmap; Pixmap mini_preview; WMHandlerID handlerID; /* timer handler ID for cycling select * color */ } WIcon; WIcon *icon_create_for_dock(WScreen *scr, const char *command, const char *wm_instance, const char *wm_class, int tile); WIcon *icon_create_for_wwindow(WWindow *wwin); void set_icon_image_from_database(WIcon *icon, const char *wm_instance, const char *wm_class, const char *command); void wIconDestroy(WIcon *icon); void wIconPaint(WIcon *icon); void wIconUpdate(WIcon *icon); void wIconSelect(WIcon *icon); void wIconChangeTitle(WIcon *icon, WWindow *wwin); void update_icon_pixmap(WIcon *icon); int wIconChangeImageFile(WIcon *icon, const char *file); -RImage *wIconValidateIconSize(RImage *icon, int max_size); +RImage *wIconValidateIconSize(RImage *icon, int max_size, Bool scale_down); RImage *get_rimage_icon_from_wm_hints(WIcon *icon); char *wIconStore(WIcon *icon); char *get_name_for_instance_class(const char *wm_instance, const char *wm_class); void wIconSetHighlited(WIcon *icon, Bool flag); void set_icon_image_from_image(WIcon *icon, RImage *image); void set_icon_minipreview(WIcon *icon, RImage *image); void remove_cache_icon(char *filename); #endif /* WMICON_H_ */ diff --git a/src/switchpanel.c b/src/switchpanel.c index 5bf84da..e113f36 100644 --- a/src/switchpanel.c +++ b/src/switchpanel.c @@ -1,714 +1,714 @@ /* * Window Maker window manager * * Copyright (c) 1997-2004 Alfredo K. Kojima * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "wconfig.h" #include <stdint.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #include "WindowMaker.h" #include "screen.h" #include "framewin.h" #include "icon.h" #include "window.h" #include "defaults.h" #include "switchpanel.h" #include "misc.h" #include "xinerama.h" #ifdef USE_XSHAPE #include <X11/extensions/shape.h> #endif struct SwitchPanel { WScreen *scr; WMWindow *win; WMFrame *iconBox; WMArray *icons; WMArray *images; WMArray *windows; WMArray *flags; RImage *bg; int current; int firstVisible; int visibleCount; WMLabel *label; RImage *tileTmp; RImage *tile; WMFont *font; WMColor *white; }; /* these values will be updated whenever the switch panel * is created to to match the size defined in switch_panel_icon_size * and the selected font size */ static short int icon_size; static short int border_space; static short int icon_tile_size; static short int label_height; #define SCREEN_BORDER_SPACING 2*20 #define ICON_SELECTED (1<<1) #define ICON_DIM (1<<2) static int canReceiveFocus(WWindow *wwin) { if (wwin->frame->workspace != wwin->screen_ptr->current_workspace) return 0; if (wPreferences.cycle_active_head_only && wGetHeadForWindow(wwin) != wGetHeadForPointerLocation(wwin->screen_ptr)) return 0; if (WFLAGP(wwin, no_focusable)) return 0; if (!wwin->flags.mapped) { if (!wwin->flags.shaded && !wwin->flags.miniaturized && !wwin->flags.hidden) return 0; else return -1; } return 1; } static Bool sameWindowClass(WWindow *wwin, WWindow *curwin) { if (!wwin->wm_class || !curwin->wm_class) return False; if (strcmp(wwin->wm_class, curwin->wm_class)) return False; return True; } static void changeImage(WSwitchPanel *panel, int idecks, int selected, Bool dim, Bool force) { WMFrame *icon = NULL; RImage *image = NULL; int flags; int desired = 0; /* This whole function is a no-op if we aren't drawing the panel */ if (!wPreferences.swtileImage) return; icon = WMGetFromArray(panel->icons, idecks); image = WMGetFromArray(panel->images, idecks); flags = (int) (uintptr_t) WMGetFromArray(panel->flags, idecks); if (selected) desired |= ICON_SELECTED; if (dim) desired |= ICON_DIM; if (flags == desired && !force) return; WMReplaceInArray(panel->flags, idecks, (void *) (uintptr_t) desired); if (!panel->bg && !panel->tile && !selected) WMSetFrameRelief(icon, WRFlat); if (image && icon) { RImage *back; int opaq = (dim) ? 75 : 255; RImage *tile; WMPoint pos; Pixmap p; if (canReceiveFocus(WMGetFromArray(panel->windows, idecks)) < 0) opaq = 50; pos = WMGetViewPosition(WMWidgetView(icon)); back = panel->tileTmp; if (panel->bg) { RCopyArea(back, panel->bg, border_space + pos.x - panel->firstVisible * icon_tile_size, border_space + pos.y, back->width, back->height, 0, 0); } else { RColor color; WMScreen *wscr = WMWidgetScreen(icon); color.red = 255; color.red = WMRedComponentOfColor(WMGrayColor(wscr)) >> 8; color.green = WMGreenComponentOfColor(WMGrayColor(wscr)) >> 8; color.blue = WMBlueComponentOfColor(WMGrayColor(wscr)) >> 8; RFillImage(back, &color); } if (selected) { tile = panel->tile; RCombineArea(back, tile, 0, 0, tile->width, tile->height, (back->width - tile->width) / 2, (back->height - tile->height) / 2); } RCombineAreaWithOpaqueness(back, image, 0, 0, image->width, image->height, (back->width - image->width) / 2, (back->height - image->height) / 2, opaq); RConvertImage(panel->scr->rcontext, back, &p); XSetWindowBackgroundPixmap(dpy, WMWidgetXID(icon), p); XClearWindow(dpy, WMWidgetXID(icon)); XFreePixmap(dpy, p); } if (!panel->bg && !panel->tile && selected) WMSetFrameRelief(icon, WRSimple); } static void addIconForWindow(WSwitchPanel *panel, WMWidget *parent, WWindow *wwin, int x, int y) { WMFrame *icon = WMCreateFrame(parent); RImage *image = NULL; WMSetFrameRelief(icon, WRFlat); WMResizeWidget(icon, icon_tile_size, icon_tile_size); WMMoveWidget(icon, x, y); if (!WFLAGP(wwin, always_user_icon) && wwin->net_icon_image) image = RRetainImage(wwin->net_icon_image); /* get_icon_image() includes the default icon image */ if (!image) image = get_icon_image(panel->scr, wwin->wm_instance, wwin->wm_class, icon_tile_size); /* We must resize the icon size (~64) to the switch panel icon size (~48) */ - image = wIconValidateIconSize(image, icon_size); + image = wIconValidateIconSize(image, icon_size, False); WMAddToArray(panel->images, image); WMAddToArray(panel->icons, icon); } static void scrollIcons(WSwitchPanel *panel, int delta) { int nfirst = panel->firstVisible + delta; int i; int count = WMGetArrayItemCount(panel->windows); Bool dim; if (count <= panel->visibleCount) return; if (nfirst < 0) nfirst = 0; else if (nfirst >= count - panel->visibleCount) nfirst = count - panel->visibleCount; if (nfirst == panel->firstVisible) return; WMMoveWidget(panel->iconBox, -nfirst * icon_tile_size, 0); panel->firstVisible = nfirst; for (i = panel->firstVisible; i < panel->firstVisible + panel->visibleCount; i++) { if (i == panel->current) continue; dim = ((int) (uintptr_t) WMGetFromArray(panel->flags, i) & ICON_DIM); changeImage(panel, i, 0, dim, True); } } /* * 0 1 2 * 3 4 5 * 6 7 8 */ static RImage *assemblePuzzleImage(RImage **images, int width, int height) { RImage *img; RImage *tmp; int tw, th; RColor color; tw = width - images[0]->width - images[2]->width; th = height - images[0]->height - images[6]->height; if (tw <= 0 || th <= 0) return NULL; img = RCreateImage(width, height, 1); if (!img) return NULL; color.red = 0; color.green = 0; color.blue = 0; color.alpha = 255; RFillImage(img, &color); /* top */ tmp = RSmoothScaleImage(images[1], tw, images[1]->height); RCopyArea(img, tmp, 0, 0, tmp->width, tmp->height, images[0]->width, 0); RReleaseImage(tmp); /* bottom */ tmp = RSmoothScaleImage(images[7], tw, images[7]->height); RCopyArea(img, tmp, 0, 0, tmp->width, tmp->height, images[6]->width, height - images[6]->height); RReleaseImage(tmp); /* left */ tmp = RSmoothScaleImage(images[3], images[3]->width, th); RCopyArea(img, tmp, 0, 0, tmp->width, tmp->height, 0, images[0]->height); RReleaseImage(tmp); /* right */ tmp = RSmoothScaleImage(images[5], images[5]->width, th); RCopyArea(img, tmp, 0, 0, tmp->width, tmp->height, width - images[5]->width, images[2]->height); RReleaseImage(tmp); /* center */ tmp = RSmoothScaleImage(images[4], tw, th); RCopyArea(img, tmp, 0, 0, tmp->width, tmp->height, images[0]->width, images[0]->height); RReleaseImage(tmp); /* corners */ RCopyArea(img, images[0], 0, 0, images[0]->width, images[0]->height, 0, 0); RCopyArea(img, images[2], 0, 0, images[2]->width, images[2]->height, width - images[2]->width, 0); RCopyArea(img, images[6], 0, 0, images[6]->width, images[6]->height, 0, height - images[6]->height); RCopyArea(img, images[8], 0, 0, images[8]->width, images[8]->height, width - images[8]->width, height - images[8]->height); return img; } static RImage *createBackImage(int width, int height) { return assemblePuzzleImage(wPreferences.swbackImage, width, height); } static RImage *getTile(void) { RImage *stile; if (!wPreferences.swtileImage) return NULL; stile = RScaleImage(wPreferences.swtileImage, icon_tile_size, icon_tile_size); if (!stile) return wPreferences.swtileImage; return stile; } static void drawTitle(WSwitchPanel *panel, int idecks, const char *title) { char *ntitle; int width = WMWidgetWidth(panel->win); int x; if (title) ntitle = ShrinkString(panel->font, title, width - 2 * border_space); else ntitle = NULL; if (panel->bg) { if (ntitle) { if (strcmp(ntitle, title) != 0) { x = border_space; } else { int w = WMWidthOfString(panel->font, ntitle, strlen(ntitle)); x = border_space + (idecks - panel->firstVisible) * icon_tile_size+ icon_tile_size/ 2 - w / 2; if (x < border_space) x = border_space; else if (x + w > width - border_space) x = width - border_space - w; } } XClearWindow(dpy, WMWidgetXID(panel->win)); if (ntitle) WMDrawString(panel->scr->wmscreen, WMWidgetXID(panel->win), panel->white, panel->font, x, WMWidgetHeight(panel->win) - border_space - label_height + WMFontHeight(panel->font) / 2, ntitle, strlen(ntitle)); } else { if (ntitle) WMSetLabelText(panel->label, ntitle); } if (ntitle) free(ntitle); } static WMArray *makeWindowListArray(WScreen *scr, int include_unmapped, Bool class_only) { WMArray *windows = WMCreateArray(10); WWindow *wwin = scr->focused_window; while (wwin) { if ((canReceiveFocus(wwin) != 0) && (wwin->flags.mapped || wwin->flags.shaded || include_unmapped)) { if (class_only) if (!sameWindowClass(scr->focused_window, wwin)) { wwin = wwin->prev; continue; } if (!WFLAGP(wwin, skip_switchpanel)) WMAddToArray(windows, wwin); } wwin = wwin->prev; } return windows; } static WMArray *makeWindowFlagsArray(int count) { WMArray *flags = WMCreateArray(count); int i; for (i = 0; i < count; i++) WMAddToArray(flags, (void *) 0); return flags; } WSwitchPanel *wInitSwitchPanel(WScreen *scr, WWindow *curwin, Bool class_only) { int wmScaleWidth, wmScaleHeight; WMGetScaleBaseFromSystemFont(scr->wmscreen, &wmScaleWidth, &wmScaleHeight); icon_size = wPreferences.switch_panel_icon_size; icon_tile_size = (short int)(((float)icon_size * (float)1.2) + 0.5); border_space = WMScaleY(10); label_height = WMScaleY(25); WWindow *wwin; WSwitchPanel *panel = wmalloc(sizeof(WSwitchPanel)); WMFrame *viewport; int i, width, height, iconsThatFitCount, count; WMRect rect = wGetRectForHead(scr, wGetHeadForPointerLocation(scr)); panel->scr = scr; panel->windows = makeWindowListArray(scr, wPreferences.swtileImage != NULL, class_only); count = WMGetArrayItemCount(panel->windows); if (count) panel->flags = makeWindowFlagsArray(count); if (count == 0) { WMFreeArray(panel->windows); wfree(panel); return NULL; } width = icon_tile_size* count; iconsThatFitCount = count; if (width > (int)rect.size.width) { iconsThatFitCount = (rect.size.width - SCREEN_BORDER_SPACING) / icon_tile_size; width = iconsThatFitCount * icon_tile_size; } panel->visibleCount = iconsThatFitCount; if (!wPreferences.swtileImage) return panel; height = label_height + icon_tile_size; panel->tileTmp = RCreateImage(icon_tile_size, icon_tile_size, 1); panel->tile = getTile(); if (panel->tile && wPreferences.swbackImage[8]) panel->bg = createBackImage(width + 2 * border_space, height + 2 * border_space); if (!panel->tileTmp || !panel->tile) { if (panel->bg) RReleaseImage(panel->bg); panel->bg = NULL; if (panel->tile) RReleaseImage(panel->tile); panel->tile = NULL; if (panel->tileTmp) RReleaseImage(panel->tileTmp); panel->tileTmp = NULL; } panel->white = WMWhiteColor(scr->wmscreen); panel->font = WMBoldSystemFontOfSize(scr->wmscreen, WMScaleY(12)); panel->icons = WMCreateArray(count); panel->images = WMCreateArray(count); panel->win = WMCreateWindow(scr->wmscreen, ""); if (!panel->bg) { WMFrame *frame = WMCreateFrame(panel->win); WMColor *darkGray = WMDarkGrayColor(scr->wmscreen); WMSetFrameRelief(frame, WRSimple); WMSetViewExpandsToParent(WMWidgetView(frame), 0, 0, 0, 0); panel->label = WMCreateLabel(panel->win); WMResizeWidget(panel->label, width, label_height); WMMoveWidget(panel->label, border_space, border_space + icon_tile_size+ 5); WMSetLabelRelief(panel->label, WRSimple); WMSetWidgetBackgroundColor(panel->label, darkGray); WMSetLabelFont(panel->label, panel->font); WMSetLabelTextColor(panel->label, panel->white); WMReleaseColor(darkGray); height += 5; } WMResizeWidget(panel->win, width + 2 * border_space, height + 2 * border_space); viewport = WMCreateFrame(panel->win); WMResizeWidget(viewport, width, icon_tile_size); WMMoveWidget(viewport, border_space, border_space); WMSetFrameRelief(viewport, WRFlat); panel->iconBox = WMCreateFrame(viewport); WMMoveWidget(panel->iconBox, 0, 0); WMResizeWidget(panel->iconBox, icon_tile_size* count, icon_tile_size); WMSetFrameRelief(panel->iconBox, WRFlat); WM_ITERATE_ARRAY(panel->windows, wwin, i) { addIconForWindow(panel, panel->iconBox, wwin, i * icon_tile_size, 0); } WMMapSubwidgets(panel->win); WMRealizeWidget(panel->win); WM_ITERATE_ARRAY(panel->windows, wwin, i) { changeImage(panel, i, 0, False, True); } if (panel->bg) { Pixmap pixmap, mask; RConvertImageMask(scr->rcontext, panel->bg, &pixmap, &mask, 250); XSetWindowBackgroundPixmap(dpy, WMWidgetXID(panel->win), pixmap); #ifdef USE_XSHAPE if (mask && w_global.xext.shape.supported) XShapeCombineMask(dpy, WMWidgetXID(panel->win), ShapeBounding, 0, 0, mask, ShapeSet); #endif if (pixmap) XFreePixmap(dpy, pixmap); if (mask) XFreePixmap(dpy, mask); } { WMPoint center; center = wGetPointToCenterRectInHead(scr, wGetHeadForPointerLocation(scr), width + 2 * border_space, height + 2 * border_space); WMMoveWidget(panel->win, center.x, center.y); } panel->current = WMGetFirstInArray(panel->windows, curwin); if (panel->current >= 0) changeImage(panel, panel->current, 1, False, False); WMMapWidget(panel->win); return panel; } void wSwitchPanelDestroy(WSwitchPanel *panel) { int i; RImage *image; if (panel->win) { Window info_win = panel->scr->info_window; XEvent ev; ev.xclient.type = ClientMessage; ev.xclient.message_type = w_global.atom.wm.ignore_focus_events; ev.xclient.format = 32; ev.xclient.data.l[0] = True; XSendEvent(dpy, info_win, True, EnterWindowMask, &ev); WMUnmapWidget(panel->win); ev.xclient.data.l[0] = False; XSendEvent(dpy, info_win, True, EnterWindowMask, &ev); } if (panel->images) { WM_ITERATE_ARRAY(panel->images, image, i) { if (image) RReleaseImage(image); } WMFreeArray(panel->images); } if (panel->win) WMDestroyWidget(panel->win); if (panel->icons) WMFreeArray(panel->icons); if (panel->flags) WMFreeArray(panel->flags); WMFreeArray(panel->windows); if (panel->tile) RReleaseImage(panel->tile); if (panel->tileTmp) RReleaseImage(panel->tileTmp); if (panel->bg) RReleaseImage(panel->bg); if (panel->font) WMReleaseFont(panel->font); if (panel->white) WMReleaseColor(panel->white); wfree(panel); } WWindow *wSwitchPanelSelectNext(WSwitchPanel *panel, int back, int ignore_minimized, Bool class_only) { WWindow *wwin, *curwin, *tmpwin; int count = WMGetArrayItemCount(panel->windows); int orig = panel->current; int i; Bool dim = False; if (count == 0) return NULL; if (!wPreferences.cycle_ignore_minimized) ignore_minimized = False; if (ignore_minimized && canReceiveFocus(WMGetFromArray(panel->windows, (count + panel->current) % count)) < 0) ignore_minimized = False; curwin = WMGetFromArray(panel->windows, orig); do { do { if (back) panel->current--; else panel->current++; panel->current = (count + panel->current) % count; wwin = WMGetFromArray(panel->windows, panel->current); if (!class_only) break; if (panel->current == orig) break; } while (!sameWindowClass(wwin, curwin)); } while (ignore_minimized && panel->current != orig && canReceiveFocus(wwin) < 0); WM_ITERATE_ARRAY(panel->windows, tmpwin, i) { if (i == panel->current) continue; if (!class_only || sameWindowClass(tmpwin, curwin)) changeImage(panel, i, 0, False, False); else { if (i == orig) dim = True; changeImage(panel, i, 0, True, False); } } if (panel->current < panel->firstVisible) scrollIcons(panel, panel->current - panel->firstVisible); else if (panel->current - panel->firstVisible >= panel->visibleCount) scrollIcons(panel, panel->current - panel->firstVisible - panel->visibleCount + 1); if (panel->win) { drawTitle(panel, panel->current, wwin->frame->title); if (panel->current != orig) changeImage(panel, orig, 0, dim, False); changeImage(panel, panel->current, 1, False, False); } return wwin; } WWindow *wSwitchPanelSelectFirst(WSwitchPanel *panel, int back) { WWindow *wwin; int count = WMGetArrayItemCount(panel->windows); char *title; int i; if (count == 0) return NULL; if (back) { panel->current = count - 1; scrollIcons(panel, count); } else { panel->current = 0; scrollIcons(panel, -count); } wwin = WMGetFromArray(panel->windows, panel->current); title = wwin->frame->title; if (panel->win) { for (WMArrayFirst(panel->windows, &(i)); (i) != WANotFound; WMArrayNext(panel->windows, &(i))) changeImage(panel, i, i == panel->current, False, False); drawTitle(panel, panel->current, title); } return wwin; } WWindow *wSwitchPanelHandleEvent(WSwitchPanel *panel, XEvent *event) { WMFrame *icon; int i; int focus = -1; if (!panel->win) return NULL; if (event->type == MotionNotify) { WM_ITERATE_ARRAY(panel->icons, icon, i) { if (WMWidgetXID(icon) == event->xmotion.window) { focus = i; break; } } } if (focus >= 0 && panel->current != focus) { WWindow *wwin; WM_ITERATE_ARRAY(panel->windows, wwin, i) { changeImage(panel, i, i == focus, False, False); } panel->current = focus; diff --git a/src/wdefaults.c b/src/wdefaults.c index 7aad3db..0bb476b 100644 --- a/src/wdefaults.c +++ b/src/wdefaults.c @@ -1,678 +1,678 @@ /* wdefaults.c - window specific defaults * * Window Maker window manager * * Copyright (c) 1997-2003 Alfredo K. Kojima * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "wconfig.h" #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <strings.h> #include <ctype.h> #include <X11/Xlib.h> #include <X11/Xutil.h> #include <X11/keysym.h> #include <wraster.h> #include "WindowMaker.h" #include "window.h" #include "appicon.h" #include "screen.h" #include "workspace.h" #include "defaults.h" #include "icon.h" #include "misc.h" #define APPLY_VAL(value, flag, attrib) \ if (value) {attr->flag = getBool(attrib, value); \ if (mask) mask->flag = 1;} /* Local stuff */ /* type converters */ static int getBool(WMPropList *, WMPropList *); static char *getString(WMPropList *, WMPropList *); static WMPropList *ANoTitlebar = NULL; static WMPropList *ANoResizebar; static WMPropList *ANoMiniaturizeButton; static WMPropList *ANoMiniaturizable; static WMPropList *ANoCloseButton; static WMPropList *ANoBorder; static WMPropList *ANoHideOthers; static WMPropList *ANoMouseBindings; static WMPropList *ANoKeyBindings; static WMPropList *ANoAppIcon; /* app */ static WMPropList *AKeepOnTop; static WMPropList *AKeepOnBottom; static WMPropList *AOmnipresent; static WMPropList *ASkipWindowList; static WMPropList *ASkipSwitchPanel; static WMPropList *AKeepInsideScreen; static WMPropList *AUnfocusable; static WMPropList *AAlwaysUserIcon; static WMPropList *AStartMiniaturized; static WMPropList *AStartMaximized; static WMPropList *AStartHidden; /* app */ static WMPropList *ADontSaveSession; /* app */ static WMPropList *AEmulateAppIcon; static WMPropList *AFocusAcrossWorkspace; static WMPropList *AFullMaximize; static WMPropList *ASharedAppIcon; /* app */ #ifdef XKB_BUTTON_HINT static WMPropList *ANoLanguageButton; #endif static WMPropList *AStartWorkspace; static WMPropList *AIgnoreDecorationChanges; static WMPropList *AIcon; static WMPropList *AnyWindow; static WMPropList *No; static void init_wdefaults(void) { AIcon = WMCreatePLString("Icon"); ANoTitlebar = WMCreatePLString("NoTitlebar"); ANoResizebar = WMCreatePLString("NoResizebar"); ANoMiniaturizeButton = WMCreatePLString("NoMiniaturizeButton"); ANoMiniaturizable = WMCreatePLString("NoMiniaturizable"); ANoCloseButton = WMCreatePLString("NoCloseButton"); ANoBorder = WMCreatePLString("NoBorder"); ANoHideOthers = WMCreatePLString("NoHideOthers"); ANoMouseBindings = WMCreatePLString("NoMouseBindings"); ANoKeyBindings = WMCreatePLString("NoKeyBindings"); ANoAppIcon = WMCreatePLString("NoAppIcon"); AKeepOnTop = WMCreatePLString("KeepOnTop"); AKeepOnBottom = WMCreatePLString("KeepOnBottom"); AOmnipresent = WMCreatePLString("Omnipresent"); ASkipWindowList = WMCreatePLString("SkipWindowList"); ASkipSwitchPanel = WMCreatePLString("SkipSwitchPanel"); AKeepInsideScreen = WMCreatePLString("KeepInsideScreen"); AUnfocusable = WMCreatePLString("Unfocusable"); AAlwaysUserIcon = WMCreatePLString("AlwaysUserIcon"); AStartMiniaturized = WMCreatePLString("StartMiniaturized"); AStartHidden = WMCreatePLString("StartHidden"); AStartMaximized = WMCreatePLString("StartMaximized"); ADontSaveSession = WMCreatePLString("DontSaveSession"); AEmulateAppIcon = WMCreatePLString("EmulateAppIcon"); AFocusAcrossWorkspace = WMCreatePLString("FocusAcrossWorkspace"); AFullMaximize = WMCreatePLString("FullMaximize"); ASharedAppIcon = WMCreatePLString("SharedAppIcon"); #ifdef XKB_BUTTON_HINT ANoLanguageButton = WMCreatePLString("NoLanguageButton"); #endif AStartWorkspace = WMCreatePLString("StartWorkspace"); AIgnoreDecorationChanges = WMCreatePLString("IgnoreDecorationChanges"); AnyWindow = WMCreatePLString("*"); No = WMCreatePLString("No"); } /* Returns the correct WMPropList, using instance+class or instance, or class, or default */ static WMPropList *get_value(WMPropList * dict_win, WMPropList * dict_class, WMPropList * dict_name, WMPropList * dict_any, WMPropList * option, WMPropList * default_value, Bool useGlobalDefault) { WMPropList *value; if (dict_win) { value = WMGetFromPLDictionary(dict_win, option); if (value) return value; } if (dict_name) { value = WMGetFromPLDictionary(dict_name, option); if (value) return value; } if (dict_class) { value = WMGetFromPLDictionary(dict_class, option); if (value) return value; } if (!useGlobalDefault) return NULL; if (dict_any) { value = WMGetFromPLDictionary(dict_any, option); if (value) return value; } return default_value; } static WMPropList *get_value_from_instanceclass(const char *value) { WMPropList *key, *val = NULL; if (!value) return NULL; key = WMCreatePLString(value); WMPLSetCaseSensitive(True); if (w_global.domain.window_attr->dictionary) val = key ? WMGetFromPLDictionary(w_global.domain.window_attr->dictionary, key) : NULL; if (key) WMReleasePropList(key); WMPLSetCaseSensitive(False); return val; } /* *---------------------------------------------------------------------- * wDefaultFillAttributes-- * Retrieves attributes for the specified instance/class and * fills attr with it. Values that are actually defined are also * set in mask. If useGlobalDefault is True, the default for * all windows ("*") will be used for when no values are found * for that instance/class. * *---------------------------------------------------------------------- */ void wDefaultFillAttributes(const char *instance, const char *class, WWindowAttributes *attr, WWindowAttributes *mask, Bool useGlobalDefault) { WMPropList *value, *dw, *dc, *dn, *da; char *buffer; dw = dc = dn = da = NULL; if (!ANoTitlebar) init_wdefaults(); if (class && instance) { buffer = StrConcatDot(instance, class); dw = get_value_from_instanceclass(buffer); wfree(buffer); } dn = get_value_from_instanceclass(instance); dc = get_value_from_instanceclass(class); WMPLSetCaseSensitive(True); if ((w_global.domain.window_attr->dictionary) && (useGlobalDefault)) da = WMGetFromPLDictionary(w_global.domain.window_attr->dictionary, AnyWindow); /* get the data */ value = get_value(dw, dc, dn, da, ANoTitlebar, No, useGlobalDefault); APPLY_VAL(value, no_titlebar, ANoTitlebar); value = get_value(dw, dc, dn, da, ANoResizebar, No, useGlobalDefault); APPLY_VAL(value, no_resizebar, ANoResizebar); value = get_value(dw, dc, dn, da, ANoMiniaturizeButton, No, useGlobalDefault); APPLY_VAL(value, no_miniaturize_button, ANoMiniaturizeButton); value = get_value(dw, dc, dn, da, ANoMiniaturizable, No, useGlobalDefault); APPLY_VAL(value, no_miniaturizable, ANoMiniaturizable); value = get_value(dw, dc, dn, da, ANoCloseButton, No, useGlobalDefault); APPLY_VAL(value, no_close_button, ANoCloseButton); value = get_value(dw, dc, dn, da, ANoBorder, No, useGlobalDefault); APPLY_VAL(value, no_border, ANoBorder); value = get_value(dw, dc, dn, da, ANoHideOthers, No, useGlobalDefault); APPLY_VAL(value, no_hide_others, ANoHideOthers); value = get_value(dw, dc, dn, da, ANoMouseBindings, No, useGlobalDefault); APPLY_VAL(value, no_bind_mouse, ANoMouseBindings); value = get_value(dw, dc, dn, da, ANoKeyBindings, No, useGlobalDefault); APPLY_VAL(value, no_bind_keys, ANoKeyBindings); value = get_value(dw, dc, dn, da, ANoAppIcon, No, useGlobalDefault); APPLY_VAL(value, no_appicon, ANoAppIcon); value = get_value(dw, dc, dn, da, ASharedAppIcon, No, useGlobalDefault); APPLY_VAL(value, shared_appicon, ASharedAppIcon); value = get_value(dw, dc, dn, da, AKeepOnTop, No, useGlobalDefault); APPLY_VAL(value, floating, AKeepOnTop); value = get_value(dw, dc, dn, da, AKeepOnBottom, No, useGlobalDefault); APPLY_VAL(value, sunken, AKeepOnBottom); value = get_value(dw, dc, dn, da, AOmnipresent, No, useGlobalDefault); APPLY_VAL(value, omnipresent, AOmnipresent); value = get_value(dw, dc, dn, da, ASkipWindowList, No, useGlobalDefault); APPLY_VAL(value, skip_window_list, ASkipWindowList); value = get_value(dw, dc, dn, da, ASkipSwitchPanel, No, useGlobalDefault); APPLY_VAL(value, skip_switchpanel, ASkipSwitchPanel); value = get_value(dw, dc, dn, da, AKeepInsideScreen, No, useGlobalDefault); APPLY_VAL(value, dont_move_off, AKeepInsideScreen); value = get_value(dw, dc, dn, da, AUnfocusable, No, useGlobalDefault); APPLY_VAL(value, no_focusable, AUnfocusable); value = get_value(dw, dc, dn, da, AAlwaysUserIcon, No, useGlobalDefault); APPLY_VAL(value, always_user_icon, AAlwaysUserIcon); value = get_value(dw, dc, dn, da, AStartMiniaturized, No, useGlobalDefault); APPLY_VAL(value, start_miniaturized, AStartMiniaturized); value = get_value(dw, dc, dn, da, AStartHidden, No, useGlobalDefault); APPLY_VAL(value, start_hidden, AStartHidden); value = get_value(dw, dc, dn, da, AStartMaximized, No, useGlobalDefault); APPLY_VAL(value, start_maximized, AStartMaximized); value = get_value(dw, dc, dn, da, ADontSaveSession, No, useGlobalDefault); APPLY_VAL(value, dont_save_session, ADontSaveSession); value = get_value(dw, dc, dn, da, AEmulateAppIcon, No, useGlobalDefault); APPLY_VAL(value, emulate_appicon, AEmulateAppIcon); value = get_value(dw, dc, dn, da, AFocusAcrossWorkspace, No, useGlobalDefault); APPLY_VAL(value, focus_across_wksp, AFocusAcrossWorkspace); value = get_value(dw, dc, dn, da, AFullMaximize, No, useGlobalDefault); APPLY_VAL(value, full_maximize, AFullMaximize); value = get_value(dw, dc, dn, da, AIgnoreDecorationChanges, No, useGlobalDefault); APPLY_VAL(value, ignore_decoration_changes, AIgnoreDecorationChanges); #ifdef XKB_BUTTON_HINT value = get_value(dw, dc, dn, da, ANoLanguageButton, No, useGlobalDefault); APPLY_VAL(value, no_language_button, ANoLanguageButton); #endif /* clean up */ WMPLSetCaseSensitive(False); } static WMPropList *get_generic_value(const char *instance, const char *class, WMPropList *option, Bool default_icon) { WMPropList *value, *key, *dict; value = NULL; WMPLSetCaseSensitive(True); /* Search the icon name using class and instance */ if (class && instance) { char *buffer; buffer = wmalloc(strlen(class) + strlen(instance) + 2); sprintf(buffer, "%s.%s", instance, class); key = WMCreatePLString(buffer); wfree(buffer); dict = WMGetFromPLDictionary(w_global.domain.window_attr->dictionary, key); WMReleasePropList(key); if (dict) value = WMGetFromPLDictionary(dict, option); } /* Search the icon name using instance */ if (!value && instance) { key = WMCreatePLString(instance); dict = WMGetFromPLDictionary(w_global.domain.window_attr->dictionary, key); WMReleasePropList(key); if (dict) value = WMGetFromPLDictionary(dict, option); } /* Search the icon name using class */ if (!value && class) { key = WMCreatePLString(class); dict = WMGetFromPLDictionary(w_global.domain.window_attr->dictionary, key); WMReleasePropList(key); if (dict) value = WMGetFromPLDictionary(dict, option); } /* Search the default icon name - See default_icon argument! */ if (!value && default_icon) { /* AnyWindow is "*" - see wdefaults.c */ dict = WMGetFromPLDictionary(w_global.domain.window_attr->dictionary, AnyWindow); if (dict) value = WMGetFromPLDictionary(dict, option); } WMPLSetCaseSensitive(False); return value; } /* Get the file name of the image, using instance and class */ char *get_icon_filename(const char *winstance, const char *wclass, const char *command, Bool default_icon) { char *file_name; char *file_path; /* Get the file name of the image, using instance and class */ file_name = wDefaultGetIconFile(winstance, wclass, default_icon); /* Check if the file really exists in the disk */ if (file_name) file_path = FindImage(wPreferences.icon_path, file_name); else file_path = NULL; /* If the specific icon filename is not found, and command is specified, * then include the .app icons and re-do the search. */ if (!file_path && command) { wApplicationExtractDirPackIcon(command, winstance, wclass); file_name = wDefaultGetIconFile(winstance, wclass, False); if (file_name) { file_path = FindImage(wPreferences.icon_path, file_name); if (!file_path) wwarning(_("icon \"%s\" doesn't exist, check your config files"), file_name); /* FIXME: Here, if file_path does not exist then the icon is still in the * "icon database" (w_global.domain.window_attr->dictionary), but the file * for the icon is no more on disk. Therefore, we should remove it from the * database. Is possible to do that using wDefaultChangeIcon() */ } } /* * Don't wfree(file_name) because it is a direct pointer inside the icon * dictionary (w_global.domain.window_attr->dictionary) and not a result * allocated with wstrdup() */ if (!file_path && default_icon) file_path = get_default_image_path(); return file_path; } /* This function returns the image picture for the file_name file */ RImage *get_rimage_from_file(WScreen *scr, const char *file_name, int max_size) { RImage *image = NULL; if (!file_name) return NULL; image = RLoadImage(scr->rcontext, file_name, 0); if (!image) wwarning(_("error loading image file \"%s\": %s"), file_name, RMessageForError(RErrorCode)); - image = wIconValidateIconSize(image, max_size); + image = wIconValidateIconSize(image, max_size, False); return image; } /* This function returns the default icon's full path * If the path for an icon is not found, returns NULL */ char *get_default_image_path(void) { char *path = NULL, *file = NULL; /* Get the default icon */ file = wDefaultGetIconFile(NULL, NULL, True); if (file) path = FindImage(wPreferences.icon_path, file); return path; } /* This function creates the RImage using the default icon */ RImage *get_default_image(WScreen *scr) { RImage *image = NULL; char *path = NULL; /* Get the filename full path */ path = get_default_image_path(); if (!path) return NULL; /* Get the default icon */ image = get_rimage_from_file(scr, path, wPreferences.icon_size); if (!image) wwarning(_("could not find default icon \"%s\""), path); /* Resize the icon to the wPreferences.icon_size size * usually this function will return early, because size is right */ - image = wIconValidateIconSize(image, wPreferences.icon_size); + image = wIconValidateIconSize(image, wPreferences.icon_size, False); return image; } RImage *get_icon_image(WScreen *scr, const char *winstance, const char *wclass, int max_size) { char *file_name = NULL; /* Get the file name of the image, using instance and class */ file_name = get_icon_filename(winstance, wclass, NULL, True); return get_rimage_from_file(scr, file_name, max_size); } int wDefaultGetStartWorkspace(WScreen *scr, const char *instance, const char *class) { WMPropList *value; int w; char *tmp; if (!ANoTitlebar) init_wdefaults(); if (!w_global.domain.window_attr->dictionary) return -1; value = get_generic_value(instance, class, AStartWorkspace, True); if (!value) return -1; tmp = getString(AStartWorkspace, value); if (!tmp || strlen(tmp) == 0) return -1; /* Get the workspace number for the workspace name */ w = wGetWorkspaceNumber(scr, tmp); return w; } /* Get the name of the Icon File. If default_icon is True, then, default value included */ char *wDefaultGetIconFile(const char *instance, const char *class, Bool default_icon) { WMPropList *value; char *tmp; if (!ANoTitlebar) init_wdefaults(); if (!w_global.domain.window_attr || !w_global.domain.window_attr->dictionary) return NULL; value = get_generic_value(instance, class, AIcon, default_icon); if (!value) return NULL; tmp = getString(AIcon, value); return tmp; } void wDefaultChangeIcon(const char *instance, const char *class, const char *file) { WDDomain *db = w_global.domain.window_attr; WMPropList *icon_value = NULL, *value, *attr, *key, *def_win, *def_icon = NULL; WMPropList *dict = db->dictionary; int same = 0; if (!dict) { dict = WMCreatePLDictionary(NULL, NULL); if (dict) db->dictionary = dict; else return; } WMPLSetCaseSensitive(True); if (instance && class) { char *buffer; buffer = StrConcatDot(instance, class); key = WMCreatePLString(buffer); wfree(buffer); } else if (instance) { key = WMCreatePLString(instance); } else if (class) { key = WMCreatePLString(class); } else { key = WMRetainPropList(AnyWindow); } if (file) { value = WMCreatePLString(file); icon_value = WMCreatePLDictionary(AIcon, value, NULL); WMReleasePropList(value); def_win = WMGetFromPLDictionary(dict, AnyWindow); if (def_win != NULL) def_icon = WMGetFromPLDictionary(def_win, AIcon); if (def_icon && !strcmp(WMGetFromPLString(def_icon), file)) same = 1; } attr = WMGetFromPLDictionary(dict, key); if (attr != NULL) { if (WMIsPLDictionary(attr)) { if (icon_value != NULL && !same) WMMergePLDictionaries(attr, icon_value, False); else WMRemoveFromPLDictionary(attr, AIcon); } } else if (icon_value != NULL && !same) { WMPutInPLDictionary(dict, key, icon_value); } if (!wPreferences.flags.noupdates) UpdateDomainFile(db); WMReleasePropList(key); if (icon_value) WMReleasePropList(icon_value); WMPLSetCaseSensitive(False); } void wDefaultPurgeInfo(const char *instance, const char *class) { WMPropList *value, *key, *dict; char *buffer; if (!AIcon) { /* Unnecessary precaution */ init_wdefaults(); } WMPLSetCaseSensitive(True); buffer = wmalloc(strlen(class) + strlen(instance) + 2); sprintf(buffer, "%s.%s", instance, class); key = WMCreatePLString(buffer); dict = WMGetFromPLDictionary(w_global.domain.window_attr->dictionary, key); if (dict) { value = WMGetFromPLDictionary(dict, AIcon); if (value) { WMRemoveFromPLDictionary(dict, AIcon); } WMRemoveFromPLDictionary(w_global.domain.window_attr->dictionary, key); UpdateDomainFile(w_global.domain.window_attr); } wfree(buffer); WMReleasePropList(key); WMPLSetCaseSensitive(False); } /* --------------------------- Local ----------------------- */ static int getBool(WMPropList * key, WMPropList * value) { char *val; if (!WMIsPLString(value)) { wwarning(_("Wrong option format for key \"%s\". Should be %s."), WMGetFromPLString(key), "Boolean"); return 0; } val = WMGetFromPLString(value); if ((val[1] == '\0' && (val[0] == 'y' || val[0] == 'Y' || val[0] == 'T' || val[0] == 't' || val[0] == '1')) || (strcasecmp(val, "YES") == 0 || strcasecmp(val, "TRUE") == 0)) { return 1; } else if ((val[1] == '\0' && (val[0] == 'n' || val[0] == 'N' || val[0] == 'F' || val[0] == 'f' || val[0] == '0')) || (strcasecmp(val, "NO") == 0 || strcasecmp(val, "FALSE") == 0)) { return 0; } else { wwarning(_("can't convert \"%s\" to boolean"), val); /* We return False if we can't convert to BOOLEAN. * This is because all options defaults to False. * -1 is not checked and thus is interpreted as True, * which is not good.*/ return 0; } } /* WARNING: Do not free the value returned by this function!! */ static char *getString(WMPropList * key, WMPropList * value) { if (!WMIsPLString(value)) { wwarning(_("Wrong option format for key \"%s\". Should be %s."), WMGetFromPLString(key), "String"); return NULL; } return WMGetFromPLString(value); } diff --git a/src/wmspec.c b/src/wmspec.c index 64eaa05..af29d5d 100644 --- a/src/wmspec.c +++ b/src/wmspec.c @@ -27,1025 +27,1025 @@ * proper checks need to be made on the returned values. Only checking for * return to be Success is not enough. -Dan */ #include "wconfig.h" #include <X11/Xlib.h> #include <X11/Xatom.h> #include <string.h> #include <WINGs/WUtil.h> #include "WindowMaker.h" #include "window.h" #include "screen.h" #include "workspace.h" #include "framewin.h" #include "actions.h" #include "client.h" #include "appicon.h" #include "wmspec.h" #include "icon.h" #include "stacking.h" #include "xinerama.h" #include "properties.h" /* Root Window Properties */ static Atom net_supported; static Atom net_client_list; static Atom net_client_list_stacking; static Atom net_number_of_desktops; static Atom net_desktop_geometry; static Atom net_desktop_viewport; static Atom net_current_desktop; static Atom net_desktop_names; static Atom net_active_window; static Atom net_workarea; static Atom net_supporting_wm_check; static Atom net_virtual_roots; /* N/A */ static Atom net_desktop_layout; /* XXX */ static Atom net_showing_desktop; /* Other Root Window Messages */ static Atom net_close_window; static Atom net_moveresize_window; /* TODO */ static Atom net_wm_moveresize; /* TODO */ /* Application Window Properties */ static Atom net_wm_name; static Atom net_wm_visible_name; /* TODO (unnecessary?) */ static Atom net_wm_icon_name; static Atom net_wm_visible_icon_name; /* TODO (unnecessary?) */ static Atom net_wm_desktop; static Atom net_wm_window_type; static Atom net_wm_window_type_desktop; static Atom net_wm_window_type_dock; static Atom net_wm_window_type_toolbar; static Atom net_wm_window_type_menu; static Atom net_wm_window_type_utility; static Atom net_wm_window_type_splash; static Atom net_wm_window_type_dialog; static Atom net_wm_window_type_dropdown_menu; static Atom net_wm_window_type_popup_menu; static Atom net_wm_window_type_tooltip; static Atom net_wm_window_type_notification; static Atom net_wm_window_type_combo; static Atom net_wm_window_type_dnd; static Atom net_wm_window_type_normal; static Atom net_wm_state; static Atom net_wm_state_modal; /* XXX: what is this?!? */ static Atom net_wm_state_sticky; static Atom net_wm_state_maximized_vert; static Atom net_wm_state_maximized_horz; static Atom net_wm_state_shaded; static Atom net_wm_state_skip_taskbar; static Atom net_wm_state_skip_pager; static Atom net_wm_state_hidden; static Atom net_wm_state_fullscreen; static Atom net_wm_state_above; static Atom net_wm_state_below; static Atom net_wm_state_focused; static Atom net_wm_allowed_actions; static Atom net_wm_action_move; static Atom net_wm_action_resize; static Atom net_wm_action_minimize; static Atom net_wm_action_shade; static Atom net_wm_action_stick; static Atom net_wm_action_maximize_horz; static Atom net_wm_action_maximize_vert; static Atom net_wm_action_fullscreen; static Atom net_wm_action_change_desktop; static Atom net_wm_action_close; static Atom net_wm_strut; static Atom net_wm_strut_partial; /* TODO: doesn't really fit into the current strut scheme */ static Atom net_wm_icon_geometry; /* FIXME: should work together with net_wm_handled_icons, gnome-panel-2.2.0.1 doesn't use _NET_WM_HANDLED_ICONS, thus present situation. */ static Atom net_wm_icon; static Atom net_wm_pid; /* TODO */ static Atom net_wm_handled_icons; /* FIXME: see net_wm_icon_geometry */ static Atom net_wm_window_opacity; static Atom net_frame_extents; /* Window Manager Protocols */ static Atom net_wm_ping; /* TODO */ static Atom utf8_string; typedef struct { char *name; Atom *atom; } atomitem_t; static atomitem_t atomNames[] = { {"_NET_SUPPORTED", &net_supported}, {"_NET_CLIENT_LIST", &net_client_list}, {"_NET_CLIENT_LIST_STACKING", &net_client_list_stacking}, {"_NET_NUMBER_OF_DESKTOPS", &net_number_of_desktops}, {"_NET_DESKTOP_GEOMETRY", &net_desktop_geometry}, {"_NET_DESKTOP_VIEWPORT", &net_desktop_viewport}, {"_NET_CURRENT_DESKTOP", &net_current_desktop}, {"_NET_DESKTOP_NAMES", &net_desktop_names}, {"_NET_ACTIVE_WINDOW", &net_active_window}, {"_NET_WORKAREA", &net_workarea}, {"_NET_SUPPORTING_WM_CHECK", &net_supporting_wm_check}, {"_NET_VIRTUAL_ROOTS", &net_virtual_roots}, {"_NET_DESKTOP_LAYOUT", &net_desktop_layout}, {"_NET_SHOWING_DESKTOP", &net_showing_desktop}, {"_NET_CLOSE_WINDOW", &net_close_window}, {"_NET_MOVERESIZE_WINDOW", &net_moveresize_window}, {"_NET_WM_MOVERESIZE", &net_wm_moveresize}, {"_NET_WM_NAME", &net_wm_name}, {"_NET_WM_VISIBLE_NAME", &net_wm_visible_name}, {"_NET_WM_ICON_NAME", &net_wm_icon_name}, {"_NET_WM_VISIBLE_ICON_NAME", &net_wm_visible_icon_name}, {"_NET_WM_DESKTOP", &net_wm_desktop}, {"_NET_WM_WINDOW_TYPE", &net_wm_window_type}, {"_NET_WM_WINDOW_TYPE_DESKTOP", &net_wm_window_type_desktop}, {"_NET_WM_WINDOW_TYPE_DOCK", &net_wm_window_type_dock}, {"_NET_WM_WINDOW_TYPE_TOOLBAR", &net_wm_window_type_toolbar}, {"_NET_WM_WINDOW_TYPE_MENU", &net_wm_window_type_menu}, {"_NET_WM_WINDOW_TYPE_UTILITY", &net_wm_window_type_utility}, {"_NET_WM_WINDOW_TYPE_SPLASH", &net_wm_window_type_splash}, {"_NET_WM_WINDOW_TYPE_DIALOG", &net_wm_window_type_dialog}, {"_NET_WM_WINDOW_TYPE_DROPDOWN_MENU", &net_wm_window_type_dropdown_menu}, {"_NET_WM_WINDOW_TYPE_POPUP_MENU", &net_wm_window_type_popup_menu}, {"_NET_WM_WINDOW_TYPE_TOOLTIP", &net_wm_window_type_tooltip}, {"_NET_WM_WINDOW_TYPE_NOTIFICATION", &net_wm_window_type_notification}, {"_NET_WM_WINDOW_TYPE_COMBO", &net_wm_window_type_combo}, {"_NET_WM_WINDOW_TYPE_DND", &net_wm_window_type_dnd}, {"_NET_WM_WINDOW_TYPE_NORMAL", &net_wm_window_type_normal}, {"_NET_WM_STATE", &net_wm_state}, {"_NET_WM_STATE_MODAL", &net_wm_state_modal}, {"_NET_WM_STATE_STICKY", &net_wm_state_sticky}, {"_NET_WM_STATE_MAXIMIZED_VERT", &net_wm_state_maximized_vert}, {"_NET_WM_STATE_MAXIMIZED_HORZ", &net_wm_state_maximized_horz}, {"_NET_WM_STATE_SHADED", &net_wm_state_shaded}, {"_NET_WM_STATE_SKIP_TASKBAR", &net_wm_state_skip_taskbar}, {"_NET_WM_STATE_SKIP_PAGER", &net_wm_state_skip_pager}, {"_NET_WM_STATE_HIDDEN", &net_wm_state_hidden}, {"_NET_WM_STATE_FULLSCREEN", &net_wm_state_fullscreen}, {"_NET_WM_STATE_ABOVE", &net_wm_state_above}, {"_NET_WM_STATE_BELOW", &net_wm_state_below}, {"_NET_WM_STATE_FOCUSED", &net_wm_state_focused}, {"_NET_WM_ALLOWED_ACTIONS", &net_wm_allowed_actions}, {"_NET_WM_ACTION_MOVE", &net_wm_action_move}, {"_NET_WM_ACTION_RESIZE", &net_wm_action_resize}, {"_NET_WM_ACTION_MINIMIZE", &net_wm_action_minimize}, {"_NET_WM_ACTION_SHADE", &net_wm_action_shade}, {"_NET_WM_ACTION_STICK", &net_wm_action_stick}, {"_NET_WM_ACTION_MAXIMIZE_HORZ", &net_wm_action_maximize_horz}, {"_NET_WM_ACTION_MAXIMIZE_VERT", &net_wm_action_maximize_vert}, {"_NET_WM_ACTION_FULLSCREEN", &net_wm_action_fullscreen}, {"_NET_WM_ACTION_CHANGE_DESKTOP", &net_wm_action_change_desktop}, {"_NET_WM_ACTION_CLOSE", &net_wm_action_close}, {"_NET_WM_STRUT", &net_wm_strut}, {"_NET_WM_STRUT_PARTIAL", &net_wm_strut_partial}, {"_NET_WM_ICON_GEOMETRY", &net_wm_icon_geometry}, {"_NET_WM_ICON", &net_wm_icon}, {"_NET_WM_PID", &net_wm_pid}, {"_NET_WM_HANDLED_ICONS", &net_wm_handled_icons}, {"_NET_WM_WINDOW_OPACITY", &net_wm_window_opacity}, {"_NET_FRAME_EXTENTS", &net_frame_extents}, {"_NET_WM_PING", &net_wm_ping}, {"UTF8_STRING", &utf8_string}, }; #define _NET_WM_STATE_ADD 1 #define _NET_WM_STATE_TOGGLE 2 #if 0 /* * These constant provide information on the kind of window move/resize when * it is initiated by the application instead of by WindowMaker. They are * parameter for the client message _NET_WM_MOVERESIZE, as defined by the * FreeDesktop wm-spec standard: * http://standards.freedesktop.org/wm-spec/1.5/ar01s04.html * * Today, WindowMaker does not support this at all (the corresponding Atom * is not added to the list in setSupportedHints), probably because there is * nothing it needs to do about it, the application is assumed to know what * it is doing, and WindowMaker won't get in the way. * * The definition of the constants (taken from the standard) are disabled to * avoid a spurious warning (-Wunused-macros). */ #define _NET_WM_MOVERESIZE_SIZE_TOPLEFT 0 #define _NET_WM_MOVERESIZE_SIZE_TOP 1 #define _NET_WM_MOVERESIZE_SIZE_TOPRIGHT 2 #define _NET_WM_MOVERESIZE_SIZE_RIGHT 3 #define _NET_WM_MOVERESIZE_SIZE_BOTTOMRIGHT 4 #define _NET_WM_MOVERESIZE_SIZE_BOTTOM 5 #define _NET_WM_MOVERESIZE_SIZE_BOTTOMLEFT 6 #define _NET_WM_MOVERESIZE_SIZE_LEFT 7 #define _NET_WM_MOVERESIZE_MOVE 8 /* movement only */ #define _NET_WM_MOVERESIZE_SIZE_KEYBOARD 9 /* size via keyboard */ #define _NET_WM_MOVERESIZE_MOVE_KEYBOARD 10 /* move via keyboard */ #endif static void observer(void *self, WMNotification *notif); static void wsobserver(void *self, WMNotification *notif); static void updateClientList(WScreen *scr); static void updateClientListStacking(WScreen *scr, WWindow *); static void updateWorkspaceNames(WScreen *scr); static void updateCurrentWorkspace(WScreen *scr); static void updateWorkspaceCount(WScreen *scr); static void wNETWMShowingDesktop(WScreen *scr, Bool show); typedef struct NetData { WScreen *scr; WReservedArea *strut; WWindow **show_desktop; } NetData; static void setSupportedHints(WScreen *scr) { Atom atom[wlengthof(atomNames)]; int i = 0; /* set supported hints list */ /* XXX: extend this !!! */ atom[i++] = net_client_list; atom[i++] = net_client_list_stacking; atom[i++] = net_number_of_desktops; atom[i++] = net_desktop_geometry; atom[i++] = net_desktop_viewport; atom[i++] = net_current_desktop; atom[i++] = net_desktop_names; atom[i++] = net_active_window; atom[i++] = net_workarea; atom[i++] = net_supporting_wm_check; atom[i++] = net_showing_desktop; #if 0 atom[i++] = net_wm_moveresize; #endif atom[i++] = net_wm_desktop; atom[i++] = net_wm_window_type; atom[i++] = net_wm_window_type_desktop; atom[i++] = net_wm_window_type_dock; atom[i++] = net_wm_window_type_toolbar; atom[i++] = net_wm_window_type_menu; atom[i++] = net_wm_window_type_utility; atom[i++] = net_wm_window_type_splash; atom[i++] = net_wm_window_type_dialog; atom[i++] = net_wm_window_type_dropdown_menu; atom[i++] = net_wm_window_type_popup_menu; atom[i++] = net_wm_window_type_tooltip; atom[i++] = net_wm_window_type_notification; atom[i++] = net_wm_window_type_combo; atom[i++] = net_wm_window_type_dnd; atom[i++] = net_wm_window_type_normal; atom[i++] = net_wm_state; /* atom[i++] = net_wm_state_modal; *//* XXX: not sure where/when to use it. */ atom[i++] = net_wm_state_sticky; atom[i++] = net_wm_state_shaded; atom[i++] = net_wm_state_maximized_horz; atom[i++] = net_wm_state_maximized_vert; atom[i++] = net_wm_state_skip_taskbar; atom[i++] = net_wm_state_skip_pager; atom[i++] = net_wm_state_hidden; atom[i++] = net_wm_state_fullscreen; atom[i++] = net_wm_state_above; atom[i++] = net_wm_state_below; atom[i++] = net_wm_state_focused; atom[i++] = net_wm_allowed_actions; atom[i++] = net_wm_action_move; atom[i++] = net_wm_action_resize; atom[i++] = net_wm_action_minimize; atom[i++] = net_wm_action_shade; atom[i++] = net_wm_action_stick; atom[i++] = net_wm_action_maximize_horz; atom[i++] = net_wm_action_maximize_vert; atom[i++] = net_wm_action_fullscreen; atom[i++] = net_wm_action_change_desktop; atom[i++] = net_wm_action_close; atom[i++] = net_wm_strut; atom[i++] = net_wm_icon_geometry; atom[i++] = net_wm_icon; atom[i++] = net_wm_handled_icons; atom[i++] = net_wm_window_opacity; atom[i++] = net_frame_extents; atom[i++] = net_wm_name; atom[i++] = net_wm_icon_name; XChangeProperty(dpy, scr->root_win, net_supported, XA_ATOM, 32, PropModeReplace, (unsigned char *)atom, i); /* set supporting wm hint */ XChangeProperty(dpy, scr->root_win, net_supporting_wm_check, XA_WINDOW, 32, PropModeReplace, (unsigned char *)&scr->info_window, 1); XChangeProperty(dpy, scr->info_window, net_supporting_wm_check, XA_WINDOW, 32, PropModeReplace, (unsigned char *)&scr->info_window, 1); } void wNETWMUpdateDesktop(WScreen *scr) { long *views, sizes[2]; int count, i; if (scr->workspace_count == 0) return; count = scr->workspace_count * 2; views = wmalloc(sizeof(long) * count); sizes[0] = scr->scr_width; sizes[1] = scr->scr_height; for (i = 0; i < scr->workspace_count; i++) { views[2 * i + 0] = 0; views[2 * i + 1] = 0; } XChangeProperty(dpy, scr->root_win, net_desktop_geometry, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)sizes, 2); XChangeProperty(dpy, scr->root_win, net_desktop_viewport, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)views, count); wfree(views); } int wNETWMGetCurrentDesktopFromHint(WScreen *scr) { int count; unsigned char *prop; prop = PropGetCheckProperty(scr->root_win, net_current_desktop, XA_CARDINAL, 0, 1, &count); if (prop) { int desktop = *(long *)prop; XFree(prop); return desktop; } return -1; } static RImage *makeRImageFromARGBData(unsigned long *data) { int size, width, height, i; RImage *image; unsigned char *imgdata; unsigned long pixel; width = data[0]; height = data[1]; size = width * height; if (size == 0) return NULL; image = RCreateImage(width, height, True); for (imgdata = image->data, i = 2; i < size + 2; i++, imgdata += 4) { pixel = data[i]; imgdata[3] = (pixel >> 24) & 0xff; /* A */ imgdata[0] = (pixel >> 16) & 0xff; /* R */ imgdata[1] = (pixel >> 8) & 0xff; /* G */ imgdata[2] = (pixel >> 0) & 0xff; /* B */ } return image; } /* Find the best icon to be used by Window Maker for appicon/miniwindows. */ static RImage *findBestIcon(unsigned long *data, unsigned long items) { int wanted; int dx, dy, d; int sx, sy, size; int best_d, largest; unsigned long i; unsigned long *icon; RImage *src_image, *ret_image; double f; if (wPreferences.enforce_icon_margin) { /* better use only 75% of icon_size. For 64x64 this means 48x48 * This leaves room around the icon for the miniwindow title and * results in better overall aesthetics -Dan */ wanted = (int)((double)wPreferences.icon_size * 0.75 + 0.5); /* the size should be a multiple of 4 */ wanted = (wanted >> 2) << 2; } else { /* This is the "old" approach, which tries to find the largest * icon that still fits into icon_size. */ wanted = wPreferences.icon_size; } /* try to find an icon which is close to the wanted size, but not larger */ icon = NULL; best_d = wanted * wanted * 2; for (i = 0L; i < items - 1;) { /* get the current icon's size */ sx = (int)data[i]; sy = (int)data[i + 1]; if ((sx < 1) || (sy < 1)) break; size = sx * sy + 2; /* check the size difference if it's not too large */ if ((sx <= wanted) && (sy <= wanted)) { dx = wanted - sx; dy = wanted - sy; d = (dx * dx) + (dy * dy); if (d < best_d) { icon = &data[i]; best_d = d; } } i += size; } /* if an icon has been found, no transformation is needed */ if (icon) return makeRImageFromARGBData(icon); /* We need to scale down an icon. Find the largest one, for it usually * looks better to scale down a large image by a large scale than a * small image by a small scale. */ largest = 0; for (i = 0L; i < items - 1;) { size = (int)data[i] * (int)data[i + 1]; if (size == 0) break; if (size > largest) { icon = &data[i]; largest = size; } i += size + 2; } /* give up if there's no icon to work with */ if (!icon) return NULL; /* create a scaled down version of the icon */ src_image = makeRImageFromARGBData(icon); if (src_image->width > src_image->height) { f = (double)wanted / (double)src_image->width; ret_image = RScaleImage(src_image, wanted, (int)(f * (double)(src_image->height))); } else { f = (double)wanted / (double)src_image->height; ret_image = RScaleImage(src_image, (int)(f * (double)src_image->width), wanted); } RReleaseImage(src_image); return ret_image; } RImage *get_window_image_from_x11(Window window) { RImage *image; Atom type; int format; unsigned long items, rest; unsigned long *property; /* Get the icon from X11 Window */ if (XGetWindowProperty(dpy, window, net_wm_icon, 0L, LONG_MAX, False, XA_CARDINAL, &type, &format, &items, &rest, (unsigned char **)&property) != Success || !property) return NULL; if (type != XA_CARDINAL || format != 32 || items < 2) { XFree(property); return NULL; } /* Find the best icon */ image = findBestIcon(property, items); XFree(property); if (!image) return NULL; /* Resize the image to the correct value */ - image = wIconValidateIconSize(image, wPreferences.icon_size); + image = wIconValidateIconSize(image, wPreferences.icon_size, False); return image; } static void updateIconImage(WWindow *wwin) { /* Remove the icon image from X11 */ if (wwin->net_icon_image) RReleaseImage(wwin->net_icon_image); /* Save the icon in the X11 icon */ wwin->net_icon_image = get_window_image_from_x11(wwin->client_win); /* Refresh the Window Icon */ if (wwin->icon) wIconUpdate(wwin->icon); /* Refresh the application icon */ WApplication *app = wApplicationOf(wwin->main_window); if (app && app->app_icon) { wIconUpdate(app->app_icon->icon); wAppIconPaint(app->app_icon); } } static void updateWindowOpacity(WWindow *wwin) { Atom type; int format; unsigned long items, rest; unsigned long *property; if (!wwin->frame) return; /* We don't care about this ourselves, but other programs need us to copy * this to the frame window. */ if (XGetWindowProperty(dpy, wwin->client_win, net_wm_window_opacity, 0L, 1L, False, XA_CARDINAL, &type, &format, &items, &rest, (unsigned char **)&property) != Success) return; if (type == None) { XDeleteProperty(dpy, wwin->frame->core->window, net_wm_window_opacity); } else if (type == XA_CARDINAL && format == 32 && items == 1 && property) { XChangeProperty(dpy, wwin->frame->core->window, net_wm_window_opacity, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)property, 1L); } if (property) XFree(property); } static void updateShowDesktop(WScreen *scr, Bool show) { long foo; foo = (show == True); XChangeProperty(dpy, scr->root_win, net_showing_desktop, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&foo, 1); } static void wNETWMShowingDesktop(WScreen *scr, Bool show) { if (show && scr->netdata->show_desktop == NULL) { WWindow *tmp, **wins; int i = 0; wins = (WWindow **) wmalloc(sizeof(WWindow *) * (scr->window_count + 1)); tmp = scr->focused_window; while (tmp) { if (!tmp->flags.hidden && !tmp->flags.miniaturized && !WFLAGP(tmp, skip_window_list)) { wins[i++] = tmp; tmp->flags.skip_next_animation = 1; tmp->flags.net_show_desktop = 1; wIconifyWindow(tmp); } tmp = tmp->prev; } wins[i++] = NULL; scr->netdata->show_desktop = wins; updateShowDesktop(scr, True); } else if (scr->netdata->show_desktop != NULL) { /* FIXME: get rid of workspace flashing ! */ int ws = scr->current_workspace; WWindow **tmp; for (tmp = scr->netdata->show_desktop; *tmp; ++tmp) { wDeiconifyWindow(*tmp); (*tmp)->flags.net_show_desktop = 0; } if (ws != scr->current_workspace) wWorkspaceChange(scr, ws); wfree(scr->netdata->show_desktop); scr->netdata->show_desktop = NULL; updateShowDesktop(scr, False); } } void wNETWMInitStuff(WScreen *scr) { NetData *data; int i; #ifdef DEBUG_WMSPEC wmessage("wNETWMInitStuff"); #endif #ifdef HAVE_XINTERNATOMS { Atom atoms[wlengthof(atomNames)]; char *names[wlengthof(atomNames)]; for (i = 0; i < wlengthof(atomNames); ++i) names[i] = atomNames[i].name; XInternAtoms(dpy, &names[0], wlengthof(atomNames), False, atoms); for (i = 0; i < wlengthof(atomNames); ++i) *atomNames[i].atom = atoms[i]; } #else for (i = 0; i < wlengthof(atomNames); i++) *atomNames[i].atom = XInternAtom(dpy, atomNames[i].name, False); #endif data = wmalloc(sizeof(NetData)); data->scr = scr; data->strut = NULL; data->show_desktop = NULL; scr->netdata = data; setSupportedHints(scr); WMAddNotificationObserver(observer, data, WMNManaged, NULL); WMAddNotificationObserver(observer, data, WMNUnmanaged, NULL); WMAddNotificationObserver(observer, data, WMNChangedWorkspace, NULL); WMAddNotificationObserver(observer, data, WMNChangedState, NULL); WMAddNotificationObserver(observer, data, WMNChangedFocus, NULL); WMAddNotificationObserver(observer, data, WMNChangedStacking, NULL); WMAddNotificationObserver(observer, data, WMNChangedName, NULL); WMAddNotificationObserver(wsobserver, data, WMNWorkspaceCreated, NULL); WMAddNotificationObserver(wsobserver, data, WMNWorkspaceDestroyed, NULL); WMAddNotificationObserver(wsobserver, data, WMNWorkspaceChanged, NULL); WMAddNotificationObserver(wsobserver, data, WMNWorkspaceNameChanged, NULL); updateClientList(scr); updateClientListStacking(scr, NULL); updateWorkspaceCount(scr); updateWorkspaceNames(scr); updateShowDesktop(scr, False); wScreenUpdateUsableArea(scr); } void wNETWMCleanup(WScreen *scr) { int i; for (i = 0; i < wlengthof(atomNames); i++) XDeleteProperty(dpy, scr->root_win, *atomNames[i].atom); } void wNETWMUpdateActions(WWindow *wwin, Bool del) { Atom action[10]; /* nr of actions atoms defined */ int i = 0; if (del) { XDeleteProperty(dpy, wwin->client_win, net_wm_allowed_actions); return; } if (IS_MOVABLE(wwin)) action[i++] = net_wm_action_move; if (IS_RESIZABLE(wwin)) action[i++] = net_wm_action_resize; if (!WFLAGP(wwin, no_miniaturizable)) action[i++] = net_wm_action_minimize; if (!WFLAGP(wwin, no_shadeable)) action[i++] = net_wm_action_shade; /* if (!WFLAGP(wwin, no_stickable)) */ action[i++] = net_wm_action_stick; /* if (!(WFLAGP(wwin, no_maximizeable) & MAX_HORIZONTAL)) */ if (IS_RESIZABLE(wwin)) action[i++] = net_wm_action_maximize_horz; /* if (!(WFLAGP(wwin, no_maximizeable) & MAX_VERTICAL)) */ if (IS_RESIZABLE(wwin)) action[i++] = net_wm_action_maximize_vert; /* if (!WFLAGP(wwin, no_fullscreen)) */ action[i++] = net_wm_action_fullscreen; /* if (!WFLAGP(wwin, no_change_desktop)) */ action[i++] = net_wm_action_change_desktop; if (!WFLAGP(wwin, no_closable)) action[i++] = net_wm_action_close; XChangeProperty(dpy, wwin->client_win, net_wm_allowed_actions, XA_ATOM, 32, PropModeReplace, (unsigned char *)action, i); } void wNETWMUpdateWorkarea(WScreen *scr) { WArea total_usable; int nb_workspace; if (!scr->netdata) { /* If the _NET_xxx were not initialised, it not necessary to do anything */ return; } if (!scr->usableArea) { /* If we don't have any info, we fall back on using the complete screen area */ total_usable.x1 = 0; total_usable.y1 = 0; total_usable.x2 = scr->scr_width; total_usable.y2 = scr->scr_height; } else { int i; /* * the _NET_WORKAREA is supposed to contain the total area of the screen that * is usable, so we merge the areas from all xrandr sub-screens */ total_usable = scr->usableArea[0]; for (i = 1; i < wXineramaHeads(scr); i++) { /* The merge is not subtle because _NET_WORKAREA does not need more */ if (scr->usableArea[i].x1 < total_usable.x1) total_usable.x1 = scr->usableArea[i].x1; if (scr->usableArea[i].y1 < total_usable.y1) total_usable.y1 = scr->usableArea[i].y1; if (scr->usableArea[i].x2 > total_usable.x2) total_usable.x2 = scr->usableArea[i].x2; if (scr->usableArea[i].y2 > total_usable.y2) total_usable.y2 = scr->usableArea[i].y2; } } /* We are expected to repeat the information for each workspace */ if (scr->workspace_count == 0) nb_workspace = 1; else nb_workspace = scr->workspace_count; { long property_value[nb_workspace * 4]; int i; for (i = 0; i < nb_workspace; i++) { property_value[4 * i + 0] = total_usable.x1; property_value[4 * i + 1] = total_usable.y1; property_value[4 * i + 2] = total_usable.x2 - total_usable.x1; property_value[4 * i + 3] = total_usable.y2 - total_usable.y1; } XChangeProperty(dpy, scr->root_win, net_workarea, XA_CARDINAL, 32, PropModeReplace, (unsigned char *) property_value, nb_workspace * 4); } } Bool wNETWMGetUsableArea(WScreen *scr, int head, WArea *area) { WReservedArea *cur; WMRect rect; if (!scr->netdata || !scr->netdata->strut) return False; area->x1 = area->y1 = area->x2 = area->y2 = 0; for (cur = scr->netdata->strut; cur; cur = cur->next) { WWindow *wwin = wWindowFor(cur->window); if (wWindowTouchesHead(wwin, head)) { if (cur->area.x1 > area->x1) area->x1 = cur->area.x1; if (cur->area.y1 > area->y1) area->y1 = cur->area.y1; if (cur->area.x2 > area->x2) area->x2 = cur->area.x2; if (cur->area.y2 > area->y2) area->y2 = cur->area.y2; } } if (area->x1 == 0 && area->x2 == 0 && area->y1 == 0 && area->y2 == 0) return False; rect = wGetRectForHead(scr, head); /* NOTE(gryf): calculation for the reserved area should be preformed for * current head, but area, which comes form _NET_WM_STRUT, has to be * calculated relative to entire screen size, i.e. suppose we have three * heads arranged like this: * * ╔════════════════════════╗ * ║ 0 ║ * ║ ╠═══════════╗ * ║ ║ 2 ║ * ║ ║ ║ * ╟────────────────────────╫───────────╢ * ╠════════════════════════╬═══════════╝ * ║ 1 ║ * ║ ║ * ║ ║ * ║ ║ * ║ ║ * ╟────────────────────────╢ * ╚════════════════════════╝ * * where head 0 have resolution 1920x1080, head 1: 1920x1200 and head 2 * 800x600, so the screen size in this arrangement will be 2720x2280 (1920 * + 800) x (1080 + 1200). * * Bottom line represents some 3rd party panel, which sets properties in * _NET_WM_STRUT_PARTIAL and optionally _NET_WM_STRUT. * * By coincidence, coordinates x1 and y1 from left and top are the same as * the original data which came from _NET_WM_STRUT, since they meaning * distance from the edge, so we leave it as-is, otherwise if they have 0 * value, we need to set right head position. */ /* optional reserved space from left */ if (area->x1 == 0) area->x1 = rect.pos.x; /* optional reserved space from top */ if (area->y1 == 0) area->y1 = rect.pos.y; /* optional reserved space from right */ if (area->x2 == 0) area->x2 = rect.pos.x + rect.size.width; else area->x2 = scr->scr_width - area->x2; /* optional reserved space from bottom */ if (area->y2 == 0) area->y2 = rect.pos.y + rect.size.height; else area->y2 = scr->scr_height - area->y2; return True; } static void updateClientList(WScreen *scr) { WWindow *wwin; Window *windows; int count; windows = (Window *) wmalloc(sizeof(Window) * (scr->window_count + 1)); count = 0; wwin = scr->focused_window; while (wwin) { windows[count++] = wwin->client_win; wwin = wwin->prev; } XChangeProperty(dpy, scr->root_win, net_client_list, XA_WINDOW, 32, PropModeReplace, (unsigned char *)windows, count); wfree(windows); XFlush(dpy); } static void updateClientListStacking(WScreen *scr, WWindow *wwin_excl) { WWindow *wwin; Window *client_list, *client_list_reverse; int client_count, i; WCoreWindow *tmp; WMBagIterator iter; /* update client list */ i = scr->window_count + 1; client_list = (Window *) wmalloc(sizeof(Window) * i); client_list_reverse = (Window *) wmalloc(sizeof(Window) * i); client_count = 0; WM_ETARETI_BAG(scr->stacking_list, tmp, iter) { while (tmp) { wwin = wWindowFor(tmp->window); /* wwin_excl is a window to exclude from the list (e.g. it's now unmanaged) */ if (wwin && (wwin != wwin_excl)) client_list[client_count++] = wwin->client_win; tmp = tmp->stacking->under; } } for (i = 0; i < client_count; i++) { Window w = client_list[client_count - i - 1]; client_list_reverse[i] = w; } XChangeProperty(dpy, scr->root_win, net_client_list_stacking, XA_WINDOW, 32, PropModeReplace, (unsigned char *)client_list_reverse, client_count); wfree(client_list); wfree(client_list_reverse); XFlush(dpy); } static void updateWorkspaceCount(WScreen *scr) { /* changeable */ long count; count = scr->workspace_count; XChangeProperty(dpy, scr->root_win, net_number_of_desktops, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&count, 1); } static void updateCurrentWorkspace(WScreen *scr) { /* changeable */ long count; count = scr->current_workspace; XChangeProperty(dpy, scr->root_win, net_current_desktop, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&count, 1); } static void updateWorkspaceNames(WScreen *scr) { char buf[MAX_WORKSPACES * (MAX_WORKSPACENAME_WIDTH + 1)], *pos; unsigned int i, len, curr_size; pos = buf; len = 0; for (i = 0; i < scr->workspace_count; i++) { curr_size = strlen(scr->workspaces[i]->name); strcpy(pos, scr->workspaces[i]->name); pos += (curr_size + 1); len += (curr_size + 1); } XChangeProperty(dpy, scr->root_win, net_desktop_names, utf8_string, 8, PropModeReplace, (unsigned char *)buf, len); } static void updateFocusHint(WScreen *scr) { /* changeable */ Window window; if (!scr->focused_window || !scr->focused_window->flags.focused) window = None; else window = scr->focused_window->client_win; XChangeProperty(dpy, scr->root_win, net_active_window, XA_WINDOW, 32, PropModeReplace, (unsigned char *)&window, 1); } static void updateWorkspaceHint(WWindow *wwin, Bool fake, Bool del) { long l; if (del) { XDeleteProperty(dpy, wwin->client_win, net_wm_desktop); } else { l = ((fake || IS_OMNIPRESENT(wwin)) ? -1 : wwin->frame->workspace); XChangeProperty(dpy, wwin->client_win, net_wm_desktop, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&l, 1); } } static void updateStateHint(WWindow *wwin, Bool changedWorkspace, Bool del) { /* changeable */ if (del) { XDeleteProperty(dpy, wwin->client_win, net_wm_state); } else { Atom state[15]; /* nr of defined state atoms */ int i = 0; if (changedWorkspace || (wPreferences.sticky_icons && !IS_OMNIPRESENT(wwin))) updateWorkspaceHint(wwin, False, False); if (IS_OMNIPRESENT(wwin)) state[i++] = net_wm_state_sticky; if (wwin->flags.shaded) state[i++] = net_wm_state_shaded; if (wwin->flags.maximized & MAX_HORIZONTAL) state[i++] = net_wm_state_maximized_horz; if (wwin->flags.maximized & MAX_VERTICAL) state[i++] = net_wm_state_maximized_vert; if (WFLAGP(wwin, skip_window_list)) state[i++] = net_wm_state_skip_taskbar; if (wwin->flags.net_skip_pager) state[i++] = net_wm_state_skip_pager; if ((wwin->flags.hidden || wwin->flags.miniaturized) && !wwin->flags.net_show_desktop) { state[i++] = net_wm_state_hidden; state[i++] = net_wm_state_skip_pager;
roblillack/wmaker
ea0ca51e3496cd3c209cc8e41b37122b0872cc96
Fix default window attributes that lead to all app menus not working. (#4)
diff --git a/WindowMaker/Defaults/WMWindowAttributes.in b/WindowMaker/Defaults/WMWindowAttributes.in index f182e51..d2886c6 100644 --- a/WindowMaker/Defaults/WMWindowAttributes.in +++ b/WindowMaker/Defaults/WMWindowAttributes.in @@ -1,7 +1,7 @@ { Logo.WMDock = {Icon = GNUstepGlow.#extension#;}; Logo.WMPanel = {Icon = GNUstep.#extension#;}; Logo.WMClip = {Icon = clip.#extension#;}; WMDrawer = {Icon = Drawer.#extension#;}; - "*" = {Icon = defaultAppIcon.#extension#;SharedAppIcon = Yes;}; + "*" = {Icon = defaultAppIcon.#extension#;}; }
roblillack/wmaker
bf86d4f4ad2361dc885769c10ff3ce14a65047fa
Adds a space of 3 pixels next to the dock--like in NeXTSTEP/OPENSTEP. (#3)
diff --git a/src/wconfig.h.in b/src/wconfig.h.in index 46c3059..b4117dc 100644 --- a/src/wconfig.h.in +++ b/src/wconfig.h.in @@ -1,406 +1,406 @@ /* * wconfig.h- default configuration and definitions + compile time options * * WindowMaker window manager * * Copyright (c) 1997-2003 Alfredo K. Kojima * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, * MA 02110-1301, USA. */ #ifndef WMCONFIG_H_ #define WMCONFIG_H_ #include "config.h" /*** Change this file (wconfig.h) *after* you ran configure ***/ /* * Comment out the following #defines if you want to disable a feature. * Also check the features you can enable through configure. */ /* * Undefine BALLOON_TEXT if you don't want balloons for showing extra * information, like window titles that are not fully visible. */ #define BALLOON_TEXT /* * If balloons should be shaped or be simple rectangles. * The X server must support the shape extensions and it's support * must be enabled (default). */ #define SHAPED_BALLOON /* * Turn on a hack to make mouse and keyboard actions work even if * the NumLock or ScrollLock modifiers are turned on. They might * inflict a performance/memory penalty. * * If you're an X expert (knows the implementation of XGrabKey() in X) * and knows that the penalty is small (or not), please tell me. */ #define NUMLOCK_HACK /* * define OPTIMIZE_SHAPE if you want the shape setting code to be optimized * for applications that change their shape frequently (like xdaliclock * -shape), removing flickering. If wmaker and your display are on * different machines and the network connection is slow, it is not * recommended. */ #undef OPTIMIZE_SHAPE /* define CONFIGURE_WINDOW_WHILE_MOVING if you want WindowMaker to send * the synthetic ConfigureNotify event to windows while moving at every * single movement. Default is to send a synthetic ConfigureNotify event * only at the end of window moving, which improves performance. */ #undef CONFIGURE_WINDOW_WHILE_MOVING /* disable/enable workspace indicator in the dock */ #undef WS_INDICATOR /* * define HIDDENDOT if you want a dot to be shown in the application icon * of applications that are hidden. */ #define HIDDENDOT /* * Ignores the PPosition hint from clients. This is needed for some * programs that have buggy implementations of such hint and place * themselves in strange locations. */ #undef IGNORE_PPOSITION /* * The following options WILL NOT BE MADE RUN-TIME. Please do not request. * They will only add unneeded bloat. */ /* * define SHADOW_RESIZEBAR if you want a resizebar with shadows like in * AfterStep, instead of the default Openstep look. * NEXTSTEP 3.3 also does not have these shadows. */ #undef SHADOW_RESIZEBAR #define NORMAL_ICON_KABOOM /* * #define if you want the window creation animation when superfluous * is enabled. */ #undef WINDOW_BIRTH_ZOOM /* * Some of the following options can be configured in the preference files, * but if for some reason they can't, these are their defaults. * * There are also some options that can only be configured here, at compile time. */ /* list of paths to look for the config files, searched in order of appearance */ #define DEF_CONFIG_PATHS "~/GNUstep/Library/WindowMaker:"PKGDATADIR #define DEF_MENU_FILE "menu" /* name of the script to execute at startup */ #define DEF_INIT_SCRIPT "autostart" #define DEF_EXIT_SCRIPT "exitscript" #define DEFAULTS_DIR "Defaults" #ifdef USE_TIFF #define DEF_BUTTON_IMAGES PKGDATADIR"/buttons.tiff" #else #define DEF_BUTTON_IMAGES PKGDATADIR"/buttons.xpm" #endif /* the file of the system wide submenu to be forced into the main menu */ #define GLOBAL_PREAMBLE_MENU_FILE "GlobalMenu.pre" #define GLOBAL_EPILOGUE_MENU_FILE "GlobalMenu.post" /* pixmap path */ #define DEF_PIXMAP_PATHS \ "(" \ "\"~/GNUstep/Library/WindowMaker/Pixmaps\"," \ "\"~/GNUstep/Library/WindowMaker/Backgrounds\"," \ "\"~/GNUstep/Library/WindowMaker/CachedPixmaps\"," \ "\"~/pixmaps\"," \ "\""PKGDATADIR"/Pixmaps\"," \ "\""PKGDATADIR"/Backgrounds\"," \ "\""PIXMAPDIR"\"" \ ")" #ifdef USER_MENU #define GLOBAL_USER_MENU_PATH PKGDATADIR"/UserMenus" #define DEF_USER_MENU_PATHS \ "~/GNUstep/Library/WindowMaker/UserMenus:"GLOBAL_USER_MENU_PATH #endif /* icon path */ #define DEF_ICON_PATHS \ "(" \ "\"~/GNUstep/Library/Icons\"," \ "\"~/GNUstep/Library/WindowMaker/Pixmaps\"," \ "\"~/GNUstep/Library/WindowMaker/CachedPixmaps\"," \ "\"~/pixmaps\"," \ "\""PKGDATADIR"/Icons\"," \ "\""PKGDATADIR"/Pixmaps\"," \ "\""PIXMAPDIR"\"" \ ")" /* window title to use for untitled windows */ #define DEF_WINDOW_TITLE "Untitled" /* default style */ #define DEF_FRAME_COLOR "white" /* default fonts */ #define DEF_TITLE_FONT "\"Sans:bold:pixelsize=12\"" #define DEF_MENU_TITLE_FONT "\"Sans:bold:pixelsize=12\"" #define DEF_MENU_ENTRY_FONT "\"Sans:pixelsize=12\"" #define DEF_ICON_TITLE_FONT "\"Sans:pixelsize=9\"" #define DEF_CLIP_TITLE_FONT "\"Sans:bold:pixelsize=10\"" #define DEF_WORKSPACE_NAME_FONT "\"Sans:pixelsize=24\"" /* line width of the move/resize frame */ #define DEF_FRAME_THICKNESS 1 #define DEF_WINDOW_TITLE_EXTEND_SPACE "0" #define DEF_MENU_TITLE_EXTEND_SPACE "0" #define DEF_MENU_TEXT_EXTEND_SPACE "0" #define TITLEBAR_EXTEND_SPACE 4 #define DEF_XPM_CLOSENESS 40000 /* default position of application menus */ #define DEF_APPMENU_X 10 #define DEF_APPMENU_Y 10 /* calculate window edge resistance from edge resistance */ #define WIN_RESISTANCE(x) (((x)*20)/30) /* Window level where icons reside */ #define NORMAL_ICON_LEVEL WMNormalLevel /* do not divide main menu and submenu in different tiers, * opposed to OpenStep */ #define SINGLE_MENULEVEL /* max. time to spend doing animations in seconds. If the animation * time exceeds this value, it is immediately finished. Useful for * moments of high-load. DO NOT set *_DELAY_{Z,T,F} to zero! */ #define MAX_ANIMATION_TIME 1 /* Zoom animation */ #define MINIATURIZE_ANIMATION_FRAMES_Z 7 #define MINIATURIZE_ANIMATION_STEPS_Z 16 #define MINIATURIZE_ANIMATION_DELAY_Z 10000 /* Twist animation */ #define MINIATURIZE_ANIMATION_FRAMES_T 12 #define MINIATURIZE_ANIMATION_STEPS_T 16 #define MINIATURIZE_ANIMATION_DELAY_T 20000 #define MINIATURIZE_ANIMATION_TWIST_T 0.5 /* Flip animation */ #define MINIATURIZE_ANIMATION_FRAMES_F 12 #define MINIATURIZE_ANIMATION_STEPS_F 16 #define MINIATURIZE_ANIMATION_DELAY_F 20000 #define MINIATURIZE_ANIMATION_TWIST_F 0.5 /* delays in ms...*/ #define BALLOON_DELAY 1000 /* ...before balloon is shown */ #define MENU_SELECT_DELAY 200 /* ...for menu item selection hysteresis */ #define MENU_JUMP_BACK_DELAY 400 /* ...for jumpback of scrolled menus */ /* animation speed constants */ #define ICON_SLIDE_SLOWDOWN_UF 1 #define ICON_SLIDE_DELAY_UF 0 #define ICON_SLIDE_STEPS_UF 50 #define ICON_SLIDE_SLOWDOWN_F 3 #define ICON_SLIDE_DELAY_F 0 #define ICON_SLIDE_STEPS_F 50 #define ICON_SLIDE_SLOWDOWN_M 5 #define ICON_SLIDE_DELAY_M 0 #define ICON_SLIDE_STEPS_M 30 #define ICON_SLIDE_SLOWDOWN_S 10 #define ICON_SLIDE_DELAY_S 0 #define ICON_SLIDE_STEPS_S 20 #define ICON_SLIDE_SLOWDOWN_US 20 #define ICON_SLIDE_DELAY_US 1 #define ICON_SLIDE_STEPS_US 10 /* menu scrolling */ #define MENU_SCROLL_STEPS_UF 14 #define MENU_SCROLL_DELAY_UF 1 #define MENU_SCROLL_STEPS_F 10 #define MENU_SCROLL_DELAY_F 5 #define MENU_SCROLL_STEPS_M 6 #define MENU_SCROLL_DELAY_M 5 #define MENU_SCROLL_STEPS_S 4 #define MENU_SCROLL_DELAY_S 6 #define MENU_SCROLL_STEPS_US 1 #define MENU_SCROLL_DELAY_US 8 /* shade animation */ #define SHADE_STEPS_UF 5 #define SHADE_DELAY_UF 0 #define SHADE_STEPS_F 10 #define SHADE_DELAY_F 0 #define SHADE_STEPS_M 15 #define SHADE_DELAY_M 0 #define SHADE_STEPS_S 30 #define SHADE_DELAY_S 0 #define SHADE_STEPS_US 40 #define SHADE_DELAY_US 10 /* workspace name on switch display */ #define WORKSPACE_NAME_FADE_DELAY 30 #define WORKSPACE_NAME_DELAY 400 /* Delay when cycling colors of selected icons. */ #define COLOR_CYCLE_DELAY 200 /* size of the pieces in the undocked icon explosion */ #define ICON_KABOOM_PIECE_SIZE 4 /* * Position increment for smart placement: >= 1 * Raise these values if it's too slow for you */ #define PLACETEST_HSTEP 8 #define PLACETEST_VSTEP 8 -#define DOCK_EXTRA_SPACE 0 +#define DOCK_EXTRA_SPACE 3 /* Vicinity in which an icon can be attached to the clip */ #define CLIP_ATTACH_VICINITY 1 #define CLIP_BUTTON_SIZE 23 /* The amount of space (in multiples of the icon size) * a docked icon must be dragged out to detach it */ #define DOCK_DETTACH_THRESHOLD 3 /* Max. number of icons the dock and clip can have */ #define DOCK_MAX_ICONS 32 /* blink interval when invoking a menu item */ #define MENU_BLINK_DELAY 60000 #define MENU_BLINK_COUNT 2 #define CURSOR_BLINK_RATE 300 /* how many pixels to move before dragging windows and other objects */ #define MOVE_THRESHOLD 5 #define HRESIZE_THRESHOLD 3 #define MAX_WORKSPACENAME_WIDTH 64 /* max width of window title in window list */ #define MAX_WINDOWLIST_WIDTH 400 #ifndef HAVE_INOTIFY /* Check defaults database for changes every this many milliseconds */ #define DEFAULTS_CHECK_INTERVAL 2000 #endif #define KEY_CONTROL_WINDOW_WEIGHT 1 /* don't put titles in miniwindows */ #undef NO_MINIWINDOW_TITLES /* for boxes with high mouse sampling rates (SGI) */ #define DELAY_BETWEEN_MOUSE_SAMPLING 10 /* * You should not modify the following values, unless you know * what you're doing. */ /* number of window shortcuts */ #define MAX_WINDOW_SHORTCUTS 10 #define MIN_TITLEFONT_HEIGHT(h) ((h)>14 ? (h) : 14) #define TITLEBAR_HEIGHT 18 /* window's titlebar height */ #define RESIZEBAR_HEIGHT 8 /* height of the resizebar */ #define RESIZEBAR_MIN_WIDTH 20 /* min width of handles-corner_width */ #define RESIZEBAR_CORNER_WIDTH 28 /* width of the corner of resizebars */ #define MENU_INDICATOR_SPACE 12 #define MIN_WINDOW_SIZE 5 /* minimum size for windows */ #define ICON_WIDTH 64 /* size of the icon window */ #define ICON_HEIGHT 64 #define ICON_BORDER_WIDTH 2 #define MAX_ICON_WIDTH 60 /* size of the icon pixmap */ #define MAX_ICON_HEIGHT 48 #define MAX_WORKSPACES 100 #define MAX_MENU_TEXT_LENGTH 512 #define MAX_RESTART_ARGS 16 #define MAX_DEAD_PROCESSES 128 #define MAXLINE 1024 #ifdef _MAX_PATH # define DEFAULT_PATH_MAX _MAX_PATH #else # define DEFAULT_PATH_MAX 512 #endif /* some rules */ #ifndef USE_XSHAPE #undef SHAPED_BALLOON #endif #ifdef XKB_MODELOCK #define KEEP_XKB_LOCK_STATUS /* This is a hidden feature. * Choose just one of LANGUAGE_* hints. * Icon can be changed in def_pixmaps.h. * More icons are welcome. */ #define XKB_BUTTON_HINT #undef LANGUAGE_TH #undef LANGUAGE_SK #endif #if defined(HAVE_LIBINTL_H) && defined(I18N) #include <libintl.h> #define _(text) gettext(text) /* Use N_() in initializers, it will make xgettext pick * the string up for translation */ #define N_(text) (text) #if defined(MENU_TEXTDOMAIN) #define M_(text) dgettext(MENU_TEXTDOMAIN, text) #else #define M_(text) (text) #endif #else #define _(text) (text) #define N_(text) (text) #define M_(text) (text) #endif #endif /* WMCONFIG_H_ */
roblillack/wmaker
f0a635b481676ff3ab8446d5bd98f91dbbb6aafd
wings: Use the GNUstep/OPENSTEP/menu background color as default gray. (#2)
diff --git a/WINGs/wcolor.c b/WINGs/wcolor.c index a02c182..1b21ce3 100644 --- a/WINGs/wcolor.c +++ b/WINGs/wcolor.c @@ -1,326 +1,326 @@ #include "WINGsP.h" #include "wconfig.h" #include <wraster.h> #define LIGHT_STIPPLE_WIDTH 4 #define LIGHT_STIPPLE_HEIGHT 4 static char LIGHT_STIPPLE_BITS[] = { 0x05, 0x0a, 0x05, 0x0a }; #define DARK_STIPPLE_WIDTH 4 #define DARK_STIPPLE_HEIGHT 4 static char DARK_STIPPLE_BITS[] = { 0x0a, 0x04, 0x0a, 0x01 }; static WMColor *createRGBAColor(WMScreen * scr, unsigned short red, unsigned short green, unsigned short blue, unsigned short alpha); /* * TODO: make the color creation code return the same WMColor for the * same colors. * make findCloseColor() find the closest color in the RContext pallette * or in the other colors allocated by WINGs. */ static WMColor *findCloseColor(WMScreen * scr, unsigned short red, unsigned short green, unsigned short blue, unsigned short alpha) { WMColor *color; XColor xcolor; RColor rcolor; rcolor.red = red >> 8; rcolor.green = green >> 8; rcolor.blue = blue >> 8; rcolor.alpha = alpha >> 8; if (!RGetClosestXColor(scr->rcontext, &rcolor, &xcolor)) return NULL; if (!XAllocColor(scr->display, scr->colormap, &xcolor)) return NULL; color = wmalloc(sizeof(WMColor)); color->screen = scr; color->refCount = 1; color->color = xcolor; color->alpha = alpha; color->flags.exact = 1; color->gc = NULL; return color; } static WMColor *createRGBAColor(WMScreen * scr, unsigned short red, unsigned short green, unsigned short blue, unsigned short alpha) { WMColor *color; XColor xcolor; xcolor.red = red; xcolor.green = green; xcolor.blue = blue; xcolor.flags = DoRed | DoGreen | DoBlue; if (!XAllocColor(scr->display, scr->colormap, &xcolor)) return NULL; color = wmalloc(sizeof(WMColor)); color->screen = scr; color->refCount = 1; color->color = xcolor; color->alpha = alpha; color->flags.exact = 1; color->gc = NULL; return color; } WMColor *WMCreateRGBColor(WMScreen * scr, unsigned short red, unsigned short green, unsigned short blue, Bool exact) { WMColor *color = NULL; if (!exact || !(color = createRGBAColor(scr, red, green, blue, 0xffff))) { color = findCloseColor(scr, red, green, blue, 0xffff); } if (!color) color = WMBlackColor(scr); return color; } RColor WMGetRColorFromColor(WMColor * color) { RColor rcolor; rcolor.red = color->color.red >> 8; rcolor.green = color->color.green >> 8; rcolor.blue = color->color.blue >> 8; rcolor.alpha = color->alpha >> 8; return rcolor; } WMColor *WMCreateRGBAColor(WMScreen * scr, unsigned short red, unsigned short green, unsigned short blue, unsigned short alpha, Bool exact) { WMColor *color = NULL; if (!exact || !(color = createRGBAColor(scr, red, green, blue, alpha))) { color = findCloseColor(scr, red, green, blue, alpha); } if (!color) color = WMBlackColor(scr); return color; } WMColor *WMCreateNamedColor(WMScreen * scr, const char *name, Bool exact) { WMColor *color; XColor xcolor; if (!XParseColor(scr->display, scr->colormap, name, &xcolor)) return NULL; if (scr->visual->class == TrueColor) exact = True; if (!exact || !(color = createRGBAColor(scr, xcolor.red, xcolor.green, xcolor.blue, 0xffff))) { color = findCloseColor(scr, xcolor.red, xcolor.green, xcolor.blue, 0xffff); } return color; } WMColor *WMRetainColor(WMColor * color) { assert(color != NULL); color->refCount++; return color; } void WMReleaseColor(WMColor * color) { color->refCount--; if (color->refCount < 1) { XFreeColors(color->screen->display, color->screen->colormap, &(color->color.pixel), 1, 0); if (color->gc) XFreeGC(color->screen->display, color->gc); wfree(color); } } void WMSetColorAlpha(WMColor * color, unsigned short alpha) { color->alpha = alpha; } void WMPaintColorSwatch(WMColor * color, Drawable d, int x, int y, unsigned int width, unsigned int height) { XFillRectangle(color->screen->display, d, WMColorGC(color), x, y, width, height); } WMPixel WMColorPixel(WMColor * color) { return color->color.pixel; } GC WMColorGC(WMColor * color) { if (!color->gc) { XGCValues gcv; WMScreen *scr = color->screen; gcv.foreground = color->color.pixel; gcv.graphics_exposures = False; color->gc = XCreateGC(scr->display, scr->rcontext->drawable, GCForeground | GCGraphicsExposures, &gcv); } return color->gc; } void WMSetColorInGC(WMColor * color, GC gc) { XSetForeground(color->screen->display, gc, color->color.pixel); } /* "system" colors */ WMColor *WMWhiteColor(WMScreen * scr) { if (!scr->white) { scr->white = WMCreateRGBColor(scr, 0xffff, 0xffff, 0xffff, True); if (!scr->white->flags.exact) wwarning(_("could not allocate %s color"), _("white")); } return WMRetainColor(scr->white); } WMColor *WMBlackColor(WMScreen * scr) { if (!scr->black) { scr->black = WMCreateRGBColor(scr, 0, 0, 0, True); if (!scr->black->flags.exact) wwarning(_("could not allocate %s color"), _("black")); } return WMRetainColor(scr->black); } WMColor *WMGrayColor(WMScreen * scr) { if (!scr->gray) { WMColor *color; if (scr->depth == 1) { Pixmap stipple; WMColor *white = WMWhiteColor(scr); WMColor *black = WMBlackColor(scr); XGCValues gcv; stipple = XCreateBitmapFromData(scr->display, W_DRAWABLE(scr), LIGHT_STIPPLE_BITS, LIGHT_STIPPLE_WIDTH, LIGHT_STIPPLE_HEIGHT); color = createRGBAColor(scr, 0xffff, 0xffff, 0xffff, 0xffff); gcv.foreground = white->color.pixel; gcv.background = black->color.pixel; gcv.fill_style = FillStippled; gcv.stipple = stipple; color->gc = XCreateGC(scr->display, W_DRAWABLE(scr), GCForeground | GCBackground | GCStipple | GCFillStyle | GCGraphicsExposures, &gcv); XFreePixmap(scr->display, stipple); WMReleaseColor(white); WMReleaseColor(black); } else { - color = WMCreateRGBColor(scr, 0xaeba, 0xaaaa, 0xaeba, True); + color = WMCreateRGBColor(scr, 0xaaaa, 0xaaaa, 0xaaaa, True); if (!color->flags.exact) wwarning(_("could not allocate %s color"), _("gray")); } scr->gray = color; } return WMRetainColor(scr->gray); } WMColor *WMDarkGrayColor(WMScreen * scr) { if (!scr->darkGray) { WMColor *color; if (scr->depth == 1) { Pixmap stipple; WMColor *white = WMWhiteColor(scr); WMColor *black = WMBlackColor(scr); XGCValues gcv; stipple = XCreateBitmapFromData(scr->display, W_DRAWABLE(scr), DARK_STIPPLE_BITS, DARK_STIPPLE_WIDTH, DARK_STIPPLE_HEIGHT); color = createRGBAColor(scr, 0, 0, 0, 0xffff); gcv.foreground = white->color.pixel; gcv.background = black->color.pixel; gcv.fill_style = FillStippled; gcv.stipple = stipple; color->gc = XCreateGC(scr->display, W_DRAWABLE(scr), GCForeground | GCBackground | GCStipple | GCFillStyle | GCGraphicsExposures, &gcv); XFreePixmap(scr->display, stipple); WMReleaseColor(white); WMReleaseColor(black); } else { color = WMCreateRGBColor(scr, 0x5144, 0x5555, 0x5144, True); if (!color->flags.exact) wwarning(_("could not allocate %s color"), _("dark gray")); } scr->darkGray = color; } return WMRetainColor(scr->darkGray); } unsigned short WMRedComponentOfColor(WMColor * color) { return color->color.red; } unsigned short WMGreenComponentOfColor(WMColor * color) { return color->color.green; } unsigned short WMBlueComponentOfColor(WMColor * color) { return color->color.blue; } unsigned short WMGetColorAlpha(WMColor * color) { return color->alpha; } char *WMGetColorRGBDescription(WMColor * color) { char *str = wmalloc(8); if (snprintf(str, 8, "#%02x%02x%02x", color->color.red >> 8, color->color.green >> 8, color->color.blue >> 8) >= 8) { wfree(str); return NULL; } return str; }
roblillack/wmaker
cd7bd08adcd723e348013d8c50333fb6a24d9824
Add unicode symbols (the same that are used on MacOS) representing the modifier keys in menus. (#1)
diff --git a/src/xmodifier.c b/src/xmodifier.c index 5208867..13bd41d 100644 --- a/src/xmodifier.c +++ b/src/xmodifier.c @@ -1,338 +1,338 @@ /* Grok X modifier mappings for shortcuts. Most of this code was taken from src/event-Xt.c in XEmacs 20.3-b17. The copyright(s) from the original XEmacs code are included below. Perpetrator: Sudish Joseph <[email protected]>, Sept. 1997. */ /* The event_stream interface for X11 with Xt, and/or tty frames. Copyright (C) 1991, 1992, 1993, 1994, 1995 Free Software Foundation, Inc. Copyright (C) 1995 Sun Microsystems, Inc. Copyright (C) 1996 Ben Wing. This file is part of XEmacs. XEmacs is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2, or (at your option) any later version. XEmacs is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with XEmacs; see the file COPYING. if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "wconfig.h" #include <string.h> #include <strings.h> #include <X11/Xlib.h> #include <X11/keysym.h> #include <X11/XKBlib.h> #include <WINGs/WUtil.h> #include "WindowMaker.h" #include "xmodifier.h" /************************************************************************/ /* keymap handling */ /************************************************************************/ /* X bogusly doesn't define the interpretations of any bits besides ModControl, ModShift, and ModLock; so the Interclient Communication Conventions Manual says that we have to bend over backwards to figure out what the other modifier bits mean. According to ICCCM: - Any keycode which is assigned ModControl is a "control" key. - Any modifier bit which is assigned to a keycode which generates Meta_L or Meta_R is the modifier bit meaning "meta". Likewise for Super, Hyper, etc. - Any keypress event which contains ModControl in its state should be interpreted as a "control" character. - Any keypress event which contains a modifier bit in its state which is generated by a keycode whose corresponding keysym is Meta_L or Meta_R should be interpreted as a "meta" character. Likewise for Super, Hyper, etc. - It is illegal for a keysym to be associated with more than one modifier bit. This means that the only thing that emacs can reasonably interpret as a "meta" key is a key whose keysym is Meta_L or Meta_R, and which generates one of the modifier bits Mod1-Mod5. Unfortunately, many keyboards don't have Meta keys in their default configuration. So, if there are no Meta keys, but there are "Alt" keys, emacs will interpret Alt as Meta. If there are both Meta and Alt keys, then the Meta keys mean "Meta", and the Alt keys mean "Alt" (it used to mean "Symbol," but that just confused the hell out of way too many people). This works with the default configurations of the 19 keyboard-types I've checked. Emacs detects keyboard configurations which violate the above rules, and prints an error message on the standard-error-output. (Perhaps it should use a pop-up-window instead.) */ static int MetaMask, HyperMask, SuperMask, AltMask, ModeMask; static const char *index_to_name(int indice) { switch (indice) { case ShiftMapIndex: return "ModShift"; case LockMapIndex: return "ModLock"; case ControlMapIndex: return "ModControl"; case Mod1MapIndex: return "Mod1"; case Mod2MapIndex: return "Mod2"; case Mod3MapIndex: return "Mod3"; case Mod4MapIndex: return "Mod4"; case Mod5MapIndex: return "Mod5"; default: return "???"; } } static void x_reset_modifier_mapping(Display * display) { int modifier_index, modifier_key, column, mkpm; int meta_bit = 0; int hyper_bit = 0; int super_bit = 0; int alt_bit = 0; int mode_bit = 0; XModifierKeymap *x_modifier_keymap = XGetModifierMapping(display); mkpm = x_modifier_keymap->max_keypermod; for (modifier_index = 0; modifier_index < 8; modifier_index++) for (modifier_key = 0; modifier_key < mkpm; modifier_key++) { KeySym last_sym = 0; for (column = 0; column < 4; column += 2) { KeyCode code; KeySym sym; inline void modwarn(const char *key_name, int old_mod, const char *other_key) { wwarning(_("key %s (0x%x) generates %s, which is generated by %s"), key_name, code, index_to_name(old_mod), other_key); } inline void modbarf(const char *key_name, const char *other_mod) { wwarning(_("key %s (0x%x) generates %s, which is nonsensical"), key_name, code, other_mod); } inline void check_modifier(const char *key_name, int mask) { if ((1 << modifier_index) != mask) modbarf(key_name, index_to_name(modifier_index)); } inline void store_modifier(const char *key_name, int *old_mod) { if (*old_mod && *old_mod != modifier_index) wwarning(_("key %s (0x%x) generates both %s and %s, which is nonsensical"), key_name, code, index_to_name(*old_mod), index_to_name(modifier_index)); if (modifier_index == ShiftMapIndex) { modbarf(key_name, "ModShift"); } else if (modifier_index == LockMapIndex) { modbarf(key_name, "ModLock"); } else if (modifier_index == ControlMapIndex) { modbarf(key_name, "ModControl"); } else if (sym == XK_Mode_switch) { mode_bit = modifier_index; /* Mode_switch is special, see below... */ } else if (modifier_index == meta_bit && *old_mod != meta_bit) { modwarn(key_name, meta_bit, "Meta"); } else if (modifier_index == super_bit && *old_mod != super_bit) { modwarn(key_name, super_bit, "Super"); } else if (modifier_index == hyper_bit && *old_mod != hyper_bit) { modwarn(key_name, hyper_bit, "Hyper"); } else if (modifier_index == alt_bit && *old_mod != alt_bit) { modwarn(key_name, alt_bit, "Alt"); } else { *(old_mod) = modifier_index; } } code = x_modifier_keymap->modifiermap[modifier_index * mkpm + modifier_key]; sym = (code ? XkbKeycodeToKeysym(display, code, 0, column) : NoSymbol); if (sym == last_sym) continue; last_sym = sym; switch (sym) { case XK_Mode_switch: store_modifier("Mode_switch", &mode_bit); break; case XK_Meta_L: store_modifier("Meta_L", &meta_bit); break; case XK_Meta_R: store_modifier("Meta_R", &meta_bit); break; case XK_Super_L: store_modifier("Super_L", &super_bit); break; case XK_Super_R: store_modifier("Super_R", &super_bit); break; case XK_Hyper_L: store_modifier("Hyper_L", &hyper_bit); break; case XK_Hyper_R: store_modifier("Hyper_R", &hyper_bit); break; case XK_Alt_L: store_modifier("Alt_L", &alt_bit); break; case XK_Alt_R: store_modifier("Alt_R", &alt_bit); break; case XK_Control_L: check_modifier("Control_L", ControlMask); break; case XK_Control_R: check_modifier("Control_R", ControlMask); break; case XK_Shift_L: check_modifier("Shift_L", ShiftMask); break; case XK_Shift_R: check_modifier("Shift_R", ShiftMask); break; case XK_Shift_Lock: check_modifier("Shift_Lock", LockMask); break; case XK_Caps_Lock: check_modifier("Caps_Lock", LockMask); break; /* It probably doesn't make any sense for a modifier bit to be assigned to a key that is not one of the above, but OpenWindows assigns modifier bits to a couple of random function keys for no reason that I can discern, so printing a warning here would be annoying. */ } } } /* If there was no Meta key, then try using the Alt key instead. If there is both a Meta key and an Alt key, then the Alt key is not disturbed and remains an Alt key. */ if (!meta_bit && alt_bit) meta_bit = alt_bit, alt_bit = 0; /* mode_bit overrides everything, since it's processed down inside of XLookupString() instead of by us. If Meta and Mode_switch both generate the same modifier bit (which is an error), then we don't interpret that bit as Meta, because we can't make XLookupString() not interpret it as Mode_switch; and interpreting it as both would be totally wrong. */ if (mode_bit) { const char *warn = NULL; if (mode_bit == meta_bit) warn = "Meta", meta_bit = 0; else if (mode_bit == hyper_bit) warn = "Hyper", hyper_bit = 0; else if (mode_bit == super_bit) warn = "Super", super_bit = 0; else if (mode_bit == alt_bit) warn = "Alt", alt_bit = 0; if (warn) { wwarning("%s is being used for both Mode_switch and %s.", index_to_name(mode_bit), warn); } } MetaMask = (meta_bit ? (1 << meta_bit) : 0); HyperMask = (hyper_bit ? (1 << hyper_bit) : 0); SuperMask = (super_bit ? (1 << super_bit) : 0); AltMask = (alt_bit ? (1 << alt_bit) : 0); ModeMask = (mode_bit ? (1 << mode_bit) : 0); /* unused */ XFreeModifiermap(x_modifier_keymap); } const char *wXModifierToShortcutLabel(int mask) { if (mask < 0) return NULL; if (mask == ShiftMask) - return "Sh+"; + return "\342\207\247"; // ⇧ U+21E7 UPWARDS WHITE ARROW if (mask == ControlMask) return "^"; if (mask == AltMask) - return "A+"; + return "\342\214\245"; // ⌥ U+2325 OPTION KEY if (mask == Mod1Mask) - return "M1+"; + return "\342\214\245"; // ⌥ U+2325 OPTION KEY if (mask == Mod2Mask) return "M2+"; if (mask == Mod3Mask) return "M3+"; if (mask == Mod4Mask) - return "M4+"; + return "\342\214\230"; // ⌘ U+2318 PLACE OF INTEREST SIGN if (mask == Mod5Mask) return "M5+"; if (mask == MetaMask) - return "M+"; + return "\342\231\246"; // ♦ U+2666 BLACK DIAMOND SUIT wwarning(_("Can't convert keymask 0x%04X to a shortcut label"), mask); return NULL; } int wXModifierFromKey(const char *key) { if (strcasecmp(key, "SHIFT") == 0 && ShiftMask != 0) return ShiftMask; else if (strcasecmp(key, "CONTROL") == 0 && ControlMask != 0) return ControlMask; else if (strcasecmp(key, "ALT") == 0 && AltMask != 0) return AltMask; else if (strcasecmp(key, "META") == 0 && MetaMask != 0) return MetaMask; else if (strcasecmp(key, "SUPER") == 0 && SuperMask != 0) return SuperMask; else if (strcasecmp(key, "HYPER") == 0 && HyperMask != 0) return HyperMask; else if (strcasecmp(key, "MOD1") == 0 && Mod1Mask != 0) return Mod1Mask; else if (strcasecmp(key, "MOD2") == 0 && Mod2Mask != 0) return Mod2Mask; else if (strcasecmp(key, "MOD3") == 0 && Mod3Mask != 0) return Mod3Mask; else if (strcasecmp(key, "MOD4") == 0 && Mod4Mask != 0) return Mod4Mask; else if (strcasecmp(key, "MOD5") == 0 && Mod5Mask != 0) return Mod5Mask; else return -1; } /* Wrapper so that we may fit the WM naming conventions, yet leave the original XEmacs function name in place. */ void wXModifierInitialize(void) { x_reset_modifier_mapping(dpy); }
roblillack/wmaker
09885c7335d3ad32550b0481bdac7db7c55a45d8
Add README for this fork.
diff --git a/README.md b/README.md new file mode 100644 index 0000000..4187221 --- /dev/null +++ b/README.md @@ -0,0 +1,14 @@ +# What is this? + +Window Maker is a NeXTSTEP-like window manager for the X11 Window System. + +This repository tracks the [original sources](https://repo.or.cz/w/wmaker-crm.git) +but adds some of my personal patches on top: + +- Adds unicode symbols for modified keys in menus (#1) +- Use the corrent OPENSTEP background color by default for all widgets (#2) +- Adds a margin of 3 pixels next to the dock (#3) +- Fix application menus (#4) +- Improve appicon scaling algorithm (#5) + +For more information, please check the [original README](./README.orig). diff --git a/README b/README.orig similarity index 100% rename from README rename to README.orig
roblillack/wmaker
82ab2d2d0681e327845726d3a28f27d68ce7573d
Correct calculation of usable space for reserved area.
diff --git a/src/wmspec.c b/src/wmspec.c index 645cd6c..64eaa05 100644 --- a/src/wmspec.c +++ b/src/wmspec.c @@ -336,1061 +336,1074 @@ static void setSupportedHints(WScreen *scr) atom[i++] = net_wm_window_opacity; atom[i++] = net_frame_extents; atom[i++] = net_wm_name; atom[i++] = net_wm_icon_name; XChangeProperty(dpy, scr->root_win, net_supported, XA_ATOM, 32, PropModeReplace, (unsigned char *)atom, i); /* set supporting wm hint */ XChangeProperty(dpy, scr->root_win, net_supporting_wm_check, XA_WINDOW, 32, PropModeReplace, (unsigned char *)&scr->info_window, 1); XChangeProperty(dpy, scr->info_window, net_supporting_wm_check, XA_WINDOW, 32, PropModeReplace, (unsigned char *)&scr->info_window, 1); } void wNETWMUpdateDesktop(WScreen *scr) { long *views, sizes[2]; int count, i; if (scr->workspace_count == 0) return; count = scr->workspace_count * 2; views = wmalloc(sizeof(long) * count); sizes[0] = scr->scr_width; sizes[1] = scr->scr_height; for (i = 0; i < scr->workspace_count; i++) { views[2 * i + 0] = 0; views[2 * i + 1] = 0; } XChangeProperty(dpy, scr->root_win, net_desktop_geometry, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)sizes, 2); XChangeProperty(dpy, scr->root_win, net_desktop_viewport, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)views, count); wfree(views); } int wNETWMGetCurrentDesktopFromHint(WScreen *scr) { int count; unsigned char *prop; prop = PropGetCheckProperty(scr->root_win, net_current_desktop, XA_CARDINAL, 0, 1, &count); if (prop) { int desktop = *(long *)prop; XFree(prop); return desktop; } return -1; } static RImage *makeRImageFromARGBData(unsigned long *data) { int size, width, height, i; RImage *image; unsigned char *imgdata; unsigned long pixel; width = data[0]; height = data[1]; size = width * height; if (size == 0) return NULL; image = RCreateImage(width, height, True); for (imgdata = image->data, i = 2; i < size + 2; i++, imgdata += 4) { pixel = data[i]; imgdata[3] = (pixel >> 24) & 0xff; /* A */ imgdata[0] = (pixel >> 16) & 0xff; /* R */ imgdata[1] = (pixel >> 8) & 0xff; /* G */ imgdata[2] = (pixel >> 0) & 0xff; /* B */ } return image; } /* Find the best icon to be used by Window Maker for appicon/miniwindows. */ static RImage *findBestIcon(unsigned long *data, unsigned long items) { int wanted; int dx, dy, d; int sx, sy, size; int best_d, largest; unsigned long i; unsigned long *icon; RImage *src_image, *ret_image; double f; if (wPreferences.enforce_icon_margin) { /* better use only 75% of icon_size. For 64x64 this means 48x48 * This leaves room around the icon for the miniwindow title and * results in better overall aesthetics -Dan */ wanted = (int)((double)wPreferences.icon_size * 0.75 + 0.5); /* the size should be a multiple of 4 */ wanted = (wanted >> 2) << 2; } else { /* This is the "old" approach, which tries to find the largest * icon that still fits into icon_size. */ wanted = wPreferences.icon_size; } /* try to find an icon which is close to the wanted size, but not larger */ icon = NULL; best_d = wanted * wanted * 2; for (i = 0L; i < items - 1;) { /* get the current icon's size */ sx = (int)data[i]; sy = (int)data[i + 1]; if ((sx < 1) || (sy < 1)) break; size = sx * sy + 2; /* check the size difference if it's not too large */ if ((sx <= wanted) && (sy <= wanted)) { dx = wanted - sx; dy = wanted - sy; d = (dx * dx) + (dy * dy); if (d < best_d) { icon = &data[i]; best_d = d; } } i += size; } /* if an icon has been found, no transformation is needed */ if (icon) return makeRImageFromARGBData(icon); /* We need to scale down an icon. Find the largest one, for it usually * looks better to scale down a large image by a large scale than a * small image by a small scale. */ largest = 0; for (i = 0L; i < items - 1;) { size = (int)data[i] * (int)data[i + 1]; if (size == 0) break; if (size > largest) { icon = &data[i]; largest = size; } i += size + 2; } /* give up if there's no icon to work with */ if (!icon) return NULL; /* create a scaled down version of the icon */ src_image = makeRImageFromARGBData(icon); if (src_image->width > src_image->height) { f = (double)wanted / (double)src_image->width; ret_image = RScaleImage(src_image, wanted, (int)(f * (double)(src_image->height))); } else { f = (double)wanted / (double)src_image->height; ret_image = RScaleImage(src_image, (int)(f * (double)src_image->width), wanted); } RReleaseImage(src_image); return ret_image; } RImage *get_window_image_from_x11(Window window) { RImage *image; Atom type; int format; unsigned long items, rest; unsigned long *property; /* Get the icon from X11 Window */ if (XGetWindowProperty(dpy, window, net_wm_icon, 0L, LONG_MAX, False, XA_CARDINAL, &type, &format, &items, &rest, (unsigned char **)&property) != Success || !property) return NULL; if (type != XA_CARDINAL || format != 32 || items < 2) { XFree(property); return NULL; } /* Find the best icon */ image = findBestIcon(property, items); XFree(property); if (!image) return NULL; /* Resize the image to the correct value */ image = wIconValidateIconSize(image, wPreferences.icon_size); return image; } static void updateIconImage(WWindow *wwin) { /* Remove the icon image from X11 */ if (wwin->net_icon_image) RReleaseImage(wwin->net_icon_image); /* Save the icon in the X11 icon */ wwin->net_icon_image = get_window_image_from_x11(wwin->client_win); /* Refresh the Window Icon */ if (wwin->icon) wIconUpdate(wwin->icon); /* Refresh the application icon */ WApplication *app = wApplicationOf(wwin->main_window); if (app && app->app_icon) { wIconUpdate(app->app_icon->icon); wAppIconPaint(app->app_icon); } } static void updateWindowOpacity(WWindow *wwin) { Atom type; int format; unsigned long items, rest; unsigned long *property; if (!wwin->frame) return; /* We don't care about this ourselves, but other programs need us to copy * this to the frame window. */ if (XGetWindowProperty(dpy, wwin->client_win, net_wm_window_opacity, 0L, 1L, False, XA_CARDINAL, &type, &format, &items, &rest, (unsigned char **)&property) != Success) return; if (type == None) { XDeleteProperty(dpy, wwin->frame->core->window, net_wm_window_opacity); } else if (type == XA_CARDINAL && format == 32 && items == 1 && property) { XChangeProperty(dpy, wwin->frame->core->window, net_wm_window_opacity, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)property, 1L); } if (property) XFree(property); } static void updateShowDesktop(WScreen *scr, Bool show) { long foo; foo = (show == True); XChangeProperty(dpy, scr->root_win, net_showing_desktop, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&foo, 1); } static void wNETWMShowingDesktop(WScreen *scr, Bool show) { if (show && scr->netdata->show_desktop == NULL) { WWindow *tmp, **wins; int i = 0; wins = (WWindow **) wmalloc(sizeof(WWindow *) * (scr->window_count + 1)); tmp = scr->focused_window; while (tmp) { if (!tmp->flags.hidden && !tmp->flags.miniaturized && !WFLAGP(tmp, skip_window_list)) { wins[i++] = tmp; tmp->flags.skip_next_animation = 1; tmp->flags.net_show_desktop = 1; wIconifyWindow(tmp); } tmp = tmp->prev; } wins[i++] = NULL; scr->netdata->show_desktop = wins; updateShowDesktop(scr, True); } else if (scr->netdata->show_desktop != NULL) { /* FIXME: get rid of workspace flashing ! */ int ws = scr->current_workspace; WWindow **tmp; for (tmp = scr->netdata->show_desktop; *tmp; ++tmp) { wDeiconifyWindow(*tmp); (*tmp)->flags.net_show_desktop = 0; } if (ws != scr->current_workspace) wWorkspaceChange(scr, ws); wfree(scr->netdata->show_desktop); scr->netdata->show_desktop = NULL; updateShowDesktop(scr, False); } } void wNETWMInitStuff(WScreen *scr) { NetData *data; int i; #ifdef DEBUG_WMSPEC wmessage("wNETWMInitStuff"); #endif #ifdef HAVE_XINTERNATOMS { Atom atoms[wlengthof(atomNames)]; char *names[wlengthof(atomNames)]; for (i = 0; i < wlengthof(atomNames); ++i) names[i] = atomNames[i].name; XInternAtoms(dpy, &names[0], wlengthof(atomNames), False, atoms); for (i = 0; i < wlengthof(atomNames); ++i) *atomNames[i].atom = atoms[i]; } #else for (i = 0; i < wlengthof(atomNames); i++) *atomNames[i].atom = XInternAtom(dpy, atomNames[i].name, False); #endif data = wmalloc(sizeof(NetData)); data->scr = scr; data->strut = NULL; data->show_desktop = NULL; scr->netdata = data; setSupportedHints(scr); WMAddNotificationObserver(observer, data, WMNManaged, NULL); WMAddNotificationObserver(observer, data, WMNUnmanaged, NULL); WMAddNotificationObserver(observer, data, WMNChangedWorkspace, NULL); WMAddNotificationObserver(observer, data, WMNChangedState, NULL); WMAddNotificationObserver(observer, data, WMNChangedFocus, NULL); WMAddNotificationObserver(observer, data, WMNChangedStacking, NULL); WMAddNotificationObserver(observer, data, WMNChangedName, NULL); WMAddNotificationObserver(wsobserver, data, WMNWorkspaceCreated, NULL); WMAddNotificationObserver(wsobserver, data, WMNWorkspaceDestroyed, NULL); WMAddNotificationObserver(wsobserver, data, WMNWorkspaceChanged, NULL); WMAddNotificationObserver(wsobserver, data, WMNWorkspaceNameChanged, NULL); updateClientList(scr); updateClientListStacking(scr, NULL); updateWorkspaceCount(scr); updateWorkspaceNames(scr); updateShowDesktop(scr, False); wScreenUpdateUsableArea(scr); } void wNETWMCleanup(WScreen *scr) { int i; for (i = 0; i < wlengthof(atomNames); i++) XDeleteProperty(dpy, scr->root_win, *atomNames[i].atom); } void wNETWMUpdateActions(WWindow *wwin, Bool del) { Atom action[10]; /* nr of actions atoms defined */ int i = 0; if (del) { XDeleteProperty(dpy, wwin->client_win, net_wm_allowed_actions); return; } if (IS_MOVABLE(wwin)) action[i++] = net_wm_action_move; if (IS_RESIZABLE(wwin)) action[i++] = net_wm_action_resize; if (!WFLAGP(wwin, no_miniaturizable)) action[i++] = net_wm_action_minimize; if (!WFLAGP(wwin, no_shadeable)) action[i++] = net_wm_action_shade; /* if (!WFLAGP(wwin, no_stickable)) */ action[i++] = net_wm_action_stick; /* if (!(WFLAGP(wwin, no_maximizeable) & MAX_HORIZONTAL)) */ if (IS_RESIZABLE(wwin)) action[i++] = net_wm_action_maximize_horz; /* if (!(WFLAGP(wwin, no_maximizeable) & MAX_VERTICAL)) */ if (IS_RESIZABLE(wwin)) action[i++] = net_wm_action_maximize_vert; /* if (!WFLAGP(wwin, no_fullscreen)) */ action[i++] = net_wm_action_fullscreen; /* if (!WFLAGP(wwin, no_change_desktop)) */ action[i++] = net_wm_action_change_desktop; if (!WFLAGP(wwin, no_closable)) action[i++] = net_wm_action_close; XChangeProperty(dpy, wwin->client_win, net_wm_allowed_actions, XA_ATOM, 32, PropModeReplace, (unsigned char *)action, i); } void wNETWMUpdateWorkarea(WScreen *scr) { WArea total_usable; int nb_workspace; if (!scr->netdata) { /* If the _NET_xxx were not initialised, it not necessary to do anything */ return; } if (!scr->usableArea) { /* If we don't have any info, we fall back on using the complete screen area */ total_usable.x1 = 0; total_usable.y1 = 0; total_usable.x2 = scr->scr_width; total_usable.y2 = scr->scr_height; } else { int i; /* * the _NET_WORKAREA is supposed to contain the total area of the screen that * is usable, so we merge the areas from all xrandr sub-screens */ total_usable = scr->usableArea[0]; for (i = 1; i < wXineramaHeads(scr); i++) { /* The merge is not subtle because _NET_WORKAREA does not need more */ if (scr->usableArea[i].x1 < total_usable.x1) total_usable.x1 = scr->usableArea[i].x1; if (scr->usableArea[i].y1 < total_usable.y1) total_usable.y1 = scr->usableArea[i].y1; if (scr->usableArea[i].x2 > total_usable.x2) total_usable.x2 = scr->usableArea[i].x2; if (scr->usableArea[i].y2 > total_usable.y2) total_usable.y2 = scr->usableArea[i].y2; } } /* We are expected to repeat the information for each workspace */ if (scr->workspace_count == 0) nb_workspace = 1; else nb_workspace = scr->workspace_count; { long property_value[nb_workspace * 4]; int i; for (i = 0; i < nb_workspace; i++) { property_value[4 * i + 0] = total_usable.x1; property_value[4 * i + 1] = total_usable.y1; property_value[4 * i + 2] = total_usable.x2 - total_usable.x1; property_value[4 * i + 3] = total_usable.y2 - total_usable.y1; } XChangeProperty(dpy, scr->root_win, net_workarea, XA_CARDINAL, 32, PropModeReplace, (unsigned char *) property_value, nb_workspace * 4); } } Bool wNETWMGetUsableArea(WScreen *scr, int head, WArea *area) { WReservedArea *cur; WMRect rect; if (!scr->netdata || !scr->netdata->strut) return False; area->x1 = area->y1 = area->x2 = area->y2 = 0; for (cur = scr->netdata->strut; cur; cur = cur->next) { WWindow *wwin = wWindowFor(cur->window); if (wWindowTouchesHead(wwin, head)) { if (cur->area.x1 > area->x1) area->x1 = cur->area.x1; if (cur->area.y1 > area->y1) area->y1 = cur->area.y1; if (cur->area.x2 > area->x2) area->x2 = cur->area.x2; if (cur->area.y2 > area->y2) area->y2 = cur->area.y2; } } if (area->x1 == 0 && area->x2 == 0 && area->y1 == 0 && area->y2 == 0) return False; rect = wGetRectForHead(scr, head); - /* NOTE(gryf): calculation for the reserved area should be preformed for - * current head, but area, which comes form _NET_WM_STRUT, has to be - * calculated relative to entire screen size, i.e. suppose we have three - * heads arranged like this: - * - * ╔════════════════════════╗ - * ║ 0 ║ - * ║ ╠═══════════╗ - * ║ ║ 2 ║ - * ║ ║ ║ - * ╟────────────────────────╫───────────╢ - * ╠════════════════════════╬═══════════╝ - * ║ 1 ║ - * ║ ║ - * ║ ║ - * ║ ║ - * ║ ║ - * ╟────────────────────────╢ - * ╚════════════════════════╝ - * - * where head 0 have resolution 1920x1080, head 1: 1920x1200 and head 2 - * 800x600, so the screen size in this arrangement will be 2720x2280 (1920 - * + 800) x (1080 + 1200). - * - * Bottom line represents some 3rd party panel, which sets properties in - * _NET_WM_STRUT_PARTIAL and optionally _NET_WM_STRUT. - * - * By coincidence, coordinates x1 and y1 from left and top are the same as - * the original data which came from _NET_WM_STRUT, since they meaning - * distance from the edge. - */ - - /* optional reserved space from right */ - area->x2 = scr->scr_width - area->x2; - - /* optional reserved space from bottom */ - area->y2 = scr->scr_height - area->y2; + /* NOTE(gryf): calculation for the reserved area should be preformed for + * current head, but area, which comes form _NET_WM_STRUT, has to be + * calculated relative to entire screen size, i.e. suppose we have three + * heads arranged like this: + * + * ╔════════════════════════╗ + * ║ 0 ║ + * ║ ╠═══════════╗ + * ║ ║ 2 ║ + * ║ ║ ║ + * ╟────────────────────────╫───────────╢ + * ╠════════════════════════╬═══════════╝ + * ║ 1 ║ + * ║ ║ + * ║ ║ + * ║ ║ + * ║ ║ + * ╟────────────────────────╢ + * ╚════════════════════════╝ + * + * where head 0 have resolution 1920x1080, head 1: 1920x1200 and head 2 + * 800x600, so the screen size in this arrangement will be 2720x2280 (1920 + * + 800) x (1080 + 1200). + * + * Bottom line represents some 3rd party panel, which sets properties in + * _NET_WM_STRUT_PARTIAL and optionally _NET_WM_STRUT. + * + * By coincidence, coordinates x1 and y1 from left and top are the same as + * the original data which came from _NET_WM_STRUT, since they meaning + * distance from the edge, so we leave it as-is, otherwise if they have 0 + * value, we need to set right head position. + */ + + /* optional reserved space from left */ + if (area->x1 == 0) area->x1 = rect.pos.x; + + /* optional reserved space from top */ + if (area->y1 == 0) area->y1 = rect.pos.y; + + /* optional reserved space from right */ + if (area->x2 == 0) + area->x2 = rect.pos.x + rect.size.width; + else + area->x2 = scr->scr_width - area->x2; + + /* optional reserved space from bottom */ + if (area->y2 == 0) + area->y2 = rect.pos.y + rect.size.height; + else + area->y2 = scr->scr_height - area->y2; return True; } static void updateClientList(WScreen *scr) { WWindow *wwin; Window *windows; int count; windows = (Window *) wmalloc(sizeof(Window) * (scr->window_count + 1)); count = 0; wwin = scr->focused_window; while (wwin) { windows[count++] = wwin->client_win; wwin = wwin->prev; } XChangeProperty(dpy, scr->root_win, net_client_list, XA_WINDOW, 32, PropModeReplace, (unsigned char *)windows, count); wfree(windows); XFlush(dpy); } static void updateClientListStacking(WScreen *scr, WWindow *wwin_excl) { WWindow *wwin; Window *client_list, *client_list_reverse; int client_count, i; WCoreWindow *tmp; WMBagIterator iter; /* update client list */ i = scr->window_count + 1; client_list = (Window *) wmalloc(sizeof(Window) * i); client_list_reverse = (Window *) wmalloc(sizeof(Window) * i); client_count = 0; WM_ETARETI_BAG(scr->stacking_list, tmp, iter) { while (tmp) { wwin = wWindowFor(tmp->window); /* wwin_excl is a window to exclude from the list (e.g. it's now unmanaged) */ if (wwin && (wwin != wwin_excl)) client_list[client_count++] = wwin->client_win; tmp = tmp->stacking->under; } } for (i = 0; i < client_count; i++) { Window w = client_list[client_count - i - 1]; client_list_reverse[i] = w; } XChangeProperty(dpy, scr->root_win, net_client_list_stacking, XA_WINDOW, 32, PropModeReplace, (unsigned char *)client_list_reverse, client_count); wfree(client_list); wfree(client_list_reverse); XFlush(dpy); } static void updateWorkspaceCount(WScreen *scr) { /* changeable */ long count; count = scr->workspace_count; XChangeProperty(dpy, scr->root_win, net_number_of_desktops, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&count, 1); } static void updateCurrentWorkspace(WScreen *scr) { /* changeable */ long count; count = scr->current_workspace; XChangeProperty(dpy, scr->root_win, net_current_desktop, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&count, 1); } static void updateWorkspaceNames(WScreen *scr) { char buf[MAX_WORKSPACES * (MAX_WORKSPACENAME_WIDTH + 1)], *pos; unsigned int i, len, curr_size; pos = buf; len = 0; for (i = 0; i < scr->workspace_count; i++) { curr_size = strlen(scr->workspaces[i]->name); strcpy(pos, scr->workspaces[i]->name); pos += (curr_size + 1); len += (curr_size + 1); } XChangeProperty(dpy, scr->root_win, net_desktop_names, utf8_string, 8, PropModeReplace, (unsigned char *)buf, len); } static void updateFocusHint(WScreen *scr) { /* changeable */ Window window; if (!scr->focused_window || !scr->focused_window->flags.focused) window = None; else window = scr->focused_window->client_win; XChangeProperty(dpy, scr->root_win, net_active_window, XA_WINDOW, 32, PropModeReplace, (unsigned char *)&window, 1); } static void updateWorkspaceHint(WWindow *wwin, Bool fake, Bool del) { long l; if (del) { XDeleteProperty(dpy, wwin->client_win, net_wm_desktop); } else { l = ((fake || IS_OMNIPRESENT(wwin)) ? -1 : wwin->frame->workspace); XChangeProperty(dpy, wwin->client_win, net_wm_desktop, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&l, 1); } } static void updateStateHint(WWindow *wwin, Bool changedWorkspace, Bool del) { /* changeable */ if (del) { XDeleteProperty(dpy, wwin->client_win, net_wm_state); } else { Atom state[15]; /* nr of defined state atoms */ int i = 0; if (changedWorkspace || (wPreferences.sticky_icons && !IS_OMNIPRESENT(wwin))) updateWorkspaceHint(wwin, False, False); if (IS_OMNIPRESENT(wwin)) state[i++] = net_wm_state_sticky; if (wwin->flags.shaded) state[i++] = net_wm_state_shaded; if (wwin->flags.maximized & MAX_HORIZONTAL) state[i++] = net_wm_state_maximized_horz; if (wwin->flags.maximized & MAX_VERTICAL) state[i++] = net_wm_state_maximized_vert; if (WFLAGP(wwin, skip_window_list)) state[i++] = net_wm_state_skip_taskbar; if (wwin->flags.net_skip_pager) state[i++] = net_wm_state_skip_pager; if ((wwin->flags.hidden || wwin->flags.miniaturized) && !wwin->flags.net_show_desktop) { state[i++] = net_wm_state_hidden; state[i++] = net_wm_state_skip_pager; if (wwin->flags.miniaturized && wPreferences.sticky_icons) { if (!IS_OMNIPRESENT(wwin)) updateWorkspaceHint(wwin, True, False); state[i++] = net_wm_state_sticky; } } if (WFLAGP(wwin, sunken)) state[i++] = net_wm_state_below; if (WFLAGP(wwin, floating)) state[i++] = net_wm_state_above; if (wwin->flags.fullscreen) state[i++] = net_wm_state_fullscreen; if (wwin->flags.focused) state[i++] = net_wm_state_focused; XChangeProperty(dpy, wwin->client_win, net_wm_state, XA_ATOM, 32, PropModeReplace, (unsigned char *)state, i); } } static Bool updateStrut(WScreen *scr, Window w, Bool adding) { WReservedArea *area; Bool hasState = False; if (adding) { Atom type_ret; int fmt_ret; unsigned long nitems_ret, bytes_after_ret; long *data = NULL; if ((XGetWindowProperty(dpy, w, net_wm_strut, 0, 4, False, XA_CARDINAL, &type_ret, &fmt_ret, &nitems_ret, &bytes_after_ret, (unsigned char **)&data) == Success && data) || ((XGetWindowProperty(dpy, w, net_wm_strut_partial, 0, 12, False, XA_CARDINAL, &type_ret, &fmt_ret, &nitems_ret, &bytes_after_ret, (unsigned char **)&data) == Success && data))) { /* XXX: This is strictly incorrect in the case of net_wm_strut_partial... * Discard the start and end properties from the partial strut and treat it as * a (deprecated) strut. * This means we are marking the whole width or height of the screen as * reserved, which is not necessarily what the strut defines. However for the * purposes of determining placement or maximization it's probably good enough. */ area = (WReservedArea *) wmalloc(sizeof(WReservedArea)); area->area.x1 = data[0]; area->area.x2 = data[1]; area->area.y1 = data[2]; area->area.y2 = data[3]; area->window = w; area->next = scr->netdata->strut; scr->netdata->strut = area; XFree(data); hasState = True; } } else { /* deleting */ area = scr->netdata->strut; if (area) { if (area->window == w) { scr->netdata->strut = area->next; wfree(area); hasState = True; } else { while (area->next && area->next->window != w) area = area->next; if (area->next) { WReservedArea *next; next = area->next->next; wfree(area->next); area->next = next; hasState = True; } } } } return hasState; } static int getWindowLayer(WWindow *wwin) { int layer = WMNormalLevel; if (wwin->type == net_wm_window_type_desktop) { layer = WMDesktopLevel; } else if (wwin->type == net_wm_window_type_dock) { layer = WMDockLevel; } else if (wwin->type == net_wm_window_type_toolbar) { layer = WMMainMenuLevel; } else if (wwin->type == net_wm_window_type_menu) { layer = WMSubmenuLevel; } else if (wwin->type == net_wm_window_type_utility) { } else if (wwin->type == net_wm_window_type_splash) { } else if (wwin->type == net_wm_window_type_dialog) { if (wwin->transient_for) { WWindow *parent = wWindowFor(wwin->transient_for); if (parent && parent->flags.fullscreen) layer = WMFullscreenLevel; } /* //layer = WMPopUpLevel; // this seems a bad idea -Dan */ } else if (wwin->type == net_wm_window_type_dropdown_menu) { layer = WMSubmenuLevel; } else if (wwin->type == net_wm_window_type_popup_menu) { layer = WMSubmenuLevel; } else if (wwin->type == net_wm_window_type_tooltip) { } else if (wwin->type == net_wm_window_type_notification) { layer = WMPopUpLevel; } else if (wwin->type == net_wm_window_type_combo) { layer = WMSubmenuLevel; } else if (wwin->type == net_wm_window_type_dnd) { } else if (wwin->type == net_wm_window_type_normal) { } if (wwin->client_flags.sunken && WMSunkenLevel < layer) layer = WMSunkenLevel; if (wwin->client_flags.floating && WMFloatingLevel > layer) layer = WMFloatingLevel; return layer; } static void doStateAtom(WWindow *wwin, Atom state, int set, Bool init) { if (state == net_wm_state_sticky) { if (set == _NET_WM_STATE_TOGGLE) set = !IS_OMNIPRESENT(wwin); if (set != wwin->flags.omnipresent) wWindowSetOmnipresent(wwin, set); } else if (state == net_wm_state_shaded) { if (set == _NET_WM_STATE_TOGGLE) set = !wwin->flags.shaded; if (init) { wwin->flags.shaded = set; } else { if (set) wShadeWindow(wwin); else wUnshadeWindow(wwin); } } else if (state == net_wm_state_skip_taskbar) { if (set == _NET_WM_STATE_TOGGLE) set = !wwin->client_flags.skip_window_list; wwin->client_flags.skip_window_list = set; } else if (state == net_wm_state_skip_pager) { if (set == _NET_WM_STATE_TOGGLE) set = !wwin->flags.net_skip_pager; wwin->flags.net_skip_pager = set; } else if (state == net_wm_state_maximized_vert) { if (set == _NET_WM_STATE_TOGGLE) set = !(wwin->flags.maximized & MAX_VERTICAL); if (init) { wwin->flags.maximized |= (set ? MAX_VERTICAL : 0); } else { if (set) wMaximizeWindow(wwin, wwin->flags.maximized | MAX_VERTICAL, wGetHeadForWindow(wwin)); else wMaximizeWindow(wwin, wwin->flags.maximized & ~MAX_VERTICAL, wGetHeadForWindow(wwin)); } } else if (state == net_wm_state_maximized_horz) { if (set == _NET_WM_STATE_TOGGLE) set = !(wwin->flags.maximized & MAX_HORIZONTAL); if (init) { wwin->flags.maximized |= (set ? MAX_HORIZONTAL : 0); } else { if (set) wMaximizeWindow(wwin, wwin->flags.maximized | MAX_HORIZONTAL, wGetHeadForWindow(wwin)); else wMaximizeWindow(wwin, wwin->flags.maximized & ~MAX_HORIZONTAL, wGetHeadForWindow(wwin)); } } else if (state == net_wm_state_hidden) { if (set == _NET_WM_STATE_TOGGLE) set = !(wwin->flags.miniaturized); if (init) { wwin->flags.miniaturized = set; } else { if (set) wIconifyWindow(wwin); else wDeiconifyWindow(wwin); } } else if (state == net_wm_state_fullscreen) { if (set == _NET_WM_STATE_TOGGLE) set = !(wwin->flags.fullscreen); if (init) { wwin->flags.fullscreen = set; } else { if (set) wFullscreenWindow(wwin); else wUnfullscreenWindow(wwin); } } else if (state == net_wm_state_above) { if (set == _NET_WM_STATE_TOGGLE) set = !(wwin->client_flags.floating); if (init) { wwin->client_flags.floating = set; } else { wwin->client_flags.floating = set; ChangeStackingLevel(wwin->frame->core, getWindowLayer(wwin)); } } else if (state == net_wm_state_below) { if (set == _NET_WM_STATE_TOGGLE) set = !(wwin->client_flags.sunken); if (init) { wwin->client_flags.sunken = set; } else { wwin->client_flags.sunken = set; ChangeStackingLevel(wwin->frame->core, getWindowLayer(wwin)); } } else { #ifdef DEBUG_WMSPEC wmessage("doStateAtom unknown atom %s set %d", XGetAtomName(dpy, state), set); #endif } } static void removeIcon(WWindow *wwin) { if (wwin->icon == NULL) return; if (wwin->flags.miniaturized && wwin->icon->mapped) { XUnmapWindow(dpy, wwin->icon->core->window); RemoveFromStackList(wwin->icon->core); wIconDestroy(wwin->icon); wwin->icon = NULL; } } static Bool handleWindowType(WWindow *wwin, Atom type, int *layer) { Bool ret = True; if (type == net_wm_window_type_desktop) { wwin->client_flags.no_titlebar = 1; wwin->client_flags.no_resizable = 1; wwin->client_flags.no_miniaturizable = 1; wwin->client_flags.no_border = 1; wwin->client_flags.no_resizebar = 1; wwin->client_flags.no_shadeable = 1; wwin->client_flags.no_movable = 1; wwin->client_flags.omnipresent = 1; wwin->client_flags.skip_window_list = 1; wwin->client_flags.skip_switchpanel = 1; wwin->client_flags.dont_move_off = 1; wwin->client_flags.no_appicon = 1; wwin->flags.net_skip_pager = 1; wwin->frame_x = 0; wwin->frame_y = 0; } else if (type == net_wm_window_type_dock) { wwin->client_flags.no_titlebar = 1; wwin->client_flags.no_resizable = 1; wwin->client_flags.no_miniaturizable = 1; wwin->client_flags.no_border = 1; /* XXX: really not a single decoration. */ wwin->client_flags.no_resizebar = 1; wwin->client_flags.no_shadeable = 1; wwin->client_flags.no_movable = 1; wwin->client_flags.omnipresent = 1; wwin->client_flags.skip_window_list = 1; wwin->client_flags.skip_switchpanel = 1; wwin->client_flags.dont_move_off = 1; wwin->flags.net_skip_pager = 1; } else if (type == net_wm_window_type_toolbar || type == net_wm_window_type_menu) { wwin->client_flags.no_resizable = 1; wwin->client_flags.no_miniaturizable = 1; wwin->client_flags.no_resizebar = 1; wwin->client_flags.no_shadeable = 1; wwin->client_flags.skip_window_list = 1; wwin->client_flags.skip_switchpanel = 1; wwin->client_flags.dont_move_off = 1; wwin->client_flags.no_appicon = 1; } else if (type == net_wm_window_type_dropdown_menu || type == net_wm_window_type_popup_menu || type == net_wm_window_type_combo) { wwin->client_flags.no_titlebar = 1; wwin->client_flags.no_resizable = 1; wwin->client_flags.no_miniaturizable = 1; wwin->client_flags.no_resizebar = 1; wwin->client_flags.no_shadeable = 1; wwin->client_flags.skip_window_list = 1; wwin->client_flags.skip_switchpanel = 1; wwin->client_flags.dont_move_off = 1; wwin->client_flags.no_appicon = 1; } else if (type == net_wm_window_type_utility) { wwin->client_flags.no_appicon = 1; } else if (type == net_wm_window_type_splash) { wwin->client_flags.no_titlebar = 1; wwin->client_flags.no_resizable = 1; wwin->client_flags.no_miniaturizable = 1; wwin->client_flags.no_resizebar = 1; wwin->client_flags.no_shadeable = 1; wwin->client_flags.no_movable = 1; wwin->client_flags.skip_window_list = 1; wwin->client_flags.skip_switchpanel = 1; wwin->client_flags.dont_move_off = 1; wwin->client_flags.no_appicon = 1; wwin->flags.net_skip_pager = 1; } else if (type == net_wm_window_type_dialog) { /* These also seem a bad idea in our context -Dan // wwin->client_flags.skip_window_list = 1; // wwin->client_flags.no_appicon = 1; */ } else if (wwin->type == net_wm_window_type_tooltip) { wwin->client_flags.no_titlebar = 1; wwin->client_flags.no_resizable = 1; wwin->client_flags.no_miniaturizable = 1; wwin->client_flags.no_resizebar = 1; wwin->client_flags.no_shadeable = 1; wwin->client_flags.no_movable = 1; wwin->client_flags.skip_window_list = 1; wwin->client_flags.skip_switchpanel = 1; wwin->client_flags.dont_move_off = 1; wwin->client_flags.no_appicon = 1; wwin->client_flags.no_focusable = 1; wwin->flags.net_skip_pager = 1; } else if (wwin->type == net_wm_window_type_notification) { wwin->client_flags.no_titlebar = 1; wwin->client_flags.no_resizable = 1; wwin->client_flags.no_miniaturizable = 1; wwin->client_flags.no_border = 1; wwin->client_flags.no_resizebar = 1; wwin->client_flags.no_shadeable = 1; wwin->client_flags.no_movable = 1; wwin->client_flags.omnipresent = 1; wwin->client_flags.skip_window_list = 1; wwin->client_flags.skip_switchpanel = 1; wwin->client_flags.dont_move_off = 1; wwin->client_flags.no_hide_others= 1; wwin->client_flags.no_appicon = 1; wwin->client_flags.no_focusable = 1; wwin->flags.net_skip_pager = 1;
roblillack/wmaker
bbf24d1d398e0dbcbfe0be66b5ab358d49b3c803
Correct way for reserved space on multihead environment.
diff --git a/src/wmspec.c b/src/wmspec.c index 57a72d1..645cd6c 100644 --- a/src/wmspec.c +++ b/src/wmspec.c @@ -336,1028 +336,1061 @@ static void setSupportedHints(WScreen *scr) atom[i++] = net_wm_window_opacity; atom[i++] = net_frame_extents; atom[i++] = net_wm_name; atom[i++] = net_wm_icon_name; XChangeProperty(dpy, scr->root_win, net_supported, XA_ATOM, 32, PropModeReplace, (unsigned char *)atom, i); /* set supporting wm hint */ XChangeProperty(dpy, scr->root_win, net_supporting_wm_check, XA_WINDOW, 32, PropModeReplace, (unsigned char *)&scr->info_window, 1); XChangeProperty(dpy, scr->info_window, net_supporting_wm_check, XA_WINDOW, 32, PropModeReplace, (unsigned char *)&scr->info_window, 1); } void wNETWMUpdateDesktop(WScreen *scr) { long *views, sizes[2]; int count, i; if (scr->workspace_count == 0) return; count = scr->workspace_count * 2; views = wmalloc(sizeof(long) * count); sizes[0] = scr->scr_width; sizes[1] = scr->scr_height; for (i = 0; i < scr->workspace_count; i++) { views[2 * i + 0] = 0; views[2 * i + 1] = 0; } XChangeProperty(dpy, scr->root_win, net_desktop_geometry, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)sizes, 2); XChangeProperty(dpy, scr->root_win, net_desktop_viewport, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)views, count); wfree(views); } int wNETWMGetCurrentDesktopFromHint(WScreen *scr) { int count; unsigned char *prop; prop = PropGetCheckProperty(scr->root_win, net_current_desktop, XA_CARDINAL, 0, 1, &count); if (prop) { int desktop = *(long *)prop; XFree(prop); return desktop; } return -1; } static RImage *makeRImageFromARGBData(unsigned long *data) { int size, width, height, i; RImage *image; unsigned char *imgdata; unsigned long pixel; width = data[0]; height = data[1]; size = width * height; if (size == 0) return NULL; image = RCreateImage(width, height, True); for (imgdata = image->data, i = 2; i < size + 2; i++, imgdata += 4) { pixel = data[i]; imgdata[3] = (pixel >> 24) & 0xff; /* A */ imgdata[0] = (pixel >> 16) & 0xff; /* R */ imgdata[1] = (pixel >> 8) & 0xff; /* G */ imgdata[2] = (pixel >> 0) & 0xff; /* B */ } return image; } /* Find the best icon to be used by Window Maker for appicon/miniwindows. */ static RImage *findBestIcon(unsigned long *data, unsigned long items) { int wanted; int dx, dy, d; int sx, sy, size; int best_d, largest; unsigned long i; unsigned long *icon; RImage *src_image, *ret_image; double f; if (wPreferences.enforce_icon_margin) { /* better use only 75% of icon_size. For 64x64 this means 48x48 * This leaves room around the icon for the miniwindow title and * results in better overall aesthetics -Dan */ wanted = (int)((double)wPreferences.icon_size * 0.75 + 0.5); /* the size should be a multiple of 4 */ wanted = (wanted >> 2) << 2; } else { /* This is the "old" approach, which tries to find the largest * icon that still fits into icon_size. */ wanted = wPreferences.icon_size; } /* try to find an icon which is close to the wanted size, but not larger */ icon = NULL; best_d = wanted * wanted * 2; for (i = 0L; i < items - 1;) { /* get the current icon's size */ sx = (int)data[i]; sy = (int)data[i + 1]; if ((sx < 1) || (sy < 1)) break; size = sx * sy + 2; /* check the size difference if it's not too large */ if ((sx <= wanted) && (sy <= wanted)) { dx = wanted - sx; dy = wanted - sy; d = (dx * dx) + (dy * dy); if (d < best_d) { icon = &data[i]; best_d = d; } } i += size; } /* if an icon has been found, no transformation is needed */ if (icon) return makeRImageFromARGBData(icon); /* We need to scale down an icon. Find the largest one, for it usually * looks better to scale down a large image by a large scale than a * small image by a small scale. */ largest = 0; for (i = 0L; i < items - 1;) { size = (int)data[i] * (int)data[i + 1]; if (size == 0) break; if (size > largest) { icon = &data[i]; largest = size; } i += size + 2; } /* give up if there's no icon to work with */ if (!icon) return NULL; /* create a scaled down version of the icon */ src_image = makeRImageFromARGBData(icon); if (src_image->width > src_image->height) { f = (double)wanted / (double)src_image->width; ret_image = RScaleImage(src_image, wanted, (int)(f * (double)(src_image->height))); } else { f = (double)wanted / (double)src_image->height; ret_image = RScaleImage(src_image, (int)(f * (double)src_image->width), wanted); } RReleaseImage(src_image); return ret_image; } RImage *get_window_image_from_x11(Window window) { RImage *image; Atom type; int format; unsigned long items, rest; unsigned long *property; /* Get the icon from X11 Window */ if (XGetWindowProperty(dpy, window, net_wm_icon, 0L, LONG_MAX, False, XA_CARDINAL, &type, &format, &items, &rest, (unsigned char **)&property) != Success || !property) return NULL; if (type != XA_CARDINAL || format != 32 || items < 2) { XFree(property); return NULL; } /* Find the best icon */ image = findBestIcon(property, items); XFree(property); if (!image) return NULL; /* Resize the image to the correct value */ image = wIconValidateIconSize(image, wPreferences.icon_size); return image; } static void updateIconImage(WWindow *wwin) { /* Remove the icon image from X11 */ if (wwin->net_icon_image) RReleaseImage(wwin->net_icon_image); /* Save the icon in the X11 icon */ wwin->net_icon_image = get_window_image_from_x11(wwin->client_win); /* Refresh the Window Icon */ if (wwin->icon) wIconUpdate(wwin->icon); /* Refresh the application icon */ WApplication *app = wApplicationOf(wwin->main_window); if (app && app->app_icon) { wIconUpdate(app->app_icon->icon); wAppIconPaint(app->app_icon); } } static void updateWindowOpacity(WWindow *wwin) { Atom type; int format; unsigned long items, rest; unsigned long *property; if (!wwin->frame) return; /* We don't care about this ourselves, but other programs need us to copy * this to the frame window. */ if (XGetWindowProperty(dpy, wwin->client_win, net_wm_window_opacity, 0L, 1L, False, XA_CARDINAL, &type, &format, &items, &rest, (unsigned char **)&property) != Success) return; if (type == None) { XDeleteProperty(dpy, wwin->frame->core->window, net_wm_window_opacity); } else if (type == XA_CARDINAL && format == 32 && items == 1 && property) { XChangeProperty(dpy, wwin->frame->core->window, net_wm_window_opacity, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)property, 1L); } if (property) XFree(property); } static void updateShowDesktop(WScreen *scr, Bool show) { long foo; foo = (show == True); XChangeProperty(dpy, scr->root_win, net_showing_desktop, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&foo, 1); } static void wNETWMShowingDesktop(WScreen *scr, Bool show) { if (show && scr->netdata->show_desktop == NULL) { WWindow *tmp, **wins; int i = 0; wins = (WWindow **) wmalloc(sizeof(WWindow *) * (scr->window_count + 1)); tmp = scr->focused_window; while (tmp) { if (!tmp->flags.hidden && !tmp->flags.miniaturized && !WFLAGP(tmp, skip_window_list)) { wins[i++] = tmp; tmp->flags.skip_next_animation = 1; tmp->flags.net_show_desktop = 1; wIconifyWindow(tmp); } tmp = tmp->prev; } wins[i++] = NULL; scr->netdata->show_desktop = wins; updateShowDesktop(scr, True); } else if (scr->netdata->show_desktop != NULL) { /* FIXME: get rid of workspace flashing ! */ int ws = scr->current_workspace; WWindow **tmp; for (tmp = scr->netdata->show_desktop; *tmp; ++tmp) { wDeiconifyWindow(*tmp); (*tmp)->flags.net_show_desktop = 0; } if (ws != scr->current_workspace) wWorkspaceChange(scr, ws); wfree(scr->netdata->show_desktop); scr->netdata->show_desktop = NULL; updateShowDesktop(scr, False); } } void wNETWMInitStuff(WScreen *scr) { NetData *data; int i; #ifdef DEBUG_WMSPEC wmessage("wNETWMInitStuff"); #endif #ifdef HAVE_XINTERNATOMS { Atom atoms[wlengthof(atomNames)]; char *names[wlengthof(atomNames)]; for (i = 0; i < wlengthof(atomNames); ++i) names[i] = atomNames[i].name; XInternAtoms(dpy, &names[0], wlengthof(atomNames), False, atoms); for (i = 0; i < wlengthof(atomNames); ++i) *atomNames[i].atom = atoms[i]; } #else for (i = 0; i < wlengthof(atomNames); i++) *atomNames[i].atom = XInternAtom(dpy, atomNames[i].name, False); #endif data = wmalloc(sizeof(NetData)); data->scr = scr; data->strut = NULL; data->show_desktop = NULL; scr->netdata = data; setSupportedHints(scr); WMAddNotificationObserver(observer, data, WMNManaged, NULL); WMAddNotificationObserver(observer, data, WMNUnmanaged, NULL); WMAddNotificationObserver(observer, data, WMNChangedWorkspace, NULL); WMAddNotificationObserver(observer, data, WMNChangedState, NULL); WMAddNotificationObserver(observer, data, WMNChangedFocus, NULL); WMAddNotificationObserver(observer, data, WMNChangedStacking, NULL); WMAddNotificationObserver(observer, data, WMNChangedName, NULL); WMAddNotificationObserver(wsobserver, data, WMNWorkspaceCreated, NULL); WMAddNotificationObserver(wsobserver, data, WMNWorkspaceDestroyed, NULL); WMAddNotificationObserver(wsobserver, data, WMNWorkspaceChanged, NULL); WMAddNotificationObserver(wsobserver, data, WMNWorkspaceNameChanged, NULL); updateClientList(scr); updateClientListStacking(scr, NULL); updateWorkspaceCount(scr); updateWorkspaceNames(scr); updateShowDesktop(scr, False); wScreenUpdateUsableArea(scr); } void wNETWMCleanup(WScreen *scr) { int i; for (i = 0; i < wlengthof(atomNames); i++) XDeleteProperty(dpy, scr->root_win, *atomNames[i].atom); } void wNETWMUpdateActions(WWindow *wwin, Bool del) { Atom action[10]; /* nr of actions atoms defined */ int i = 0; if (del) { XDeleteProperty(dpy, wwin->client_win, net_wm_allowed_actions); return; } if (IS_MOVABLE(wwin)) action[i++] = net_wm_action_move; if (IS_RESIZABLE(wwin)) action[i++] = net_wm_action_resize; if (!WFLAGP(wwin, no_miniaturizable)) action[i++] = net_wm_action_minimize; if (!WFLAGP(wwin, no_shadeable)) action[i++] = net_wm_action_shade; /* if (!WFLAGP(wwin, no_stickable)) */ action[i++] = net_wm_action_stick; /* if (!(WFLAGP(wwin, no_maximizeable) & MAX_HORIZONTAL)) */ if (IS_RESIZABLE(wwin)) action[i++] = net_wm_action_maximize_horz; /* if (!(WFLAGP(wwin, no_maximizeable) & MAX_VERTICAL)) */ if (IS_RESIZABLE(wwin)) action[i++] = net_wm_action_maximize_vert; /* if (!WFLAGP(wwin, no_fullscreen)) */ action[i++] = net_wm_action_fullscreen; /* if (!WFLAGP(wwin, no_change_desktop)) */ action[i++] = net_wm_action_change_desktop; if (!WFLAGP(wwin, no_closable)) action[i++] = net_wm_action_close; XChangeProperty(dpy, wwin->client_win, net_wm_allowed_actions, XA_ATOM, 32, PropModeReplace, (unsigned char *)action, i); } void wNETWMUpdateWorkarea(WScreen *scr) { WArea total_usable; int nb_workspace; if (!scr->netdata) { /* If the _NET_xxx were not initialised, it not necessary to do anything */ return; } if (!scr->usableArea) { /* If we don't have any info, we fall back on using the complete screen area */ total_usable.x1 = 0; total_usable.y1 = 0; total_usable.x2 = scr->scr_width; total_usable.y2 = scr->scr_height; } else { int i; /* * the _NET_WORKAREA is supposed to contain the total area of the screen that * is usable, so we merge the areas from all xrandr sub-screens */ total_usable = scr->usableArea[0]; for (i = 1; i < wXineramaHeads(scr); i++) { /* The merge is not subtle because _NET_WORKAREA does not need more */ if (scr->usableArea[i].x1 < total_usable.x1) total_usable.x1 = scr->usableArea[i].x1; if (scr->usableArea[i].y1 < total_usable.y1) total_usable.y1 = scr->usableArea[i].y1; if (scr->usableArea[i].x2 > total_usable.x2) total_usable.x2 = scr->usableArea[i].x2; if (scr->usableArea[i].y2 > total_usable.y2) total_usable.y2 = scr->usableArea[i].y2; } } /* We are expected to repeat the information for each workspace */ if (scr->workspace_count == 0) nb_workspace = 1; else nb_workspace = scr->workspace_count; { long property_value[nb_workspace * 4]; int i; for (i = 0; i < nb_workspace; i++) { property_value[4 * i + 0] = total_usable.x1; property_value[4 * i + 1] = total_usable.y1; property_value[4 * i + 2] = total_usable.x2 - total_usable.x1; property_value[4 * i + 3] = total_usable.y2 - total_usable.y1; } XChangeProperty(dpy, scr->root_win, net_workarea, XA_CARDINAL, 32, PropModeReplace, (unsigned char *) property_value, nb_workspace * 4); } } Bool wNETWMGetUsableArea(WScreen *scr, int head, WArea *area) { WReservedArea *cur; WMRect rect; if (!scr->netdata || !scr->netdata->strut) return False; area->x1 = area->y1 = area->x2 = area->y2 = 0; for (cur = scr->netdata->strut; cur; cur = cur->next) { WWindow *wwin = wWindowFor(cur->window); if (wWindowTouchesHead(wwin, head)) { if (cur->area.x1 > area->x1) area->x1 = cur->area.x1; if (cur->area.y1 > area->y1) area->y1 = cur->area.y1; if (cur->area.x2 > area->x2) area->x2 = cur->area.x2; if (cur->area.y2 > area->y2) area->y2 = cur->area.y2; } } if (area->x1 == 0 && area->x2 == 0 && area->y1 == 0 && area->y2 == 0) return False; rect = wGetRectForHead(scr, head); - area->x1 = rect.pos.x + area->x1; - area->x2 = rect.pos.x + rect.size.width - area->x2; - area->y1 = rect.pos.y + area->y1; - area->y2 = rect.pos.y + rect.size.height - area->y2; + /* NOTE(gryf): calculation for the reserved area should be preformed for + * current head, but area, which comes form _NET_WM_STRUT, has to be + * calculated relative to entire screen size, i.e. suppose we have three + * heads arranged like this: + * + * ╔════════════════════════╗ + * ║ 0 ║ + * ║ ╠═══════════╗ + * ║ ║ 2 ║ + * ║ ║ ║ + * ╟────────────────────────╫───────────╢ + * ╠════════════════════════╬═══════════╝ + * ║ 1 ║ + * ║ ║ + * ║ ║ + * ║ ║ + * ║ ║ + * ╟────────────────────────╢ + * ╚════════════════════════╝ + * + * where head 0 have resolution 1920x1080, head 1: 1920x1200 and head 2 + * 800x600, so the screen size in this arrangement will be 2720x2280 (1920 + * + 800) x (1080 + 1200). + * + * Bottom line represents some 3rd party panel, which sets properties in + * _NET_WM_STRUT_PARTIAL and optionally _NET_WM_STRUT. + * + * By coincidence, coordinates x1 and y1 from left and top are the same as + * the original data which came from _NET_WM_STRUT, since they meaning + * distance from the edge. + */ + + /* optional reserved space from right */ + area->x2 = scr->scr_width - area->x2; + + /* optional reserved space from bottom */ + area->y2 = scr->scr_height - area->y2; return True; } static void updateClientList(WScreen *scr) { WWindow *wwin; Window *windows; int count; windows = (Window *) wmalloc(sizeof(Window) * (scr->window_count + 1)); count = 0; wwin = scr->focused_window; while (wwin) { windows[count++] = wwin->client_win; wwin = wwin->prev; } XChangeProperty(dpy, scr->root_win, net_client_list, XA_WINDOW, 32, PropModeReplace, (unsigned char *)windows, count); wfree(windows); XFlush(dpy); } static void updateClientListStacking(WScreen *scr, WWindow *wwin_excl) { WWindow *wwin; Window *client_list, *client_list_reverse; int client_count, i; WCoreWindow *tmp; WMBagIterator iter; /* update client list */ i = scr->window_count + 1; client_list = (Window *) wmalloc(sizeof(Window) * i); client_list_reverse = (Window *) wmalloc(sizeof(Window) * i); client_count = 0; WM_ETARETI_BAG(scr->stacking_list, tmp, iter) { while (tmp) { wwin = wWindowFor(tmp->window); /* wwin_excl is a window to exclude from the list (e.g. it's now unmanaged) */ if (wwin && (wwin != wwin_excl)) client_list[client_count++] = wwin->client_win; tmp = tmp->stacking->under; } } for (i = 0; i < client_count; i++) { Window w = client_list[client_count - i - 1]; client_list_reverse[i] = w; } XChangeProperty(dpy, scr->root_win, net_client_list_stacking, XA_WINDOW, 32, PropModeReplace, (unsigned char *)client_list_reverse, client_count); wfree(client_list); wfree(client_list_reverse); XFlush(dpy); } static void updateWorkspaceCount(WScreen *scr) { /* changeable */ long count; count = scr->workspace_count; XChangeProperty(dpy, scr->root_win, net_number_of_desktops, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&count, 1); } static void updateCurrentWorkspace(WScreen *scr) { /* changeable */ long count; count = scr->current_workspace; XChangeProperty(dpy, scr->root_win, net_current_desktop, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&count, 1); } static void updateWorkspaceNames(WScreen *scr) { char buf[MAX_WORKSPACES * (MAX_WORKSPACENAME_WIDTH + 1)], *pos; unsigned int i, len, curr_size; pos = buf; len = 0; for (i = 0; i < scr->workspace_count; i++) { curr_size = strlen(scr->workspaces[i]->name); strcpy(pos, scr->workspaces[i]->name); pos += (curr_size + 1); len += (curr_size + 1); } XChangeProperty(dpy, scr->root_win, net_desktop_names, utf8_string, 8, PropModeReplace, (unsigned char *)buf, len); } static void updateFocusHint(WScreen *scr) { /* changeable */ Window window; if (!scr->focused_window || !scr->focused_window->flags.focused) window = None; else window = scr->focused_window->client_win; XChangeProperty(dpy, scr->root_win, net_active_window, XA_WINDOW, 32, PropModeReplace, (unsigned char *)&window, 1); } static void updateWorkspaceHint(WWindow *wwin, Bool fake, Bool del) { long l; if (del) { XDeleteProperty(dpy, wwin->client_win, net_wm_desktop); } else { l = ((fake || IS_OMNIPRESENT(wwin)) ? -1 : wwin->frame->workspace); XChangeProperty(dpy, wwin->client_win, net_wm_desktop, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&l, 1); } } static void updateStateHint(WWindow *wwin, Bool changedWorkspace, Bool del) { /* changeable */ if (del) { XDeleteProperty(dpy, wwin->client_win, net_wm_state); } else { Atom state[15]; /* nr of defined state atoms */ int i = 0; if (changedWorkspace || (wPreferences.sticky_icons && !IS_OMNIPRESENT(wwin))) updateWorkspaceHint(wwin, False, False); if (IS_OMNIPRESENT(wwin)) state[i++] = net_wm_state_sticky; if (wwin->flags.shaded) state[i++] = net_wm_state_shaded; if (wwin->flags.maximized & MAX_HORIZONTAL) state[i++] = net_wm_state_maximized_horz; if (wwin->flags.maximized & MAX_VERTICAL) state[i++] = net_wm_state_maximized_vert; if (WFLAGP(wwin, skip_window_list)) state[i++] = net_wm_state_skip_taskbar; if (wwin->flags.net_skip_pager) state[i++] = net_wm_state_skip_pager; if ((wwin->flags.hidden || wwin->flags.miniaturized) && !wwin->flags.net_show_desktop) { state[i++] = net_wm_state_hidden; state[i++] = net_wm_state_skip_pager; if (wwin->flags.miniaturized && wPreferences.sticky_icons) { if (!IS_OMNIPRESENT(wwin)) updateWorkspaceHint(wwin, True, False); state[i++] = net_wm_state_sticky; } } if (WFLAGP(wwin, sunken)) state[i++] = net_wm_state_below; if (WFLAGP(wwin, floating)) state[i++] = net_wm_state_above; if (wwin->flags.fullscreen) state[i++] = net_wm_state_fullscreen; if (wwin->flags.focused) state[i++] = net_wm_state_focused; XChangeProperty(dpy, wwin->client_win, net_wm_state, XA_ATOM, 32, PropModeReplace, (unsigned char *)state, i); } } static Bool updateStrut(WScreen *scr, Window w, Bool adding) { WReservedArea *area; Bool hasState = False; if (adding) { Atom type_ret; int fmt_ret; unsigned long nitems_ret, bytes_after_ret; long *data = NULL; if ((XGetWindowProperty(dpy, w, net_wm_strut, 0, 4, False, XA_CARDINAL, &type_ret, &fmt_ret, &nitems_ret, &bytes_after_ret, (unsigned char **)&data) == Success && data) || ((XGetWindowProperty(dpy, w, net_wm_strut_partial, 0, 12, False, XA_CARDINAL, &type_ret, &fmt_ret, &nitems_ret, &bytes_after_ret, (unsigned char **)&data) == Success && data))) { /* XXX: This is strictly incorrect in the case of net_wm_strut_partial... * Discard the start and end properties from the partial strut and treat it as * a (deprecated) strut. * This means we are marking the whole width or height of the screen as * reserved, which is not necessarily what the strut defines. However for the * purposes of determining placement or maximization it's probably good enough. */ area = (WReservedArea *) wmalloc(sizeof(WReservedArea)); area->area.x1 = data[0]; area->area.x2 = data[1]; area->area.y1 = data[2]; area->area.y2 = data[3]; area->window = w; area->next = scr->netdata->strut; scr->netdata->strut = area; XFree(data); hasState = True; } } else { /* deleting */ area = scr->netdata->strut; if (area) { if (area->window == w) { scr->netdata->strut = area->next; wfree(area); hasState = True; } else { while (area->next && area->next->window != w) area = area->next; if (area->next) { WReservedArea *next; next = area->next->next; wfree(area->next); area->next = next; hasState = True; } } } } return hasState; } static int getWindowLayer(WWindow *wwin) { int layer = WMNormalLevel; if (wwin->type == net_wm_window_type_desktop) { layer = WMDesktopLevel; } else if (wwin->type == net_wm_window_type_dock) { layer = WMDockLevel; } else if (wwin->type == net_wm_window_type_toolbar) { layer = WMMainMenuLevel; } else if (wwin->type == net_wm_window_type_menu) { layer = WMSubmenuLevel; } else if (wwin->type == net_wm_window_type_utility) { } else if (wwin->type == net_wm_window_type_splash) { } else if (wwin->type == net_wm_window_type_dialog) { if (wwin->transient_for) { WWindow *parent = wWindowFor(wwin->transient_for); if (parent && parent->flags.fullscreen) layer = WMFullscreenLevel; } /* //layer = WMPopUpLevel; // this seems a bad idea -Dan */ } else if (wwin->type == net_wm_window_type_dropdown_menu) { layer = WMSubmenuLevel; } else if (wwin->type == net_wm_window_type_popup_menu) { layer = WMSubmenuLevel; } else if (wwin->type == net_wm_window_type_tooltip) { } else if (wwin->type == net_wm_window_type_notification) { layer = WMPopUpLevel; } else if (wwin->type == net_wm_window_type_combo) { layer = WMSubmenuLevel; } else if (wwin->type == net_wm_window_type_dnd) { } else if (wwin->type == net_wm_window_type_normal) { } if (wwin->client_flags.sunken && WMSunkenLevel < layer) layer = WMSunkenLevel; if (wwin->client_flags.floating && WMFloatingLevel > layer) layer = WMFloatingLevel; return layer; } static void doStateAtom(WWindow *wwin, Atom state, int set, Bool init) { if (state == net_wm_state_sticky) { if (set == _NET_WM_STATE_TOGGLE) set = !IS_OMNIPRESENT(wwin); if (set != wwin->flags.omnipresent) wWindowSetOmnipresent(wwin, set); } else if (state == net_wm_state_shaded) { if (set == _NET_WM_STATE_TOGGLE) set = !wwin->flags.shaded; if (init) { wwin->flags.shaded = set; } else { if (set) wShadeWindow(wwin); else wUnshadeWindow(wwin); } } else if (state == net_wm_state_skip_taskbar) { if (set == _NET_WM_STATE_TOGGLE) set = !wwin->client_flags.skip_window_list; wwin->client_flags.skip_window_list = set; } else if (state == net_wm_state_skip_pager) { if (set == _NET_WM_STATE_TOGGLE) set = !wwin->flags.net_skip_pager; wwin->flags.net_skip_pager = set; } else if (state == net_wm_state_maximized_vert) { if (set == _NET_WM_STATE_TOGGLE) set = !(wwin->flags.maximized & MAX_VERTICAL); if (init) { wwin->flags.maximized |= (set ? MAX_VERTICAL : 0); } else { if (set) wMaximizeWindow(wwin, wwin->flags.maximized | MAX_VERTICAL, wGetHeadForWindow(wwin)); else wMaximizeWindow(wwin, wwin->flags.maximized & ~MAX_VERTICAL, wGetHeadForWindow(wwin)); } } else if (state == net_wm_state_maximized_horz) { if (set == _NET_WM_STATE_TOGGLE) set = !(wwin->flags.maximized & MAX_HORIZONTAL); if (init) { wwin->flags.maximized |= (set ? MAX_HORIZONTAL : 0); } else { if (set) wMaximizeWindow(wwin, wwin->flags.maximized | MAX_HORIZONTAL, wGetHeadForWindow(wwin)); else wMaximizeWindow(wwin, wwin->flags.maximized & ~MAX_HORIZONTAL, wGetHeadForWindow(wwin)); } } else if (state == net_wm_state_hidden) { if (set == _NET_WM_STATE_TOGGLE) set = !(wwin->flags.miniaturized); if (init) { wwin->flags.miniaturized = set; } else { if (set) wIconifyWindow(wwin); else wDeiconifyWindow(wwin); } } else if (state == net_wm_state_fullscreen) { if (set == _NET_WM_STATE_TOGGLE) set = !(wwin->flags.fullscreen); if (init) { wwin->flags.fullscreen = set; } else { if (set) wFullscreenWindow(wwin); else wUnfullscreenWindow(wwin); } } else if (state == net_wm_state_above) { if (set == _NET_WM_STATE_TOGGLE) set = !(wwin->client_flags.floating); if (init) { wwin->client_flags.floating = set; } else { wwin->client_flags.floating = set; ChangeStackingLevel(wwin->frame->core, getWindowLayer(wwin)); } } else if (state == net_wm_state_below) { if (set == _NET_WM_STATE_TOGGLE) set = !(wwin->client_flags.sunken); if (init) { wwin->client_flags.sunken = set; } else { wwin->client_flags.sunken = set; ChangeStackingLevel(wwin->frame->core, getWindowLayer(wwin)); } } else { #ifdef DEBUG_WMSPEC wmessage("doStateAtom unknown atom %s set %d", XGetAtomName(dpy, state), set); #endif } } static void removeIcon(WWindow *wwin) { if (wwin->icon == NULL) return; if (wwin->flags.miniaturized && wwin->icon->mapped) { XUnmapWindow(dpy, wwin->icon->core->window); RemoveFromStackList(wwin->icon->core); wIconDestroy(wwin->icon); wwin->icon = NULL; } } static Bool handleWindowType(WWindow *wwin, Atom type, int *layer) { Bool ret = True; if (type == net_wm_window_type_desktop) { wwin->client_flags.no_titlebar = 1; wwin->client_flags.no_resizable = 1; wwin->client_flags.no_miniaturizable = 1; wwin->client_flags.no_border = 1; wwin->client_flags.no_resizebar = 1; wwin->client_flags.no_shadeable = 1; wwin->client_flags.no_movable = 1; wwin->client_flags.omnipresent = 1; wwin->client_flags.skip_window_list = 1; wwin->client_flags.skip_switchpanel = 1; wwin->client_flags.dont_move_off = 1; wwin->client_flags.no_appicon = 1; wwin->flags.net_skip_pager = 1; wwin->frame_x = 0; wwin->frame_y = 0; } else if (type == net_wm_window_type_dock) { wwin->client_flags.no_titlebar = 1; wwin->client_flags.no_resizable = 1; wwin->client_flags.no_miniaturizable = 1; wwin->client_flags.no_border = 1; /* XXX: really not a single decoration. */ wwin->client_flags.no_resizebar = 1; wwin->client_flags.no_shadeable = 1; wwin->client_flags.no_movable = 1; wwin->client_flags.omnipresent = 1; wwin->client_flags.skip_window_list = 1; wwin->client_flags.skip_switchpanel = 1; wwin->client_flags.dont_move_off = 1; wwin->flags.net_skip_pager = 1; } else if (type == net_wm_window_type_toolbar || type == net_wm_window_type_menu) { wwin->client_flags.no_resizable = 1; wwin->client_flags.no_miniaturizable = 1; wwin->client_flags.no_resizebar = 1; wwin->client_flags.no_shadeable = 1; wwin->client_flags.skip_window_list = 1; wwin->client_flags.skip_switchpanel = 1; wwin->client_flags.dont_move_off = 1; wwin->client_flags.no_appicon = 1; } else if (type == net_wm_window_type_dropdown_menu || type == net_wm_window_type_popup_menu || type == net_wm_window_type_combo) { wwin->client_flags.no_titlebar = 1; wwin->client_flags.no_resizable = 1; wwin->client_flags.no_miniaturizable = 1; wwin->client_flags.no_resizebar = 1; wwin->client_flags.no_shadeable = 1; wwin->client_flags.skip_window_list = 1; wwin->client_flags.skip_switchpanel = 1; wwin->client_flags.dont_move_off = 1; wwin->client_flags.no_appicon = 1; } else if (type == net_wm_window_type_utility) { wwin->client_flags.no_appicon = 1; } else if (type == net_wm_window_type_splash) { wwin->client_flags.no_titlebar = 1; wwin->client_flags.no_resizable = 1; wwin->client_flags.no_miniaturizable = 1; wwin->client_flags.no_resizebar = 1; wwin->client_flags.no_shadeable = 1; wwin->client_flags.no_movable = 1; wwin->client_flags.skip_window_list = 1; wwin->client_flags.skip_switchpanel = 1; wwin->client_flags.dont_move_off = 1; wwin->client_flags.no_appicon = 1; wwin->flags.net_skip_pager = 1; } else if (type == net_wm_window_type_dialog) { /* These also seem a bad idea in our context -Dan // wwin->client_flags.skip_window_list = 1; // wwin->client_flags.no_appicon = 1; */ } else if (wwin->type == net_wm_window_type_tooltip) { wwin->client_flags.no_titlebar = 1; wwin->client_flags.no_resizable = 1; wwin->client_flags.no_miniaturizable = 1; wwin->client_flags.no_resizebar = 1; wwin->client_flags.no_shadeable = 1; wwin->client_flags.no_movable = 1; wwin->client_flags.skip_window_list = 1; wwin->client_flags.skip_switchpanel = 1; wwin->client_flags.dont_move_off = 1; wwin->client_flags.no_appicon = 1; wwin->client_flags.no_focusable = 1; wwin->flags.net_skip_pager = 1; } else if (wwin->type == net_wm_window_type_notification) { wwin->client_flags.no_titlebar = 1; wwin->client_flags.no_resizable = 1; wwin->client_flags.no_miniaturizable = 1; wwin->client_flags.no_border = 1; wwin->client_flags.no_resizebar = 1; wwin->client_flags.no_shadeable = 1; wwin->client_flags.no_movable = 1; wwin->client_flags.omnipresent = 1; wwin->client_flags.skip_window_list = 1; wwin->client_flags.skip_switchpanel = 1; wwin->client_flags.dont_move_off = 1; wwin->client_flags.no_hide_others= 1; wwin->client_flags.no_appicon = 1; wwin->client_flags.no_focusable = 1; wwin->flags.net_skip_pager = 1;
roblillack/wmaker
224cb403a720574a8f824c6a658f326cb2c2f35f
Tippfehler in de.po von WPrefs (WindowMaker)
diff --git a/WPrefs.app/po/de.po b/WPrefs.app/po/de.po index 1b7075f..8a7ec15 100644 --- a/WPrefs.app/po/de.po +++ b/WPrefs.app/po/de.po @@ -310,1025 +310,1025 @@ msgstr "" msgid "Dithering colormap for 8bpp" msgstr "Dithering für 8bpp-Farbpalette" #: ../../WPrefs.app/Configurations.c:364 msgid "" "Number of colors to reserve for Window Maker\n" "on displays that support only 8bpp (PseudoColor)." msgstr "" "Anzahl der Farben, die für Window Maker auf\n" "Display mit nur 8bpp reserviert werden sollen (PseudoColor)." #: ../../WPrefs.app/Configurations.c:371 msgid "Disable dithering in any visual/depth" msgstr "Dithering in jedem Visual und jeder Farbtiefe ausschalten." #: ../../WPrefs.app/Configurations.c:392 msgid "" "More colors for\n" "applications" msgstr "" "Mehr Farben für\n" "Anwendungen" #: ../../WPrefs.app/Configurations.c:399 msgid "" "More colors for\n" "Window Maker" msgstr "" "Mehr Farben für\n" "Window Maker" #: ../../WPrefs.app/Configurations.c:443 msgid "Other Configurations" msgstr "Verschiedene Einstellungen" #: ../../WPrefs.app/Configurations.c:444 msgid "" "Animation speeds, titlebar styles, various option\n" "toggling and number of colors to reserve for\n" "Window Maker on 8bit displays." msgstr "" "Animationsgeschwindigkeiten, Titelleisten-Stil,\n" "Einstellen der für Window Maker reservierten\n" "Farben auf 8bpp-Displays." #: ../../WPrefs.app/Expert.c:70 msgid "" "Disable miniwindows (icons for minimized windows). For use with KDE/GNOME." msgstr "Keine Minifenster (Symbole für minimierte Fenster). Für KDE/GNOME." #: ../../WPrefs.app/Expert.c:71 msgid "Do not set non-WindowMaker specific parameters (do not use xset)." msgstr "" "Keine Window Maker-spezifischen Parameter setzen (xset nicht benutzen)." #: ../../WPrefs.app/Expert.c:72 msgid "Automatically save session when exiting Window Maker." msgstr "Automatischens Abspeichern der Sitzung beim Beenden." #: ../../WPrefs.app/Expert.c:73 msgid "Use SaveUnder in window frames, icons, menus and other objects." msgstr "SaveUnder für Fensterrahmen, Symbole, Menü u. a. benutzen" #: ../../WPrefs.app/Expert.c:74 msgid "Disable confirmation panel for the Kill command." msgstr "Kein Bestätigungsdialog für den Töten-Befehl" #: ../../WPrefs.app/Expert.c:75 msgid "Disable selection animation for selected icons." msgstr "Keine Auswahlanimation für ausgewählte Symbole" #: ../../WPrefs.app/Expert.c:76 msgid "Smooth font edges (needs restart)." msgstr "Geglättete Schriftarten (Neustart erforderlich)." #: ../../WPrefs.app/Expert.c:77 msgid "Launch applications and restore windows with a single click." msgstr "" "Mit einem einzelnen Mausklick Anwendungen ausführen und " "Fenster wiederherstellen." #: ../../WPrefs.app/Expert.c:110 msgid "Expert User Preferences" msgstr "Einstellungen für Experten" #: ../../WPrefs.app/Expert.c:112 msgid "" "Options for people who know what they're doing...\n" "Also have some other misc. options." msgstr "" "Einstellungen für Leute, die wissen, was sie tun...\n" "Und einige andere Einstellungen." #: ../../WPrefs.app/Focus.c:75 #, c-format msgid "bad option value %s for option FocusMode. Using default Manual" msgstr "" "falscher Eigenschaftswert %s für FocusMode. Standardwert 'Manuell' wird " "benutzt." #: ../../WPrefs.app/Focus.c:87 #, c-format msgid "bad option value %s for option ColormapMode. Using default Auto" msgstr "" "falscher Eigenschaftswert %s für ColormapMode. Standardwert 'Auto' wird " "benutzt." #: ../../WPrefs.app/Focus.c:193 msgid "Input Focus Mode" msgstr "Eingabefokus-Modus" #: ../../WPrefs.app/Focus.c:201 msgid "Manual: Click on the window to set keyboard input focus" msgstr "Manuell: Tastaturfokus durch Anklicken des Fensters setzen" #: ../../WPrefs.app/Focus.c:207 msgid "Auto: Set keyboard input focus to the window under the mouse pointer" msgstr "Auto: Tastaturfokus immer auf das Fenster unter dem Mauszeiger setzen" #: ../../WPrefs.app/Focus.c:220 msgid "Install colormap from the window..." msgstr "Farbtabelle im Fenster setzen, das..." #: ../../WPrefs.app/Focus.c:225 msgid "...that has the input focus" msgstr "...den Eingabefokus hat" #: ../../WPrefs.app/Focus.c:230 msgid "...that's under the mouse pointer" msgstr "...unter dem Mauszeiger ist" #: ../../WPrefs.app/Focus.c:239 msgid "Automatic Window Raise Delay" msgstr "Verzögerung für Auto-Fensterheber" #: ../../WPrefs.app/Focus.c:294 ../../WPrefs.app/MouseSettings.c:555 msgid "ms" msgstr "ms" #: ../../WPrefs.app/Focus.c:311 msgid "Do not let applications receive the click used to focus windows" msgstr "Mausklicks, die ein Fenster fokussiert haben, nicht an die Anwendung senden" #: ../../WPrefs.app/Focus.c:316 msgid "Automatically focus new windows" msgstr "Neue Fenster automatisch auswählen" #: ../../WPrefs.app/Focus.c:333 msgid "Window Focus Preferences" msgstr "Einstellungen zum Fokusverhalten" #: ../../WPrefs.app/Focus.c:335 msgid "" "Keyboard focus switching policy, colormap switching\n" "policy for 8bpp displays and other related options." msgstr "" "Tastaturfokuswechsel, Farbtabellenwechsel für\n" "8bpp-Display und weitere verwandte Eigenschaften." #: ../../WPrefs.app/FontSimple.c:100 msgid "Window Title" msgstr "Titel des aktiven Fensters" #: ../../WPrefs.app/FontSimple.c:102 msgid "Menu Text" msgstr "Text eines Menüeintrages" #: ../../WPrefs.app/FontSimple.c:103 msgid "Icon Title" msgstr "Symboltitel" #: ../../WPrefs.app/FontSimple.c:104 msgid "Clip Title" msgstr "Clip-Titel" #: ../../WPrefs.app/FontSimple.c:105 msgid "Desktop Caption" msgstr "Arbeitsflächentitel" #: ../../WPrefs.app/FontSimple.c:639 msgid "Sample Text" msgstr "Beispieltext" #: ../../WPrefs.app/FontSimple.c:656 msgid "Family" msgstr "Familie" #: ../../WPrefs.app/FontSimple.c:682 msgid "Style" msgstr "Stil" #: ../../WPrefs.app/FontSimple.c:685 msgid "Size" msgstr "Größe" #: ../../WPrefs.app/FontSimple.c:718 msgid "Font Configuration" msgstr "Schrifteinstellungen" #: ../../WPrefs.app/FontSimple.c:720 msgid "Configure fonts for Window Maker titlebars, menus etc." msgstr "Schrifteinstellungen für Fenster, Menüs usw." #: ../../WPrefs.app/Icons.c:166 msgid "Icon Positioning" msgstr "Symbolpositionierung" #: ../../WPrefs.app/Icons.c:212 msgid "Iconification Animation" msgstr "Animation bei Minimierung" #: ../../WPrefs.app/Icons.c:223 msgid "Shrinking/Zooming" msgstr "Schrumpfen/Vergrößern" #: ../../WPrefs.app/Icons.c:224 msgid "Spinning/Twisting" msgstr "Drehen" #: ../../WPrefs.app/Icons.c:225 msgid "3D-flipping" msgstr "3D-Rotation" #: ../../WPrefs.app/Icons.c:226 ../../WPrefs.app/MouseSettings.c:781 #: ../../WPrefs.app/MouseSettings.c:786 msgid "None" msgstr "Keine" #: ../../WPrefs.app/Icons.c:239 msgid "Auto-arrange icons" msgstr "Automatische Symbolanordnung" #: ../../WPrefs.app/Icons.c:241 msgid "Keep icons and miniwindows arranged all the time." msgstr "Symbole und Minifenster immer anordnen" #: ../../WPrefs.app/Icons.c:246 msgid "Omnipresent miniwindows" msgstr "Haftende Minifenster" #: ../../WPrefs.app/Icons.c:248 msgid "Make miniwindows be present in all workspaces." msgstr "Minifenster sind auf allen Arbeitsflächen sichtbar" #: ../../WPrefs.app/Icons.c:256 msgid "Icon Size" msgstr "Symbolgröße" #: ../../WPrefs.app/Icons.c:258 msgid "The size of the dock/application icon and miniwindows" msgstr "Größe der Dock-, Minifenster- und Anwendungssymbole" #: ../../WPrefs.app/Icons.c:322 msgid "Icon Preferences" msgstr "Symboleinstellungen" #: ../../WPrefs.app/Icons.c:324 msgid "" "Icon/Miniwindow handling options. Icon positioning\n" "area, sizes of icons, miniaturization animation style." msgstr "" "Symbol-/Minifenster-Verhalten, Symbolpositionierung,\n" "Größe der Symbole, Minimierungs- und Animationsstil." #: ../../WPrefs.app/KeyboardSettings.c:69 msgid "Initial Key Repeat" msgstr "Verzögerungsrate" #: ../../WPrefs.app/KeyboardSettings.c:110 msgid "Key Repeat Rate" msgstr "Wiederholrate" #: ../../WPrefs.app/KeyboardSettings.c:150 msgid "Type here to test" msgstr "Zum Testen hier Tippen" #: ../../WPrefs.app/KeyboardSettings.c:166 msgid "Keyboard Preferences" msgstr "Tastatureinstellungen" #: ../../WPrefs.app/KeyboardSettings.c:168 msgid "Not done" msgstr "Noch nicht erstellt" #: ../../WPrefs.app/KeyboardShortcuts.c:295 ../../WPrefs.app/Menu.c:323 #: ../../WPrefs.app/TexturePanel.c:1408 ../../WPrefs.app/imagebrowser.c:89 msgid "Cancel" msgstr "Abbrechen" #: ../../WPrefs.app/KeyboardShortcuts.c:297 msgid "Press the desired shortcut key(s) or click Cancel to stop capturing." msgstr "" "Drücken Sie die gewünschte Tastenkombination oder klicken Sie auf Abbrechen " "zum Stoppen der Aufzeichnung." #: ../../WPrefs.app/KeyboardShortcuts.c:316 #: ../../WPrefs.app/KeyboardShortcuts.c:548 ../../WPrefs.app/Menu.c:333 #: ../../WPrefs.app/Menu.c:756 msgid "Capture" msgstr "Aufzeichnen" #: ../../WPrefs.app/KeyboardShortcuts.c:317 #: ../../WPrefs.app/KeyboardShortcuts.c:556 msgid "Click on Capture to interactively define the shortcut key." msgstr "Zum Erstellen eines Tastenkürzels auf \"Aufzeichnen\" klicken." #: ../../WPrefs.app/KeyboardShortcuts.c:453 msgid "Actions" msgstr "Aktionen" #: ../../WPrefs.app/KeyboardShortcuts.c:467 msgid "Open applications menu" msgstr "Anwendungmenü öffnen" #: ../../WPrefs.app/KeyboardShortcuts.c:468 msgid "Open window list menu" msgstr "Fensterliste öffnen" #: ../../WPrefs.app/KeyboardShortcuts.c:469 msgid "Open window commands menu" msgstr "Fenstermenü öffnen" #: ../../WPrefs.app/KeyboardShortcuts.c:470 msgid "Hide active application" msgstr "Aktive Anwendung verstecken" #: ../../WPrefs.app/KeyboardShortcuts.c:471 msgid "Hide other applications" msgstr "Alle anderen Anwendung verstecken" #: ../../WPrefs.app/KeyboardShortcuts.c:472 msgid "Miniaturize active window" msgstr "Aktives Fenster minimieren" #: ../../WPrefs.app/KeyboardShortcuts.c:473 msgid "Close active window" msgstr "Aktives Fenster schließen" #: ../../WPrefs.app/KeyboardShortcuts.c:474 msgid "Maximize active window" msgstr "Aktives Fenster maximieren" #: ../../WPrefs.app/KeyboardShortcuts.c:475 msgid "Maximize active window vertically" msgstr "Aktives Fenster vertikal maximieren" #: ../../WPrefs.app/KeyboardShortcuts.c:476 msgid "Maximize active window horizontally" msgstr "Aktives Fenster horizontal maximieren" #: ../../WPrefs.app/KeyboardShortcuts.c:477 msgid "Maximize active window left half" msgstr "Aktives Fenster zur linken Hälfte maximieren" #: ../../WPrefs.app/KeyboardShortcuts.c:478 msgid "Maximize active window right half" msgstr "Aktives Fenster zur rechten Hälfte maximieren" #: ../../WPrefs.app/KeyboardShortcuts.c:479 msgid "Maximus: Tiled maximization " msgstr "Maximus: Kachel-Maximierung" #: ../../WPrefs.app/KeyboardShortcuts.c:480 msgid "Raise active window" msgstr "Aktives Fenster in den Vordergrund" #: ../../WPrefs.app/KeyboardShortcuts.c:481 msgid "Lower active window" msgstr "Aktives Fenster in den Hintergrund" #: ../../WPrefs.app/KeyboardShortcuts.c:482 msgid "Raise/Lower window under mouse pointer" msgstr "Fenster unter dem Mauszeiger in den Vor-/Hintergrund" #: ../../WPrefs.app/KeyboardShortcuts.c:483 msgid "Shade active window" msgstr "Aktives Fenster aufrollen" #: ../../WPrefs.app/KeyboardShortcuts.c:484 msgid "Move/Resize active window" msgstr "Aktives Fenster bewegen/verändern" #: ../../WPrefs.app/KeyboardShortcuts.c:485 msgid "Select active window" msgstr "Aktives Fenster auswählen" #: ../../WPrefs.app/KeyboardShortcuts.c:486 msgid "Focus next window" msgstr "Nächstes Fenster" #: ../../WPrefs.app/KeyboardShortcuts.c:487 msgid "Focus previous window" msgstr "Vorheriges Fenster" #: ../../WPrefs.app/KeyboardShortcuts.c:488 msgid "Focus next group window" msgstr "" #: ../../WPrefs.app/KeyboardShortcuts.c:489 msgid "Focus previous group window" msgstr "" #: ../../WPrefs.app/KeyboardShortcuts.c:490 msgid "Switch to next workspace" msgstr "Zur nächsten Arbeitsfläche" #: ../../WPrefs.app/KeyboardShortcuts.c:491 msgid "Switch to previous workspace" msgstr "Zur vorherigen Arbeitsfläche" #: ../../WPrefs.app/KeyboardShortcuts.c:492 msgid "Switch to next ten workspaces" msgstr "Springe 10 Arbeitsflächen vorwärts" #: ../../WPrefs.app/KeyboardShortcuts.c:493 msgid "Switch to previous ten workspaces" msgstr "Springe 10 Arbeitsflächen rückwärts" #: ../../WPrefs.app/KeyboardShortcuts.c:494 msgid "Switch to workspace 1" msgstr "Springe zu Arbeitsfläche 1" #: ../../WPrefs.app/KeyboardShortcuts.c:495 msgid "Switch to workspace 2" msgstr "Springe zu Arbeitsfläche 2" #: ../../WPrefs.app/KeyboardShortcuts.c:496 msgid "Switch to workspace 3" msgstr "Springe zu Arbeitsfläche 3" #: ../../WPrefs.app/KeyboardShortcuts.c:497 msgid "Switch to workspace 4" msgstr "Springe zu Arbeitsfläche 4" #: ../../WPrefs.app/KeyboardShortcuts.c:498 msgid "Switch to workspace 5" msgstr "Springe zu Arbeitsfläche 5" #: ../../WPrefs.app/KeyboardShortcuts.c:499 msgid "Switch to workspace 6" msgstr "Springe zu Arbeitsfläche 6" #: ../../WPrefs.app/KeyboardShortcuts.c:500 msgid "Switch to workspace 7" msgstr "Springe zu Arbeitsfläche 7" #: ../../WPrefs.app/KeyboardShortcuts.c:501 msgid "Switch to workspace 8" msgstr "Springe zu Arbeitsfläche 8" #: ../../WPrefs.app/KeyboardShortcuts.c:502 msgid "Switch to workspace 9" msgstr "Springe zu Arbeitsfläche 9" #: ../../WPrefs.app/KeyboardShortcuts.c:503 msgid "Switch to workspace 10" msgstr "Springe zu Arbeitsfläche 10" #: ../../WPrefs.app/KeyboardShortcuts.c:504 msgid "Shortcut for window 1" msgstr "Tastenkürzel für Fenster 1" #: ../../WPrefs.app/KeyboardShortcuts.c:505 msgid "Shortcut for window 2" msgstr "Tastenkürzel für Fenster 2" #: ../../WPrefs.app/KeyboardShortcuts.c:506 msgid "Shortcut for window 3" msgstr "Tastenkürzel für Fenster 3" #: ../../WPrefs.app/KeyboardShortcuts.c:507 msgid "Shortcut for window 4" msgstr "Tastenkürzel für Fenster 4" #: ../../WPrefs.app/KeyboardShortcuts.c:508 msgid "Shortcut for window 5" msgstr "Tastenkürzel für Fenster 5" #: ../../WPrefs.app/KeyboardShortcuts.c:509 msgid "Shortcut for window 6" msgstr "Tastenkürzel für Fenster 6" #: ../../WPrefs.app/KeyboardShortcuts.c:510 msgid "Shortcut for window 7" msgstr "Tastenkürzel für Fenster 7" #: ../../WPrefs.app/KeyboardShortcuts.c:511 msgid "Shortcut for window 8" msgstr "Tastenkürzel für Fenster 8" #: ../../WPrefs.app/KeyboardShortcuts.c:512 msgid "Shortcut for window 9" msgstr "Tastenkürzel für Fenster 9" #: ../../WPrefs.app/KeyboardShortcuts.c:513 msgid "Shortcut for window 10" msgstr "Tastenkürzel für Fenster 10" #: ../../WPrefs.app/KeyboardShortcuts.c:514 msgid "Switch to Next Screen/Monitor" msgstr "Springe zu nächstem Bildschirm" #: ../../WPrefs.app/KeyboardShortcuts.c:515 msgid "Raise/Lower Dock" msgstr "Dock in den Vor-/Hintergrund" #: ../../WPrefs.app/KeyboardShortcuts.c:516 msgid "Raise/Lower Clip" msgstr "Clip in den Vor-/Hintergrund" #: ../../WPrefs.app/KeyboardShortcuts.c:518 msgid "Toggle keyboard language" -msgstr "Tastatursbelegung ändern" +msgstr "Tastaturbelegung ändern" #: ../../WPrefs.app/KeyboardShortcuts.c:532 msgid "Shortcut" msgstr "Kürzel" #: ../../WPrefs.app/KeyboardShortcuts.c:542 ../../WPrefs.app/Menu.c:762 msgid "Clear" msgstr "Löschen" #: ../../WPrefs.app/KeyboardShortcuts.c:598 msgid "Keyboard Shortcut Preferences" msgstr "Tastenkürzel-Einstellungen" #: ../../WPrefs.app/KeyboardShortcuts.c:600 msgid "" "Change the keyboard shortcuts for actions such\n" "as changing workspaces and opening menus." msgstr "" "Ändern der Tastenkürzel für Aktionen wie das\n" "Wechseln der Arbeitsflächen und das Öffnen von Menüs." #: ../../WPrefs.app/Menu.c:247 msgid "Select Program" msgstr "Programm auswählen" #: ../../WPrefs.app/Menu.c:460 msgid "New Items" msgstr "Neue Einträge" #: ../../WPrefs.app/Menu.c:461 msgid "Sample Commands" msgstr "Beispielbefehle" #: ../../WPrefs.app/Menu.c:462 msgid "Sample Submenus" msgstr "Beispieluntermenüs" #: ../../WPrefs.app/Menu.c:476 msgid "Run Program" msgstr "Programm ausführen" #: ../../WPrefs.app/Menu.c:477 msgid "Internal Command" msgstr "interner Befehl" #: ../../WPrefs.app/Menu.c:478 msgid "Submenu" msgstr "Untermenü" #: ../../WPrefs.app/Menu.c:479 msgid "External Submenu" msgstr "externes Untermenü" #: ../../WPrefs.app/Menu.c:480 msgid "Generated Submenu" msgstr "erstelltes Untermenü" #: ../../WPrefs.app/Menu.c:481 msgid "Directory Contents" msgstr "Verzeichnisinhalt" #: ../../WPrefs.app/Menu.c:482 msgid "Workspace Menu" msgstr "Arbeitsflächenmenü" #: ../../WPrefs.app/Menu.c:483 ../../WPrefs.app/MouseSettings.c:783 msgid "Window List Menu" msgstr "Fensterliste" #: ../../WPrefs.app/Menu.c:502 msgid "XTerm" msgstr "" #: ../../WPrefs.app/Menu.c:505 msgid "rxvt" msgstr "" #: ../../WPrefs.app/Menu.c:508 msgid "ETerm" msgstr "" #: ../../WPrefs.app/Menu.c:511 msgid "Run..." msgstr "Ausführen..." #: ../../WPrefs.app/Menu.c:512 #, c-format msgid "%a(Run,Type command to run)" msgstr "%a(Befehl zum Ausführen eingeben)" #: ../../WPrefs.app/Menu.c:514 msgid "Netscape" msgstr "" #: ../../WPrefs.app/Menu.c:517 msgid "gimp" msgstr "" #: ../../WPrefs.app/Menu.c:520 msgid "epic" msgstr "" #: ../../WPrefs.app/Menu.c:523 msgid "ee" msgstr "" #: ../../WPrefs.app/Menu.c:526 msgid "xv" msgstr "" #: ../../WPrefs.app/Menu.c:529 msgid "Acrobat Reader" msgstr "" #: ../../WPrefs.app/Menu.c:532 msgid "ghostview" msgstr "" #: ../../WPrefs.app/Menu.c:535 ../../WPrefs.app/Menu.c:781 msgid "Exit Window Maker" msgstr "Window Maker beenden" #: ../../WPrefs.app/Menu.c:557 msgid "Debian Menu" msgstr "Debian-Menü" #: ../../WPrefs.app/Menu.c:560 msgid "RedHat Menu" msgstr "RedHat-Menü" #: ../../WPrefs.app/Menu.c:563 msgid "Menu Conectiva" msgstr "Conectiva-Menü" #: ../../WPrefs.app/Menu.c:566 ../../WPrefs.app/Themes.c:213 msgid "Themes" msgstr "Themen" #: ../../WPrefs.app/Menu.c:572 msgid "Bg Images (scale)" msgstr "Hintergrundbilder (skaliert)" #: ../../WPrefs.app/Menu.c:578 msgid "Bg Images (tile)" msgstr "Hintergrundbilder (Kacheln)" #: ../../WPrefs.app/Menu.c:584 msgid "Assorted XTerms" msgstr "sortierte XTerms" #: ../../WPrefs.app/Menu.c:586 msgid "XTerm Yellow on Blue" msgstr "XTerm Gelb auf Blau" #: ../../WPrefs.app/Menu.c:589 msgid "XTerm White on Black" msgstr "XTerm Weiß auf Schwarz" #: ../../WPrefs.app/Menu.c:592 msgid "XTerm Black on White" msgstr "XTerm Schwarz auf Weiß" #: ../../WPrefs.app/Menu.c:595 msgid "XTerm Black on Beige" msgstr "XTerm Schwarz auf Beige" #: ../../WPrefs.app/Menu.c:598 msgid "XTerm White on Green" msgstr "XTerm Weiß auf Grün" #: ../../WPrefs.app/Menu.c:601 msgid "XTerm White on Olive" msgstr "XTerm Weiß auf Oliv" #: ../../WPrefs.app/Menu.c:604 msgid "XTerm Blue on Blue" msgstr "XTerm Blau auf Blau" #: ../../WPrefs.app/Menu.c:607 msgid "XTerm BIG FONTS" msgstr "XTerm Große Schriften" #: ../../WPrefs.app/Menu.c:628 msgid "Program to Run" msgstr "auszuführendes Programm" #: ../../WPrefs.app/Menu.c:638 msgid "Browse" msgstr "Suchen..." #: ../../WPrefs.app/Menu.c:647 msgid "Run the program inside a Xterm" msgstr "Programm in einem XTerm ausführen" #: ../../WPrefs.app/Menu.c:656 msgid "Path for Menu" msgstr "Menüpfad" #: ../../WPrefs.app/Menu.c:667 msgid "" "Enter the path for a file containing a menu\n" "or a list of directories with the programs you\n" "want to have listed in the menu. Ex:\n" "~/GNUstep/Library/WindowMaker/menu\n" "or\n" "/usr/bin ~/xbin" msgstr "" "Geben Sie den Pfad einer Datei, die ein Menü\n" "enthält, oder eine Liste von Verzeichnissen\n" "mit den gewüschten Anwendungen ein. Bespiel:\n" "~/GNUstep/Library/WindowMaker/menu\n" "oder\n" "/usr/bin ~/xbin" #: ../../WPrefs.app/Menu.c:679 msgid "Command" msgstr "Befehl" #: ../../WPrefs.app/Menu.c:690 msgid "" "Enter a command that outputs a menu\n" "definition to stdout when invoked." msgstr "" "Geben Sie einen Befehl ein, der bei Aufruf\n" "ein Menü auf der Standardausgabe zurückgibt." #: ../../WPrefs.app/Menu.c:695 msgid "" "Cache menu contents after opening for\n" "the first time" msgstr "" "Menüinhalt nach erstem Laden\n" "zwischenspeichern" #: ../../WPrefs.app/Menu.c:704 msgid "Command to Open Files" msgstr "Befehl zum Öffnen der Dateien" #: ../../WPrefs.app/Menu.c:715 msgid "" "Enter the command you want to use to open the\n" "files in the directories listed below." msgstr "" "Geben Sie den Befehl zum Öffnen der Dateien\n" "in den augelisteten Verzeichnissen ein." #: ../../WPrefs.app/Menu.c:723 msgid "Directories with Files" msgstr "Verzeichnis mit Dateien" #: ../../WPrefs.app/Menu.c:734 msgid "Strip extensions from file names" msgstr "Erweiterungen von den Dateinamen entfernen" #: ../../WPrefs.app/Menu.c:745 msgid "Keyboard Shortcut" msgstr "Tastenkürzel" #: ../../WPrefs.app/Menu.c:777 msgid "Arrange Icons" msgstr "Symbole anordnen" #: ../../WPrefs.app/Menu.c:778 msgid "Hide All Windows Except For The Focused One" msgstr "Alle Fenster bis auf das aktive verstecken" #: ../../WPrefs.app/Menu.c:779 msgid "Show All Windows" msgstr "Alle Fenster anzeigen" #: ../../WPrefs.app/Menu.c:782 msgid "Exit X Session" msgstr "X-Sitzung beenden" #: ../../WPrefs.app/Menu.c:783 msgid "Restart Window Maker" msgstr "Window Maker neustarten" #: ../../WPrefs.app/Menu.c:784 msgid "Start Another Window Manager : (" msgstr "anderen Windowmanager starten : (" #: ../../WPrefs.app/Menu.c:786 msgid "Save Current Session" msgstr "aktuelle Sitzung speichern" #: ../../WPrefs.app/Menu.c:787 msgid "Clear Saved Session" msgstr "gespeicherte Sitzung löschen" #: ../../WPrefs.app/Menu.c:788 msgid "Refresh Screen" msgstr "Bildschirm auffrischen" #: ../../WPrefs.app/Menu.c:789 msgid "Open Info Panel" msgstr "Infodialog anzeigen" #: ../../WPrefs.app/Menu.c:790 msgid "Open Copyright Panel" msgstr "Copyrightinformationen anzeigen" #: ../../WPrefs.app/Menu.c:795 msgid "Window Manager to Start" msgstr "zu startender Windowmanager" #: ../../WPrefs.app/Menu.c:808 msgid "Do not confirm action." msgstr "Aktion nicht bestätigen" #: ../../WPrefs.app/Menu.c:815 msgid "" "Instructions:\n" "\n" " - drag items from the left to the menu to add new items\n" " - drag items out of the menu to remove items\n" " - drag items in menu to change their position\n" " - drag items with Control pressed to copy them\n" " - double click in a menu item to change the label\n" " - click on a menu item to change related information" msgstr "" "Hilfe:\n" "\n" " - ziehen Sie Einträge von links in das Menü, um neue Einträge zu erstellen\n" " - ziehen Sie Einträge aus dem Menu, um sie zu entfernen\n" " - ziehen Sie Einträge innerhalb des Menüs, um sie zu verschieben\n" " - ziehen Sie Einträge bei gedrückter Strg-Taste, um sie zu kopieren\n" " - doppelklicken Sie auf Einträge, um den Text zu verändern\n" " - klicken Sie auf die Einträge, um diese zu konfigurieren " #: ../../WPrefs.app/Menu.c:1032 #, c-format msgid "unknown command '%s' in menu" msgstr "unbekannter Menübefehl '%s'" #: ../../WPrefs.app/Menu.c:1060 msgid ": Execute Program" msgstr ": Programm ausführen" #: ../../WPrefs.app/Menu.c:1064 msgid ": Perform Internal Command" msgstr ": internen Befehl ausführen" #: ../../WPrefs.app/Menu.c:1068 msgid ": Open a Submenu" msgstr ": Untermenü öffnen" #: ../../WPrefs.app/Menu.c:1072 msgid ": Program Generated Submenu" msgstr ": programmgeneriertes Unternmenü" #: ../../WPrefs.app/Menu.c:1076 msgid ": Directory Contents Menu" msgstr ": Menü mit Verzeichnisinhalt" #: ../../WPrefs.app/Menu.c:1080 msgid ": Open Workspaces Submenu" msgstr ": Arbeitsflächen-Untermenü" #: ../../WPrefs.app/Menu.c:1084 msgid ": Open Window List Submenu" msgstr ": Fensterlisten-Untermenü" #: ../../WPrefs.app/Menu.c:1279 msgid "Remove Submenu" msgstr "Untermenü entfernen" #: ../../WPrefs.app/Menu.c:1280 msgid "" "Removing this item will destroy all items inside\n" "the submenu. Do you really want to do that?" msgstr "" "Das Entfernen dieses Eintrages löscht alle Einträge\n" "im Untermenü. Wollen Sie das wirklich tun?" #: ../../WPrefs.app/Menu.c:1282 msgid "Yes" msgstr "Ja" #: ../../WPrefs.app/Menu.c:1282 msgid "No" msgstr "Nein" #: ../../WPrefs.app/Menu.c:1282 msgid "Yes, don't ask again" msgstr "Ja, alle" #: ../../WPrefs.app/Menu.c:1437 #, c-format msgid "Could not open default menu from '%s'" msgstr "Standardmenü aus '%s' konnte nicht geöffnet werden" #: ../../WPrefs.app/Menu.c:1441 ../../WPrefs.app/MouseSettings.c:123 #: ../../WPrefs.app/MouseSettings.c:142 ../../WPrefs.app/TexturePanel.c:560 #: ../../WPrefs.app/TexturePanel.c:636 ../../WPrefs.app/Themes.c:84 #: ../../WPrefs.app/WPrefs.c:663 ../../WPrefs.app/WPrefs.c:667 #: ../../WPrefs.app/WPrefs.c:684 ../../WPrefs.app/WPrefs.c:695 #: ../../WPrefs.app/WPrefs.c:705 ../../WPrefs.app/WPrefs.c:745 #: ../../WPrefs.app/WPrefs.c:749 msgid "Error" msgstr "Fehler" #: ../../WPrefs.app/Menu.c:1441 ../../WPrefs.app/MouseSettings.c:125 #: ../../WPrefs.app/MouseSettings.c:145 ../../WPrefs.app/TexturePanel.c:560 #: ../../WPrefs.app/TexturePanel.c:638 ../../WPrefs.app/TexturePanel.c:1402 #: ../../WPrefs.app/Themes.c:85 ../../WPrefs.app/WPrefs.c:663 #: ../../WPrefs.app/WPrefs.c:667 ../../WPrefs.app/WPrefs.c:687 #: ../../WPrefs.app/WPrefs.c:699 ../../WPrefs.app/WPrefs.c:705 #: ../../WPrefs.app/WPrefs.c:714 ../../WPrefs.app/WPrefs.c:745 #: ../../WPrefs.app/WPrefs.c:749 ../../WPrefs.app/imagebrowser.c:94 msgid "OK" msgstr "OK" #: ../../WPrefs.app/Menu.c:1468 ../../WPrefs.app/WPrefs.c:714 msgid "Warning" msgstr "Warnung" #: ../../WPrefs.app/Menu.c:1469 msgid "" "The menu file format currently in use is not supported\n" "by this tool. Do you want to discard the current menu\n" "to use this tool?" msgstr "" "Das momentan verwendete Menüdateiformat wird von\n" "diesem Programm nicht unterstützt. Wollen Sie das aktuelle\n" "Menü verwerfen, um dieses Programm verwenden zu können?" #: ../../WPrefs.app/Menu.c:1472 msgid "Yes, Discard and Update" msgstr "Ja, Verwerfen und Erneuern" #: ../../WPrefs.app/Menu.c:1472 msgid "No, Keep Current Menu" msgstr "Nein, aktuelles Menü behalten" #: ../../WPrefs.app/Menu.c:1704 msgid "Applications Menu Definition" msgstr "Anwendungsmenü-Definition" #: ../../WPrefs.app/Menu.c:1706 msgid "Edit the menu for launching applications." msgstr "Editieren des Menüs zum Starten von Anwendungen" #: ../../WPrefs.app/MenuPreferences.c:102 msgid "Menu Scrolling Speed" msgstr "Menü-Scrollgeschwindigkeit" #: ../../WPrefs.app/MenuPreferences.c:150 msgid "Submenu Alignment" msgstr "Untermenü-Ausrichtung" #: ../../WPrefs.app/MenuPreferences.c:196 msgid "" "Always open submenus inside the screen, instead of scrolling." msgstr "" "Untermenüs immer im Bildschirm öffnen anstatt zu Scrollen." #: ../../WPrefs.app/MenuPreferences.c:201 msgid "Scroll off-screen menus when pointer is moved over them." msgstr "" "Menüs außerhalb des Bildschirms scrollen, wenn der Mauszeiger über ihnen ist." #: ../../WPrefs.app/MenuPreferences.c:218 msgid "Menu Preferences" msgstr "Menüeinstellungen" #: ../../WPrefs.app/MenuPreferences.c:220 msgid "" "Menu usability related options. Scrolling speed,\n" "alignment of submenus etc." msgstr "" "Menüverhalten und verwandte Einstellungen. Scrollgeschwindigkeit,\n" "Ausrichtung von Untermenüs usw." #: ../../WPrefs.app/MouseSettings.c:124 msgid "Invalid mouse acceleration value. Must be a positive real value." msgstr "Ungültiger Wert für Mausy^: positive Kommazahl erwartet." #: ../../WPrefs.app/MouseSettings.c:144 msgid "" "Invalid mouse acceleration threshold value. Must be the number of pixels to " "travel before accelerating." msgstr "" "Ungültiger Schwellenwert für Mausbeuschleunigung: Anzahl der zurückgelegten " "Pixel erwartet." #: ../../WPrefs.app/MouseSettings.c:231 ../../WPrefs.app/MouseSettings.c:243 #: ../../WPrefs.app/MouseSettings.c:255 ../../WPrefs.app/MouseSettings.c:267 #, c-format msgid "bad value %s for option %s" msgstr "ungültiger Wert %s für Option %s" #: ../../WPrefs.app/MouseSettings.c:323 #, c-format msgid "" "modifier key %s for option ModifierKey was not recognized. Using %s as " "default" msgstr "" "Tastenmodifikator %s für die Option ModifierKey wurde nicht erkannt. " "Standardwert %s wird benutzt" #: ../../WPrefs.app/MouseSettings.c:344 msgid "could not retrieve keyboard modifier mapping" msgstr "Tastenmodifikator-Zuordnung konnte nicht zurückverfolgt werden" #: ../../WPrefs.app/MouseSettings.c:435 msgid "Mouse Speed" msgstr "Mausgeschwindigkeit" #: ../../WPrefs.app/MouseSettings.c:465 msgid "Accel.:" msgstr "Beschl.:"
roblillack/wmaker
1cd8fea4238f78013fd18c79a195b6298a10a5da
Add support for _NET_WM_STATE_FOCUSED
diff --git a/src/wmspec.c b/src/wmspec.c index c2bb35c..57a72d1 100644 --- a/src/wmspec.c +++ b/src/wmspec.c @@ -1,1894 +1,1900 @@ /* wmspec.c-- support for the wm-spec Hints * * Window Maker window manager * * Copyright (c) 1998-2003 Alfredo K. Kojima * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ /* * TODO * ---- * * This file needs to be checked for all calls to XGetWindowProperty() and * proper checks need to be made on the returned values. Only checking for * return to be Success is not enough. -Dan */ #include "wconfig.h" #include <X11/Xlib.h> #include <X11/Xatom.h> #include <string.h> #include <WINGs/WUtil.h> #include "WindowMaker.h" #include "window.h" #include "screen.h" #include "workspace.h" #include "framewin.h" #include "actions.h" #include "client.h" #include "appicon.h" #include "wmspec.h" #include "icon.h" #include "stacking.h" #include "xinerama.h" #include "properties.h" /* Root Window Properties */ static Atom net_supported; static Atom net_client_list; static Atom net_client_list_stacking; static Atom net_number_of_desktops; static Atom net_desktop_geometry; static Atom net_desktop_viewport; static Atom net_current_desktop; static Atom net_desktop_names; static Atom net_active_window; static Atom net_workarea; static Atom net_supporting_wm_check; static Atom net_virtual_roots; /* N/A */ static Atom net_desktop_layout; /* XXX */ static Atom net_showing_desktop; /* Other Root Window Messages */ static Atom net_close_window; static Atom net_moveresize_window; /* TODO */ static Atom net_wm_moveresize; /* TODO */ /* Application Window Properties */ static Atom net_wm_name; static Atom net_wm_visible_name; /* TODO (unnecessary?) */ static Atom net_wm_icon_name; static Atom net_wm_visible_icon_name; /* TODO (unnecessary?) */ static Atom net_wm_desktop; static Atom net_wm_window_type; static Atom net_wm_window_type_desktop; static Atom net_wm_window_type_dock; static Atom net_wm_window_type_toolbar; static Atom net_wm_window_type_menu; static Atom net_wm_window_type_utility; static Atom net_wm_window_type_splash; static Atom net_wm_window_type_dialog; static Atom net_wm_window_type_dropdown_menu; static Atom net_wm_window_type_popup_menu; static Atom net_wm_window_type_tooltip; static Atom net_wm_window_type_notification; static Atom net_wm_window_type_combo; static Atom net_wm_window_type_dnd; static Atom net_wm_window_type_normal; static Atom net_wm_state; static Atom net_wm_state_modal; /* XXX: what is this?!? */ static Atom net_wm_state_sticky; static Atom net_wm_state_maximized_vert; static Atom net_wm_state_maximized_horz; static Atom net_wm_state_shaded; static Atom net_wm_state_skip_taskbar; static Atom net_wm_state_skip_pager; static Atom net_wm_state_hidden; static Atom net_wm_state_fullscreen; static Atom net_wm_state_above; static Atom net_wm_state_below; +static Atom net_wm_state_focused; static Atom net_wm_allowed_actions; static Atom net_wm_action_move; static Atom net_wm_action_resize; static Atom net_wm_action_minimize; static Atom net_wm_action_shade; static Atom net_wm_action_stick; static Atom net_wm_action_maximize_horz; static Atom net_wm_action_maximize_vert; static Atom net_wm_action_fullscreen; static Atom net_wm_action_change_desktop; static Atom net_wm_action_close; static Atom net_wm_strut; static Atom net_wm_strut_partial; /* TODO: doesn't really fit into the current strut scheme */ static Atom net_wm_icon_geometry; /* FIXME: should work together with net_wm_handled_icons, gnome-panel-2.2.0.1 doesn't use _NET_WM_HANDLED_ICONS, thus present situation. */ static Atom net_wm_icon; static Atom net_wm_pid; /* TODO */ static Atom net_wm_handled_icons; /* FIXME: see net_wm_icon_geometry */ static Atom net_wm_window_opacity; static Atom net_frame_extents; /* Window Manager Protocols */ static Atom net_wm_ping; /* TODO */ static Atom utf8_string; typedef struct { char *name; Atom *atom; } atomitem_t; static atomitem_t atomNames[] = { {"_NET_SUPPORTED", &net_supported}, {"_NET_CLIENT_LIST", &net_client_list}, {"_NET_CLIENT_LIST_STACKING", &net_client_list_stacking}, {"_NET_NUMBER_OF_DESKTOPS", &net_number_of_desktops}, {"_NET_DESKTOP_GEOMETRY", &net_desktop_geometry}, {"_NET_DESKTOP_VIEWPORT", &net_desktop_viewport}, {"_NET_CURRENT_DESKTOP", &net_current_desktop}, {"_NET_DESKTOP_NAMES", &net_desktop_names}, {"_NET_ACTIVE_WINDOW", &net_active_window}, {"_NET_WORKAREA", &net_workarea}, {"_NET_SUPPORTING_WM_CHECK", &net_supporting_wm_check}, {"_NET_VIRTUAL_ROOTS", &net_virtual_roots}, {"_NET_DESKTOP_LAYOUT", &net_desktop_layout}, {"_NET_SHOWING_DESKTOP", &net_showing_desktop}, {"_NET_CLOSE_WINDOW", &net_close_window}, {"_NET_MOVERESIZE_WINDOW", &net_moveresize_window}, {"_NET_WM_MOVERESIZE", &net_wm_moveresize}, {"_NET_WM_NAME", &net_wm_name}, {"_NET_WM_VISIBLE_NAME", &net_wm_visible_name}, {"_NET_WM_ICON_NAME", &net_wm_icon_name}, {"_NET_WM_VISIBLE_ICON_NAME", &net_wm_visible_icon_name}, {"_NET_WM_DESKTOP", &net_wm_desktop}, {"_NET_WM_WINDOW_TYPE", &net_wm_window_type}, {"_NET_WM_WINDOW_TYPE_DESKTOP", &net_wm_window_type_desktop}, {"_NET_WM_WINDOW_TYPE_DOCK", &net_wm_window_type_dock}, {"_NET_WM_WINDOW_TYPE_TOOLBAR", &net_wm_window_type_toolbar}, {"_NET_WM_WINDOW_TYPE_MENU", &net_wm_window_type_menu}, {"_NET_WM_WINDOW_TYPE_UTILITY", &net_wm_window_type_utility}, {"_NET_WM_WINDOW_TYPE_SPLASH", &net_wm_window_type_splash}, {"_NET_WM_WINDOW_TYPE_DIALOG", &net_wm_window_type_dialog}, {"_NET_WM_WINDOW_TYPE_DROPDOWN_MENU", &net_wm_window_type_dropdown_menu}, {"_NET_WM_WINDOW_TYPE_POPUP_MENU", &net_wm_window_type_popup_menu}, {"_NET_WM_WINDOW_TYPE_TOOLTIP", &net_wm_window_type_tooltip}, {"_NET_WM_WINDOW_TYPE_NOTIFICATION", &net_wm_window_type_notification}, {"_NET_WM_WINDOW_TYPE_COMBO", &net_wm_window_type_combo}, {"_NET_WM_WINDOW_TYPE_DND", &net_wm_window_type_dnd}, {"_NET_WM_WINDOW_TYPE_NORMAL", &net_wm_window_type_normal}, {"_NET_WM_STATE", &net_wm_state}, {"_NET_WM_STATE_MODAL", &net_wm_state_modal}, {"_NET_WM_STATE_STICKY", &net_wm_state_sticky}, {"_NET_WM_STATE_MAXIMIZED_VERT", &net_wm_state_maximized_vert}, {"_NET_WM_STATE_MAXIMIZED_HORZ", &net_wm_state_maximized_horz}, {"_NET_WM_STATE_SHADED", &net_wm_state_shaded}, {"_NET_WM_STATE_SKIP_TASKBAR", &net_wm_state_skip_taskbar}, {"_NET_WM_STATE_SKIP_PAGER", &net_wm_state_skip_pager}, {"_NET_WM_STATE_HIDDEN", &net_wm_state_hidden}, {"_NET_WM_STATE_FULLSCREEN", &net_wm_state_fullscreen}, {"_NET_WM_STATE_ABOVE", &net_wm_state_above}, {"_NET_WM_STATE_BELOW", &net_wm_state_below}, + {"_NET_WM_STATE_FOCUSED", &net_wm_state_focused}, {"_NET_WM_ALLOWED_ACTIONS", &net_wm_allowed_actions}, {"_NET_WM_ACTION_MOVE", &net_wm_action_move}, {"_NET_WM_ACTION_RESIZE", &net_wm_action_resize}, {"_NET_WM_ACTION_MINIMIZE", &net_wm_action_minimize}, {"_NET_WM_ACTION_SHADE", &net_wm_action_shade}, {"_NET_WM_ACTION_STICK", &net_wm_action_stick}, {"_NET_WM_ACTION_MAXIMIZE_HORZ", &net_wm_action_maximize_horz}, {"_NET_WM_ACTION_MAXIMIZE_VERT", &net_wm_action_maximize_vert}, {"_NET_WM_ACTION_FULLSCREEN", &net_wm_action_fullscreen}, {"_NET_WM_ACTION_CHANGE_DESKTOP", &net_wm_action_change_desktop}, {"_NET_WM_ACTION_CLOSE", &net_wm_action_close}, {"_NET_WM_STRUT", &net_wm_strut}, {"_NET_WM_STRUT_PARTIAL", &net_wm_strut_partial}, {"_NET_WM_ICON_GEOMETRY", &net_wm_icon_geometry}, {"_NET_WM_ICON", &net_wm_icon}, {"_NET_WM_PID", &net_wm_pid}, {"_NET_WM_HANDLED_ICONS", &net_wm_handled_icons}, {"_NET_WM_WINDOW_OPACITY", &net_wm_window_opacity}, {"_NET_FRAME_EXTENTS", &net_frame_extents}, {"_NET_WM_PING", &net_wm_ping}, {"UTF8_STRING", &utf8_string}, }; #define _NET_WM_STATE_ADD 1 #define _NET_WM_STATE_TOGGLE 2 #if 0 /* * These constant provide information on the kind of window move/resize when * it is initiated by the application instead of by WindowMaker. They are * parameter for the client message _NET_WM_MOVERESIZE, as defined by the * FreeDesktop wm-spec standard: * http://standards.freedesktop.org/wm-spec/1.5/ar01s04.html * * Today, WindowMaker does not support this at all (the corresponding Atom * is not added to the list in setSupportedHints), probably because there is * nothing it needs to do about it, the application is assumed to know what * it is doing, and WindowMaker won't get in the way. * * The definition of the constants (taken from the standard) are disabled to * avoid a spurious warning (-Wunused-macros). */ #define _NET_WM_MOVERESIZE_SIZE_TOPLEFT 0 #define _NET_WM_MOVERESIZE_SIZE_TOP 1 #define _NET_WM_MOVERESIZE_SIZE_TOPRIGHT 2 #define _NET_WM_MOVERESIZE_SIZE_RIGHT 3 #define _NET_WM_MOVERESIZE_SIZE_BOTTOMRIGHT 4 #define _NET_WM_MOVERESIZE_SIZE_BOTTOM 5 #define _NET_WM_MOVERESIZE_SIZE_BOTTOMLEFT 6 #define _NET_WM_MOVERESIZE_SIZE_LEFT 7 #define _NET_WM_MOVERESIZE_MOVE 8 /* movement only */ #define _NET_WM_MOVERESIZE_SIZE_KEYBOARD 9 /* size via keyboard */ #define _NET_WM_MOVERESIZE_MOVE_KEYBOARD 10 /* move via keyboard */ #endif static void observer(void *self, WMNotification *notif); static void wsobserver(void *self, WMNotification *notif); static void updateClientList(WScreen *scr); static void updateClientListStacking(WScreen *scr, WWindow *); static void updateWorkspaceNames(WScreen *scr); static void updateCurrentWorkspace(WScreen *scr); static void updateWorkspaceCount(WScreen *scr); static void wNETWMShowingDesktop(WScreen *scr, Bool show); typedef struct NetData { WScreen *scr; WReservedArea *strut; WWindow **show_desktop; } NetData; static void setSupportedHints(WScreen *scr) { Atom atom[wlengthof(atomNames)]; int i = 0; /* set supported hints list */ /* XXX: extend this !!! */ atom[i++] = net_client_list; atom[i++] = net_client_list_stacking; atom[i++] = net_number_of_desktops; atom[i++] = net_desktop_geometry; atom[i++] = net_desktop_viewport; atom[i++] = net_current_desktop; atom[i++] = net_desktop_names; atom[i++] = net_active_window; atom[i++] = net_workarea; atom[i++] = net_supporting_wm_check; atom[i++] = net_showing_desktop; #if 0 atom[i++] = net_wm_moveresize; #endif atom[i++] = net_wm_desktop; atom[i++] = net_wm_window_type; atom[i++] = net_wm_window_type_desktop; atom[i++] = net_wm_window_type_dock; atom[i++] = net_wm_window_type_toolbar; atom[i++] = net_wm_window_type_menu; atom[i++] = net_wm_window_type_utility; atom[i++] = net_wm_window_type_splash; atom[i++] = net_wm_window_type_dialog; atom[i++] = net_wm_window_type_dropdown_menu; atom[i++] = net_wm_window_type_popup_menu; atom[i++] = net_wm_window_type_tooltip; atom[i++] = net_wm_window_type_notification; atom[i++] = net_wm_window_type_combo; atom[i++] = net_wm_window_type_dnd; atom[i++] = net_wm_window_type_normal; atom[i++] = net_wm_state; /* atom[i++] = net_wm_state_modal; *//* XXX: not sure where/when to use it. */ atom[i++] = net_wm_state_sticky; atom[i++] = net_wm_state_shaded; atom[i++] = net_wm_state_maximized_horz; atom[i++] = net_wm_state_maximized_vert; atom[i++] = net_wm_state_skip_taskbar; atom[i++] = net_wm_state_skip_pager; atom[i++] = net_wm_state_hidden; atom[i++] = net_wm_state_fullscreen; atom[i++] = net_wm_state_above; atom[i++] = net_wm_state_below; + atom[i++] = net_wm_state_focused; atom[i++] = net_wm_allowed_actions; atom[i++] = net_wm_action_move; atom[i++] = net_wm_action_resize; atom[i++] = net_wm_action_minimize; atom[i++] = net_wm_action_shade; atom[i++] = net_wm_action_stick; atom[i++] = net_wm_action_maximize_horz; atom[i++] = net_wm_action_maximize_vert; atom[i++] = net_wm_action_fullscreen; atom[i++] = net_wm_action_change_desktop; atom[i++] = net_wm_action_close; atom[i++] = net_wm_strut; atom[i++] = net_wm_icon_geometry; atom[i++] = net_wm_icon; atom[i++] = net_wm_handled_icons; atom[i++] = net_wm_window_opacity; atom[i++] = net_frame_extents; atom[i++] = net_wm_name; atom[i++] = net_wm_icon_name; XChangeProperty(dpy, scr->root_win, net_supported, XA_ATOM, 32, PropModeReplace, (unsigned char *)atom, i); /* set supporting wm hint */ XChangeProperty(dpy, scr->root_win, net_supporting_wm_check, XA_WINDOW, 32, PropModeReplace, (unsigned char *)&scr->info_window, 1); XChangeProperty(dpy, scr->info_window, net_supporting_wm_check, XA_WINDOW, 32, PropModeReplace, (unsigned char *)&scr->info_window, 1); } void wNETWMUpdateDesktop(WScreen *scr) { long *views, sizes[2]; int count, i; if (scr->workspace_count == 0) return; count = scr->workspace_count * 2; views = wmalloc(sizeof(long) * count); sizes[0] = scr->scr_width; sizes[1] = scr->scr_height; for (i = 0; i < scr->workspace_count; i++) { views[2 * i + 0] = 0; views[2 * i + 1] = 0; } XChangeProperty(dpy, scr->root_win, net_desktop_geometry, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)sizes, 2); XChangeProperty(dpy, scr->root_win, net_desktop_viewport, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)views, count); wfree(views); } int wNETWMGetCurrentDesktopFromHint(WScreen *scr) { int count; unsigned char *prop; prop = PropGetCheckProperty(scr->root_win, net_current_desktop, XA_CARDINAL, 0, 1, &count); if (prop) { int desktop = *(long *)prop; XFree(prop); return desktop; } return -1; } static RImage *makeRImageFromARGBData(unsigned long *data) { int size, width, height, i; RImage *image; unsigned char *imgdata; unsigned long pixel; width = data[0]; height = data[1]; size = width * height; if (size == 0) return NULL; image = RCreateImage(width, height, True); for (imgdata = image->data, i = 2; i < size + 2; i++, imgdata += 4) { pixel = data[i]; imgdata[3] = (pixel >> 24) & 0xff; /* A */ imgdata[0] = (pixel >> 16) & 0xff; /* R */ imgdata[1] = (pixel >> 8) & 0xff; /* G */ imgdata[2] = (pixel >> 0) & 0xff; /* B */ } return image; } /* Find the best icon to be used by Window Maker for appicon/miniwindows. */ static RImage *findBestIcon(unsigned long *data, unsigned long items) { int wanted; int dx, dy, d; int sx, sy, size; int best_d, largest; unsigned long i; unsigned long *icon; RImage *src_image, *ret_image; double f; if (wPreferences.enforce_icon_margin) { /* better use only 75% of icon_size. For 64x64 this means 48x48 * This leaves room around the icon for the miniwindow title and * results in better overall aesthetics -Dan */ wanted = (int)((double)wPreferences.icon_size * 0.75 + 0.5); /* the size should be a multiple of 4 */ wanted = (wanted >> 2) << 2; } else { /* This is the "old" approach, which tries to find the largest * icon that still fits into icon_size. */ wanted = wPreferences.icon_size; } /* try to find an icon which is close to the wanted size, but not larger */ icon = NULL; best_d = wanted * wanted * 2; for (i = 0L; i < items - 1;) { /* get the current icon's size */ sx = (int)data[i]; sy = (int)data[i + 1]; if ((sx < 1) || (sy < 1)) break; size = sx * sy + 2; /* check the size difference if it's not too large */ if ((sx <= wanted) && (sy <= wanted)) { dx = wanted - sx; dy = wanted - sy; d = (dx * dx) + (dy * dy); if (d < best_d) { icon = &data[i]; best_d = d; } } i += size; } /* if an icon has been found, no transformation is needed */ if (icon) return makeRImageFromARGBData(icon); /* We need to scale down an icon. Find the largest one, for it usually * looks better to scale down a large image by a large scale than a * small image by a small scale. */ largest = 0; for (i = 0L; i < items - 1;) { size = (int)data[i] * (int)data[i + 1]; if (size == 0) break; if (size > largest) { icon = &data[i]; largest = size; } i += size + 2; } /* give up if there's no icon to work with */ if (!icon) return NULL; /* create a scaled down version of the icon */ src_image = makeRImageFromARGBData(icon); if (src_image->width > src_image->height) { f = (double)wanted / (double)src_image->width; ret_image = RScaleImage(src_image, wanted, (int)(f * (double)(src_image->height))); } else { f = (double)wanted / (double)src_image->height; ret_image = RScaleImage(src_image, (int)(f * (double)src_image->width), wanted); } RReleaseImage(src_image); return ret_image; } RImage *get_window_image_from_x11(Window window) { RImage *image; Atom type; int format; unsigned long items, rest; unsigned long *property; /* Get the icon from X11 Window */ if (XGetWindowProperty(dpy, window, net_wm_icon, 0L, LONG_MAX, False, XA_CARDINAL, &type, &format, &items, &rest, (unsigned char **)&property) != Success || !property) return NULL; if (type != XA_CARDINAL || format != 32 || items < 2) { XFree(property); return NULL; } /* Find the best icon */ image = findBestIcon(property, items); XFree(property); if (!image) return NULL; /* Resize the image to the correct value */ image = wIconValidateIconSize(image, wPreferences.icon_size); return image; } static void updateIconImage(WWindow *wwin) { /* Remove the icon image from X11 */ if (wwin->net_icon_image) RReleaseImage(wwin->net_icon_image); /* Save the icon in the X11 icon */ wwin->net_icon_image = get_window_image_from_x11(wwin->client_win); /* Refresh the Window Icon */ if (wwin->icon) wIconUpdate(wwin->icon); /* Refresh the application icon */ WApplication *app = wApplicationOf(wwin->main_window); if (app && app->app_icon) { wIconUpdate(app->app_icon->icon); wAppIconPaint(app->app_icon); } } static void updateWindowOpacity(WWindow *wwin) { Atom type; int format; unsigned long items, rest; unsigned long *property; if (!wwin->frame) return; /* We don't care about this ourselves, but other programs need us to copy * this to the frame window. */ if (XGetWindowProperty(dpy, wwin->client_win, net_wm_window_opacity, 0L, 1L, False, XA_CARDINAL, &type, &format, &items, &rest, (unsigned char **)&property) != Success) return; if (type == None) { XDeleteProperty(dpy, wwin->frame->core->window, net_wm_window_opacity); } else if (type == XA_CARDINAL && format == 32 && items == 1 && property) { XChangeProperty(dpy, wwin->frame->core->window, net_wm_window_opacity, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)property, 1L); } if (property) XFree(property); } static void updateShowDesktop(WScreen *scr, Bool show) { long foo; foo = (show == True); XChangeProperty(dpy, scr->root_win, net_showing_desktop, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&foo, 1); } static void wNETWMShowingDesktop(WScreen *scr, Bool show) { if (show && scr->netdata->show_desktop == NULL) { WWindow *tmp, **wins; int i = 0; wins = (WWindow **) wmalloc(sizeof(WWindow *) * (scr->window_count + 1)); tmp = scr->focused_window; while (tmp) { if (!tmp->flags.hidden && !tmp->flags.miniaturized && !WFLAGP(tmp, skip_window_list)) { wins[i++] = tmp; tmp->flags.skip_next_animation = 1; tmp->flags.net_show_desktop = 1; wIconifyWindow(tmp); } tmp = tmp->prev; } wins[i++] = NULL; scr->netdata->show_desktop = wins; updateShowDesktop(scr, True); } else if (scr->netdata->show_desktop != NULL) { /* FIXME: get rid of workspace flashing ! */ int ws = scr->current_workspace; WWindow **tmp; for (tmp = scr->netdata->show_desktop; *tmp; ++tmp) { wDeiconifyWindow(*tmp); (*tmp)->flags.net_show_desktop = 0; } if (ws != scr->current_workspace) wWorkspaceChange(scr, ws); wfree(scr->netdata->show_desktop); scr->netdata->show_desktop = NULL; updateShowDesktop(scr, False); } } void wNETWMInitStuff(WScreen *scr) { NetData *data; int i; #ifdef DEBUG_WMSPEC wmessage("wNETWMInitStuff"); #endif #ifdef HAVE_XINTERNATOMS { Atom atoms[wlengthof(atomNames)]; char *names[wlengthof(atomNames)]; for (i = 0; i < wlengthof(atomNames); ++i) names[i] = atomNames[i].name; XInternAtoms(dpy, &names[0], wlengthof(atomNames), False, atoms); for (i = 0; i < wlengthof(atomNames); ++i) *atomNames[i].atom = atoms[i]; } #else for (i = 0; i < wlengthof(atomNames); i++) *atomNames[i].atom = XInternAtom(dpy, atomNames[i].name, False); #endif data = wmalloc(sizeof(NetData)); data->scr = scr; data->strut = NULL; data->show_desktop = NULL; scr->netdata = data; setSupportedHints(scr); WMAddNotificationObserver(observer, data, WMNManaged, NULL); WMAddNotificationObserver(observer, data, WMNUnmanaged, NULL); WMAddNotificationObserver(observer, data, WMNChangedWorkspace, NULL); WMAddNotificationObserver(observer, data, WMNChangedState, NULL); WMAddNotificationObserver(observer, data, WMNChangedFocus, NULL); WMAddNotificationObserver(observer, data, WMNChangedStacking, NULL); WMAddNotificationObserver(observer, data, WMNChangedName, NULL); WMAddNotificationObserver(wsobserver, data, WMNWorkspaceCreated, NULL); WMAddNotificationObserver(wsobserver, data, WMNWorkspaceDestroyed, NULL); WMAddNotificationObserver(wsobserver, data, WMNWorkspaceChanged, NULL); WMAddNotificationObserver(wsobserver, data, WMNWorkspaceNameChanged, NULL); updateClientList(scr); updateClientListStacking(scr, NULL); updateWorkspaceCount(scr); updateWorkspaceNames(scr); updateShowDesktop(scr, False); wScreenUpdateUsableArea(scr); } void wNETWMCleanup(WScreen *scr) { int i; for (i = 0; i < wlengthof(atomNames); i++) XDeleteProperty(dpy, scr->root_win, *atomNames[i].atom); } void wNETWMUpdateActions(WWindow *wwin, Bool del) { Atom action[10]; /* nr of actions atoms defined */ int i = 0; if (del) { XDeleteProperty(dpy, wwin->client_win, net_wm_allowed_actions); return; } if (IS_MOVABLE(wwin)) action[i++] = net_wm_action_move; if (IS_RESIZABLE(wwin)) action[i++] = net_wm_action_resize; if (!WFLAGP(wwin, no_miniaturizable)) action[i++] = net_wm_action_minimize; if (!WFLAGP(wwin, no_shadeable)) action[i++] = net_wm_action_shade; /* if (!WFLAGP(wwin, no_stickable)) */ action[i++] = net_wm_action_stick; /* if (!(WFLAGP(wwin, no_maximizeable) & MAX_HORIZONTAL)) */ if (IS_RESIZABLE(wwin)) action[i++] = net_wm_action_maximize_horz; /* if (!(WFLAGP(wwin, no_maximizeable) & MAX_VERTICAL)) */ if (IS_RESIZABLE(wwin)) action[i++] = net_wm_action_maximize_vert; /* if (!WFLAGP(wwin, no_fullscreen)) */ action[i++] = net_wm_action_fullscreen; /* if (!WFLAGP(wwin, no_change_desktop)) */ action[i++] = net_wm_action_change_desktop; if (!WFLAGP(wwin, no_closable)) action[i++] = net_wm_action_close; XChangeProperty(dpy, wwin->client_win, net_wm_allowed_actions, XA_ATOM, 32, PropModeReplace, (unsigned char *)action, i); } void wNETWMUpdateWorkarea(WScreen *scr) { WArea total_usable; int nb_workspace; if (!scr->netdata) { /* If the _NET_xxx were not initialised, it not necessary to do anything */ return; } if (!scr->usableArea) { /* If we don't have any info, we fall back on using the complete screen area */ total_usable.x1 = 0; total_usable.y1 = 0; total_usable.x2 = scr->scr_width; total_usable.y2 = scr->scr_height; } else { int i; /* * the _NET_WORKAREA is supposed to contain the total area of the screen that * is usable, so we merge the areas from all xrandr sub-screens */ total_usable = scr->usableArea[0]; for (i = 1; i < wXineramaHeads(scr); i++) { /* The merge is not subtle because _NET_WORKAREA does not need more */ if (scr->usableArea[i].x1 < total_usable.x1) total_usable.x1 = scr->usableArea[i].x1; if (scr->usableArea[i].y1 < total_usable.y1) total_usable.y1 = scr->usableArea[i].y1; if (scr->usableArea[i].x2 > total_usable.x2) total_usable.x2 = scr->usableArea[i].x2; if (scr->usableArea[i].y2 > total_usable.y2) total_usable.y2 = scr->usableArea[i].y2; } } /* We are expected to repeat the information for each workspace */ if (scr->workspace_count == 0) nb_workspace = 1; else nb_workspace = scr->workspace_count; { long property_value[nb_workspace * 4]; int i; for (i = 0; i < nb_workspace; i++) { property_value[4 * i + 0] = total_usable.x1; property_value[4 * i + 1] = total_usable.y1; property_value[4 * i + 2] = total_usable.x2 - total_usable.x1; property_value[4 * i + 3] = total_usable.y2 - total_usable.y1; } XChangeProperty(dpy, scr->root_win, net_workarea, XA_CARDINAL, 32, PropModeReplace, (unsigned char *) property_value, nb_workspace * 4); } } Bool wNETWMGetUsableArea(WScreen *scr, int head, WArea *area) { WReservedArea *cur; WMRect rect; if (!scr->netdata || !scr->netdata->strut) return False; area->x1 = area->y1 = area->x2 = area->y2 = 0; for (cur = scr->netdata->strut; cur; cur = cur->next) { WWindow *wwin = wWindowFor(cur->window); if (wWindowTouchesHead(wwin, head)) { if (cur->area.x1 > area->x1) area->x1 = cur->area.x1; if (cur->area.y1 > area->y1) area->y1 = cur->area.y1; if (cur->area.x2 > area->x2) area->x2 = cur->area.x2; if (cur->area.y2 > area->y2) area->y2 = cur->area.y2; } } if (area->x1 == 0 && area->x2 == 0 && area->y1 == 0 && area->y2 == 0) return False; rect = wGetRectForHead(scr, head); area->x1 = rect.pos.x + area->x1; area->x2 = rect.pos.x + rect.size.width - area->x2; area->y1 = rect.pos.y + area->y1; area->y2 = rect.pos.y + rect.size.height - area->y2; return True; } static void updateClientList(WScreen *scr) { WWindow *wwin; Window *windows; int count; windows = (Window *) wmalloc(sizeof(Window) * (scr->window_count + 1)); count = 0; wwin = scr->focused_window; while (wwin) { windows[count++] = wwin->client_win; wwin = wwin->prev; } XChangeProperty(dpy, scr->root_win, net_client_list, XA_WINDOW, 32, PropModeReplace, (unsigned char *)windows, count); wfree(windows); XFlush(dpy); } static void updateClientListStacking(WScreen *scr, WWindow *wwin_excl) { WWindow *wwin; Window *client_list, *client_list_reverse; int client_count, i; WCoreWindow *tmp; WMBagIterator iter; /* update client list */ i = scr->window_count + 1; client_list = (Window *) wmalloc(sizeof(Window) * i); client_list_reverse = (Window *) wmalloc(sizeof(Window) * i); client_count = 0; WM_ETARETI_BAG(scr->stacking_list, tmp, iter) { while (tmp) { wwin = wWindowFor(tmp->window); /* wwin_excl is a window to exclude from the list (e.g. it's now unmanaged) */ if (wwin && (wwin != wwin_excl)) client_list[client_count++] = wwin->client_win; tmp = tmp->stacking->under; } } for (i = 0; i < client_count; i++) { Window w = client_list[client_count - i - 1]; client_list_reverse[i] = w; } XChangeProperty(dpy, scr->root_win, net_client_list_stacking, XA_WINDOW, 32, PropModeReplace, (unsigned char *)client_list_reverse, client_count); wfree(client_list); wfree(client_list_reverse); XFlush(dpy); } static void updateWorkspaceCount(WScreen *scr) { /* changeable */ long count; count = scr->workspace_count; XChangeProperty(dpy, scr->root_win, net_number_of_desktops, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&count, 1); } static void updateCurrentWorkspace(WScreen *scr) { /* changeable */ long count; count = scr->current_workspace; XChangeProperty(dpy, scr->root_win, net_current_desktop, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&count, 1); } static void updateWorkspaceNames(WScreen *scr) { char buf[MAX_WORKSPACES * (MAX_WORKSPACENAME_WIDTH + 1)], *pos; unsigned int i, len, curr_size; pos = buf; len = 0; for (i = 0; i < scr->workspace_count; i++) { curr_size = strlen(scr->workspaces[i]->name); strcpy(pos, scr->workspaces[i]->name); pos += (curr_size + 1); len += (curr_size + 1); } XChangeProperty(dpy, scr->root_win, net_desktop_names, utf8_string, 8, PropModeReplace, (unsigned char *)buf, len); } static void updateFocusHint(WScreen *scr) { /* changeable */ Window window; if (!scr->focused_window || !scr->focused_window->flags.focused) window = None; else window = scr->focused_window->client_win; XChangeProperty(dpy, scr->root_win, net_active_window, XA_WINDOW, 32, PropModeReplace, (unsigned char *)&window, 1); } static void updateWorkspaceHint(WWindow *wwin, Bool fake, Bool del) { long l; if (del) { XDeleteProperty(dpy, wwin->client_win, net_wm_desktop); } else { l = ((fake || IS_OMNIPRESENT(wwin)) ? -1 : wwin->frame->workspace); XChangeProperty(dpy, wwin->client_win, net_wm_desktop, XA_CARDINAL, 32, PropModeReplace, (unsigned char *)&l, 1); } } static void updateStateHint(WWindow *wwin, Bool changedWorkspace, Bool del) { /* changeable */ if (del) { XDeleteProperty(dpy, wwin->client_win, net_wm_state); } else { Atom state[15]; /* nr of defined state atoms */ int i = 0; if (changedWorkspace || (wPreferences.sticky_icons && !IS_OMNIPRESENT(wwin))) updateWorkspaceHint(wwin, False, False); if (IS_OMNIPRESENT(wwin)) state[i++] = net_wm_state_sticky; if (wwin->flags.shaded) state[i++] = net_wm_state_shaded; if (wwin->flags.maximized & MAX_HORIZONTAL) state[i++] = net_wm_state_maximized_horz; if (wwin->flags.maximized & MAX_VERTICAL) state[i++] = net_wm_state_maximized_vert; if (WFLAGP(wwin, skip_window_list)) state[i++] = net_wm_state_skip_taskbar; if (wwin->flags.net_skip_pager) state[i++] = net_wm_state_skip_pager; if ((wwin->flags.hidden || wwin->flags.miniaturized) && !wwin->flags.net_show_desktop) { state[i++] = net_wm_state_hidden; state[i++] = net_wm_state_skip_pager; if (wwin->flags.miniaturized && wPreferences.sticky_icons) { if (!IS_OMNIPRESENT(wwin)) updateWorkspaceHint(wwin, True, False); state[i++] = net_wm_state_sticky; } } if (WFLAGP(wwin, sunken)) state[i++] = net_wm_state_below; if (WFLAGP(wwin, floating)) state[i++] = net_wm_state_above; if (wwin->flags.fullscreen) state[i++] = net_wm_state_fullscreen; + if (wwin->flags.focused) + state[i++] = net_wm_state_focused; XChangeProperty(dpy, wwin->client_win, net_wm_state, XA_ATOM, 32, PropModeReplace, (unsigned char *)state, i); } } static Bool updateStrut(WScreen *scr, Window w, Bool adding) { WReservedArea *area; Bool hasState = False; if (adding) { Atom type_ret; int fmt_ret; unsigned long nitems_ret, bytes_after_ret; long *data = NULL; if ((XGetWindowProperty(dpy, w, net_wm_strut, 0, 4, False, XA_CARDINAL, &type_ret, &fmt_ret, &nitems_ret, &bytes_after_ret, (unsigned char **)&data) == Success && data) || ((XGetWindowProperty(dpy, w, net_wm_strut_partial, 0, 12, False, XA_CARDINAL, &type_ret, &fmt_ret, &nitems_ret, &bytes_after_ret, (unsigned char **)&data) == Success && data))) { /* XXX: This is strictly incorrect in the case of net_wm_strut_partial... * Discard the start and end properties from the partial strut and treat it as * a (deprecated) strut. * This means we are marking the whole width or height of the screen as * reserved, which is not necessarily what the strut defines. However for the * purposes of determining placement or maximization it's probably good enough. */ area = (WReservedArea *) wmalloc(sizeof(WReservedArea)); area->area.x1 = data[0]; area->area.x2 = data[1]; area->area.y1 = data[2]; area->area.y2 = data[3]; area->window = w; area->next = scr->netdata->strut; scr->netdata->strut = area; XFree(data); hasState = True; } } else { /* deleting */ area = scr->netdata->strut; if (area) { if (area->window == w) { scr->netdata->strut = area->next; wfree(area); hasState = True; } else { while (area->next && area->next->window != w) area = area->next; if (area->next) { WReservedArea *next; next = area->next->next; wfree(area->next); area->next = next; hasState = True; } } } } return hasState; } static int getWindowLayer(WWindow *wwin) { int layer = WMNormalLevel; if (wwin->type == net_wm_window_type_desktop) { layer = WMDesktopLevel; } else if (wwin->type == net_wm_window_type_dock) { layer = WMDockLevel; } else if (wwin->type == net_wm_window_type_toolbar) { layer = WMMainMenuLevel; } else if (wwin->type == net_wm_window_type_menu) { layer = WMSubmenuLevel; } else if (wwin->type == net_wm_window_type_utility) { } else if (wwin->type == net_wm_window_type_splash) { } else if (wwin->type == net_wm_window_type_dialog) { if (wwin->transient_for) { WWindow *parent = wWindowFor(wwin->transient_for); if (parent && parent->flags.fullscreen) layer = WMFullscreenLevel; } /* //layer = WMPopUpLevel; // this seems a bad idea -Dan */ } else if (wwin->type == net_wm_window_type_dropdown_menu) { layer = WMSubmenuLevel; } else if (wwin->type == net_wm_window_type_popup_menu) { layer = WMSubmenuLevel; } else if (wwin->type == net_wm_window_type_tooltip) { } else if (wwin->type == net_wm_window_type_notification) { layer = WMPopUpLevel; } else if (wwin->type == net_wm_window_type_combo) { layer = WMSubmenuLevel; } else if (wwin->type == net_wm_window_type_dnd) { } else if (wwin->type == net_wm_window_type_normal) { } if (wwin->client_flags.sunken && WMSunkenLevel < layer) layer = WMSunkenLevel; if (wwin->client_flags.floating && WMFloatingLevel > layer) layer = WMFloatingLevel; return layer; } static void doStateAtom(WWindow *wwin, Atom state, int set, Bool init) { if (state == net_wm_state_sticky) { if (set == _NET_WM_STATE_TOGGLE) set = !IS_OMNIPRESENT(wwin); if (set != wwin->flags.omnipresent) wWindowSetOmnipresent(wwin, set); } else if (state == net_wm_state_shaded) { if (set == _NET_WM_STATE_TOGGLE) set = !wwin->flags.shaded; if (init) { wwin->flags.shaded = set; } else { if (set) wShadeWindow(wwin); else wUnshadeWindow(wwin); } } else if (state == net_wm_state_skip_taskbar) { if (set == _NET_WM_STATE_TOGGLE) set = !wwin->client_flags.skip_window_list; wwin->client_flags.skip_window_list = set; } else if (state == net_wm_state_skip_pager) { if (set == _NET_WM_STATE_TOGGLE) set = !wwin->flags.net_skip_pager; wwin->flags.net_skip_pager = set; } else if (state == net_wm_state_maximized_vert) { if (set == _NET_WM_STATE_TOGGLE) set = !(wwin->flags.maximized & MAX_VERTICAL); if (init) { wwin->flags.maximized |= (set ? MAX_VERTICAL : 0); } else { if (set) wMaximizeWindow(wwin, wwin->flags.maximized | MAX_VERTICAL, wGetHeadForWindow(wwin)); else wMaximizeWindow(wwin, wwin->flags.maximized & ~MAX_VERTICAL, wGetHeadForWindow(wwin)); } } else if (state == net_wm_state_maximized_horz) { if (set == _NET_WM_STATE_TOGGLE) set = !(wwin->flags.maximized & MAX_HORIZONTAL); if (init) { wwin->flags.maximized |= (set ? MAX_HORIZONTAL : 0); } else { if (set) wMaximizeWindow(wwin, wwin->flags.maximized | MAX_HORIZONTAL, wGetHeadForWindow(wwin)); else wMaximizeWindow(wwin, wwin->flags.maximized & ~MAX_HORIZONTAL, wGetHeadForWindow(wwin)); } } else if (state == net_wm_state_hidden) { if (set == _NET_WM_STATE_TOGGLE) set = !(wwin->flags.miniaturized); if (init) { wwin->flags.miniaturized = set; } else { if (set) wIconifyWindow(wwin); else wDeiconifyWindow(wwin); } } else if (state == net_wm_state_fullscreen) { if (set == _NET_WM_STATE_TOGGLE) set = !(wwin->flags.fullscreen); if (init) { wwin->flags.fullscreen = set; } else { if (set) wFullscreenWindow(wwin); else wUnfullscreenWindow(wwin); } } else if (state == net_wm_state_above) { if (set == _NET_WM_STATE_TOGGLE) set = !(wwin->client_flags.floating); if (init) { wwin->client_flags.floating = set; } else { wwin->client_flags.floating = set; ChangeStackingLevel(wwin->frame->core, getWindowLayer(wwin)); } } else if (state == net_wm_state_below) { if (set == _NET_WM_STATE_TOGGLE) set = !(wwin->client_flags.sunken); if (init) { wwin->client_flags.sunken = set; } else { wwin->client_flags.sunken = set; ChangeStackingLevel(wwin->frame->core, getWindowLayer(wwin)); } } else { #ifdef DEBUG_WMSPEC wmessage("doStateAtom unknown atom %s set %d", XGetAtomName(dpy, state), set); #endif } } static void removeIcon(WWindow *wwin) { if (wwin->icon == NULL) return; if (wwin->flags.miniaturized && wwin->icon->mapped) { XUnmapWindow(dpy, wwin->icon->core->window); RemoveFromStackList(wwin->icon->core); wIconDestroy(wwin->icon); wwin->icon = NULL; } } static Bool handleWindowType(WWindow *wwin, Atom type, int *layer) { Bool ret = True; if (type == net_wm_window_type_desktop) { wwin->client_flags.no_titlebar = 1; wwin->client_flags.no_resizable = 1; wwin->client_flags.no_miniaturizable = 1; wwin->client_flags.no_border = 1; wwin->client_flags.no_resizebar = 1; wwin->client_flags.no_shadeable = 1; wwin->client_flags.no_movable = 1; wwin->client_flags.omnipresent = 1; wwin->client_flags.skip_window_list = 1; wwin->client_flags.skip_switchpanel = 1; wwin->client_flags.dont_move_off = 1; wwin->client_flags.no_appicon = 1; wwin->flags.net_skip_pager = 1; wwin->frame_x = 0; wwin->frame_y = 0; } else if (type == net_wm_window_type_dock) { wwin->client_flags.no_titlebar = 1; wwin->client_flags.no_resizable = 1; wwin->client_flags.no_miniaturizable = 1; wwin->client_flags.no_border = 1; /* XXX: really not a single decoration. */ wwin->client_flags.no_resizebar = 1; wwin->client_flags.no_shadeable = 1; wwin->client_flags.no_movable = 1; wwin->client_flags.omnipresent = 1; wwin->client_flags.skip_window_list = 1; wwin->client_flags.skip_switchpanel = 1; wwin->client_flags.dont_move_off = 1; wwin->flags.net_skip_pager = 1; } else if (type == net_wm_window_type_toolbar || type == net_wm_window_type_menu) { wwin->client_flags.no_resizable = 1; wwin->client_flags.no_miniaturizable = 1; wwin->client_flags.no_resizebar = 1; wwin->client_flags.no_shadeable = 1; wwin->client_flags.skip_window_list = 1; wwin->client_flags.skip_switchpanel = 1; wwin->client_flags.dont_move_off = 1; wwin->client_flags.no_appicon = 1; } else if (type == net_wm_window_type_dropdown_menu || type == net_wm_window_type_popup_menu || type == net_wm_window_type_combo) { wwin->client_flags.no_titlebar = 1; wwin->client_flags.no_resizable = 1; wwin->client_flags.no_miniaturizable = 1; wwin->client_flags.no_resizebar = 1; wwin->client_flags.no_shadeable = 1; wwin->client_flags.skip_window_list = 1; wwin->client_flags.skip_switchpanel = 1; wwin->client_flags.dont_move_off = 1; wwin->client_flags.no_appicon = 1; } else if (type == net_wm_window_type_utility) { wwin->client_flags.no_appicon = 1; } else if (type == net_wm_window_type_splash) { wwin->client_flags.no_titlebar = 1; wwin->client_flags.no_resizable = 1; wwin->client_flags.no_miniaturizable = 1; wwin->client_flags.no_resizebar = 1; wwin->client_flags.no_shadeable = 1; wwin->client_flags.no_movable = 1; wwin->client_flags.skip_window_list = 1; wwin->client_flags.skip_switchpanel = 1; wwin->client_flags.dont_move_off = 1; wwin->client_flags.no_appicon = 1; wwin->flags.net_skip_pager = 1; } else if (type == net_wm_window_type_dialog) { /* These also seem a bad idea in our context -Dan // wwin->client_flags.skip_window_list = 1; // wwin->client_flags.no_appicon = 1; */ } else if (wwin->type == net_wm_window_type_tooltip) { wwin->client_flags.no_titlebar = 1; wwin->client_flags.no_resizable = 1; wwin->client_flags.no_miniaturizable = 1; wwin->client_flags.no_resizebar = 1; wwin->client_flags.no_shadeable = 1; wwin->client_flags.no_movable = 1; wwin->client_flags.skip_window_list = 1; wwin->client_flags.skip_switchpanel = 1; wwin->client_flags.dont_move_off = 1; wwin->client_flags.no_appicon = 1; wwin->client_flags.no_focusable = 1; wwin->flags.net_skip_pager = 1; } else if (wwin->type == net_wm_window_type_notification) { wwin->client_flags.no_titlebar = 1; wwin->client_flags.no_resizable = 1; wwin->client_flags.no_miniaturizable = 1; wwin->client_flags.no_border = 1; wwin->client_flags.no_resizebar = 1; wwin->client_flags.no_shadeable = 1; wwin->client_flags.no_movable = 1; wwin->client_flags.omnipresent = 1; wwin->client_flags.skip_window_list = 1; wwin->client_flags.skip_switchpanel = 1; wwin->client_flags.dont_move_off = 1; wwin->client_flags.no_hide_others= 1; wwin->client_flags.no_appicon = 1; wwin->client_flags.no_focusable = 1; wwin->flags.net_skip_pager = 1; } else if (wwin->type == net_wm_window_type_dnd) { wwin->client_flags.no_titlebar = 1; wwin->client_flags.no_resizable = 1; wwin->client_flags.no_miniaturizable = 1; wwin->client_flags.no_border = 1; wwin->client_flags.no_resizebar = 1; wwin->client_flags.no_shadeable = 1; wwin->client_flags.no_movable = 1; wwin->client_flags.skip_window_list = 1; wwin->client_flags.skip_switchpanel = 1; wwin->client_flags.dont_move_off = 1; wwin->client_flags.no_appicon = 1; wwin->flags.net_skip_pager = 1; } else if (type == net_wm_window_type_normal) { } else { ret = False; } /* Restore decoration if the user has enabled the * IgnoreDecorationChanges option */ if (WFLAGP(wwin, ignore_decoration_changes)) { wwin->client_flags.no_titlebar = 0; wwin->client_flags.no_resizable = 0; wwin->client_flags.no_miniaturizable = 0; wwin->client_flags.no_resizebar = 0; wwin->client_flags.no_border = 0; wwin->client_flags.no_movable = 0; } wwin->type = type; *layer = getWindowLayer(wwin); return ret; } void wNETWMPositionSplash(WWindow *wwin, int *x, int *y, int width, int height) { if (wwin->type == net_wm_window_type_splash) { WScreen *scr = wwin->screen_ptr; WMRect rect = wGetRectForHead(scr, wGetHeadForPointerLocation(scr)); *x = rect.pos.x + (rect.size.width - width) / 2; *y = rect.pos.y + (rect.size.height - height) / 2; } } static void updateWindowType(WWindow *wwin) { Atom type_ret; int fmt_ret, layer; unsigned long nitems_ret, bytes_after_ret; long *data = NULL; if (XGetWindowProperty(dpy, wwin->client_win, net_wm_window_type, 0, 1, False, XA_ATOM, &type_ret, &fmt_ret, &nitems_ret, &bytes_after_ret, (unsigned char **)&data) == Success && data) { int i; Atom *type = (Atom *) data; for (i = 0; i < nitems_ret; ++i) { if (handleWindowType(wwin, type[i], &layer)) break; } XFree(data); } if (wwin->frame != NULL) { ChangeStackingLevel(wwin->frame->core, layer); wwin->frame->flags.need_texture_change = 1; wWindowConfigureBorders(wwin); wFrameWindowPaint(wwin->frame); wNETWMUpdateActions(wwin, False); } } void wNETWMCheckClientHints(WWindow *wwin, int *layer, int *workspace) { Atom type_ret; int fmt_ret, i; unsigned long nitems_ret, bytes_after_ret; long *data = NULL; if (XGetWindowProperty(dpy, wwin->client_win, net_wm_desktop, 0, 1, False, XA_CARDINAL, &type_ret, &fmt_ret, &nitems_ret, &bytes_after_ret, (unsigned char **)&data) == Success && data) { long desktop = *data; XFree(data); if (desktop == -1) wwin->client_flags.omnipresent = 1; else *workspace = desktop; } if (XGetWindowProperty(dpy, wwin->client_win, net_wm_state, 0, 1, False, XA_ATOM, &type_ret, &fmt_ret, &nitems_ret, &bytes_after_ret, (unsigned char **)&data) == Success && data) { Atom *state = (Atom *) data; for (i = 0; i < nitems_ret; ++i) doStateAtom(wwin, state[i], _NET_WM_STATE_ADD, True); XFree(data); } if (XGetWindowProperty(dpy, wwin->client_win, net_wm_window_type, 0, 1, False, XA_ATOM, &type_ret, &fmt_ret, &nitems_ret, &bytes_after_ret, (unsigned char **)&data) == Success && data) { Atom *type = (Atom *) data; for (i = 0; i < nitems_ret; ++i) { if (handleWindowType(wwin, type[i], layer)) break; } XFree(data); } wNETWMUpdateActions(wwin, False); updateStrut(wwin->screen_ptr, wwin->client_win, False); updateStrut(wwin->screen_ptr, wwin->client_win, True); wScreenUpdateUsableArea(wwin->screen_ptr); } static Bool updateNetIconInfo(WWindow *wwin) { Atom type_ret; int fmt_ret; unsigned long nitems_ret, bytes_after_ret; long *data = NULL; Bool hasState = False; Bool old_state = wwin->flags.net_handle_icon; if (XGetWindowProperty(dpy, wwin->client_win, net_wm_handled_icons, 0, 1, False, XA_CARDINAL, &type_ret, &fmt_ret, &nitems_ret, &bytes_after_ret, (unsigned char **)&data) == Success && data) { long handled = *data; wwin->flags.net_handle_icon = (handled != 0); XFree(data); hasState = True; } else { wwin->flags.net_handle_icon = False; } if (XGetWindowProperty(dpy, wwin->client_win, net_wm_icon_geometry, 0, 4, False, XA_CARDINAL, &type_ret, &fmt_ret, &nitems_ret, &bytes_after_ret, (unsigned char **)&data) == Success && data) { #ifdef NETWM_PROPER if (wwin->flags.net_handle_icon) #else wwin->flags.net_handle_icon = True; #endif { wwin->icon_x = data[0]; wwin->icon_y = data[1]; wwin->icon_w = data[2]; wwin->icon_h = data[3]; } XFree(data); hasState = True; } else { wwin->flags.net_handle_icon = False; } if (wwin->flags.miniaturized && old_state != wwin->flags.net_handle_icon) { if (wwin->flags.net_handle_icon) { removeIcon(wwin); } else { wwin->flags.miniaturized = False; wwin->flags.skip_next_animation = True; wIconifyWindow(wwin); } } return hasState; } void wNETWMCheckInitialClientState(WWindow *wwin) { #ifdef DEBUG_WMSPEC wmessage("wNETWMCheckInitialClientState"); #endif wNETWMShowingDesktop(wwin->screen_ptr, False); updateWindowType(wwin); updateNetIconInfo(wwin); updateIconImage(wwin); } void wNETWMCheckInitialFrameState(WWindow *wwin) { #ifdef DEBUG_WMSPEC wmessage("wNETWMCheckInitialFrameState"); #endif updateWindowOpacity(wwin); } static void handleDesktopNames(WScreen *scr) { unsigned long nitems_ret, bytes_after_ret; char *data, *names[32]; int fmt_ret, i, n; Atom type_ret; if (XGetWindowProperty(dpy, scr->root_win, net_desktop_names, 0, 1, False, utf8_string, &type_ret, &fmt_ret, &nitems_ret, &bytes_after_ret, (unsigned char **)&data) != Success) return; if (data == NULL) return; if (type_ret != utf8_string || fmt_ret != 8) return; n = 0; names[n] = data; for (i = 0; i < nitems_ret; i++) { if (data[i] == 0) { n++; names[n] = &data[i]; } else if (*names[n] == 0) { names[n] = &data[i]; wWorkspaceRename(scr, n, names[n]); } } } Bool wNETWMProcessClientMessage(XClientMessageEvent *event) { WScreen *scr; WWindow *wwin; #ifdef DEBUG_WMSPEC wmessage("processClientMessage type %s", XGetAtomName(dpy, event->message_type)); #endif scr = wScreenForWindow(event->window); if (scr) { /* generic client messages */ if (event->message_type == net_current_desktop) { wWorkspaceChange(scr, event->data.l[0]); return True; } else if (event->message_type == net_number_of_desktops) { long value; value = event->data.l[0]; if (value > scr->workspace_count) { wWorkspaceMake(scr, value - scr->workspace_count); } else if (value < scr->workspace_count) { int i; Bool rebuild = False; for (i = scr->workspace_count - 1; i >= value; i--) { if (!wWorkspaceDelete(scr, i)) { rebuild = True; break; } } if (rebuild) updateWorkspaceCount(scr); } return True; } else if (event->message_type == net_showing_desktop) { wNETWMShowingDesktop(scr, event->data.l[0]); return True; } else if (event->message_type == net_desktop_names) { handleDesktopNames(scr); return True; } } /* window specific client messages */ wwin = wWindowFor(event->window); if (!wwin) return False; if (event->message_type == net_active_window) { /* * Satisfy a client's focus request only if * - request comes from a pager, or * - it's explicitly allowed in Advanced Options, or * - giving the client the focus does not cause a change in * the active workspace (XXX: or the active head if Xinerama) */ if (wwin->frame->workspace == wwin->screen_ptr->current_workspace /* No workspace change */ || event->data.l[0] == 2 /* Requested by pager */ || WFLAGP(wwin, focus_across_wksp) /* Explicitly allowed */) { wNETWMShowingDesktop(scr, False); wMakeWindowVisible(wwin); } return True; } else if (event->message_type == net_close_window) { if (!WFLAGP(wwin, no_closable)) { if (wwin->protocols.DELETE_WINDOW) wClientSendProtocol(wwin, w_global.atom.wm.delete_window, w_global.timestamp.last_event); } return True; } else if (event->message_type == net_wm_state) { int maximized = wwin->flags.maximized; long set = event->data.l[0]; #ifdef DEBUG_WMSPEC wmessage("net_wm_state set %ld a1 %s a2 %s", set, XGetAtomName(dpy, event->data.l[1]), XGetAtomName(dpy, event->data.l[2])); #endif doStateAtom(wwin, (Atom) event->data.l[1], set, False); if (event->data.l[2]) doStateAtom(wwin, (Atom) event->data.l[2], set, False); if (wwin->flags.maximized != maximized) { if (!wwin->flags.maximized) { wwin->flags.maximized = maximized; wUnmaximizeWindow(wwin); } else { wMaximizeWindow(wwin, wwin->flags.maximized, wGetHeadForWindow(wwin)); } } updateStateHint(wwin, False, False); return True; } else if (event->message_type == net_wm_handled_icons || event->message_type == net_wm_icon_geometry) { updateNetIconInfo(wwin); return True; } else if (event->message_type == net_wm_desktop) { long desktop = event->data.l[0]; if (desktop == -1) { wWindowSetOmnipresent(wwin, True); } else { if (IS_OMNIPRESENT(wwin)) wWindowSetOmnipresent(wwin, False); wWindowChangeWorkspace(wwin, desktop); } return True; } return False; } void wNETWMCheckClientHintChange(WWindow *wwin, XPropertyEvent *event) { #ifdef DEBUG_WMSPEC wmessage("clientHintChange type %s", XGetAtomName(dpy, event->atom)); #endif if (event->atom == net_wm_strut || event->atom == net_wm_strut_partial) { updateStrut(wwin->screen_ptr, wwin->client_win, False); updateStrut(wwin->screen_ptr, wwin->client_win, True); wScreenUpdateUsableArea(wwin->screen_ptr); } else if (event->atom == net_wm_handled_icons || event->atom == net_wm_icon_geometry) { updateNetIconInfo(wwin); } else if (event->atom == net_wm_window_type) { updateWindowType(wwin); } else if (event->atom == net_wm_name) { char *name = wNETWMGetWindowName(wwin->client_win); wWindowUpdateName(wwin, name); if (name) wfree(name); } else if (event->atom == net_wm_icon_name) { if (wwin->icon) { wIconChangeTitle(wwin->icon, wwin); wIconPaint(wwin->icon); } } else if (event->atom == net_wm_icon) { updateIconImage(wwin); } else if (event->atom == net_wm_window_opacity) { updateWindowOpacity(wwin); } } int wNETWMGetPidForWindow(Window window) { Atom type_ret; int fmt_ret; unsigned long nitems_ret, bytes_after_ret; long *data = NULL; int pid; if (XGetWindowProperty(dpy, window, net_wm_pid, 0, 1, False, XA_CARDINAL, &type_ret, &fmt_ret, &nitems_ret, &bytes_after_ret, (unsigned char **)&data) == Success && data) { pid = *data; XFree(data); } else { pid = 0; } return pid; } char *wNETWMGetWindowName(Window window) { char *name; char *ret; int size; name = (char *)PropGetCheckProperty(window, net_wm_name, utf8_string, 0, 0, &size); if (name) { ret = wstrndup(name, size); XFree(name); } else { ret = NULL; } return ret; } char *wNETWMGetIconName(Window window) { char *name; char *ret; int size; name = (char *)PropGetCheckProperty(window, net_wm_icon_name, utf8_string, 0, 0, &size); if (name) { ret = wstrndup(name, size); XFree(name); } else { ret = NULL; } return ret; } static void observer(void *self, WMNotification *notif) { WWindow *wwin = (WWindow *) WMGetNotificationObject(notif); const char *name = WMGetNotificationName(notif); void *data = WMGetNotificationClientData(notif); NetData *ndata = (NetData *) self; if (strcmp(name, WMNManaged) == 0 && wwin) { updateClientList(wwin->screen_ptr); updateClientListStacking(wwin->screen_ptr, NULL); updateStateHint(wwin, True, False); updateStrut(wwin->screen_ptr, wwin->client_win, False); updateStrut(wwin->screen_ptr, wwin->client_win, True); wScreenUpdateUsableArea(wwin->screen_ptr); } else if (strcmp(name, WMNUnmanaged) == 0 && wwin) { updateClientList(wwin->screen_ptr); updateClientListStacking(wwin->screen_ptr, wwin); updateWorkspaceHint(wwin, False, True); updateStateHint(wwin, False, True); wNETWMUpdateActions(wwin, True); updateStrut(wwin->screen_ptr, wwin->client_win, False); wScreenUpdateUsableArea(wwin->screen_ptr); } else if (strcmp(name, WMNResetStacking) == 0 && wwin) { updateClientListStacking(wwin->screen_ptr, NULL); updateStateHint(wwin, False, False); } else if (strcmp(name, WMNChangedStacking) == 0 && wwin) { updateClientListStacking(wwin->screen_ptr, NULL); updateStateHint(wwin, False, False); - } else if (strcmp(name, WMNChangedFocus) == 0) { + } else if (strcmp(name, WMNChangedFocus) == 0 && wwin) { updateFocusHint(ndata->scr); + updateStateHint(wwin, False, False); } else if (strcmp(name, WMNChangedWorkspace) == 0 && wwin) { updateWorkspaceHint(wwin, False, False); updateStateHint(wwin, True, False); } else if (strcmp(name, WMNChangedState) == 0 && wwin) { updateStateHint(wwin, !strcmp(data, "omnipresent"), False); } } static void wsobserver(void *self, WMNotification *notif) { WScreen *scr = (WScreen *) WMGetNotificationObject(notif); const char *name = WMGetNotificationName(notif); /* Parameter not used, but tell the compiler that it is ok */ (void) self; if (strcmp(name, WMNWorkspaceCreated) == 0) { updateWorkspaceCount(scr); updateWorkspaceNames(scr); wNETWMUpdateWorkarea(scr); } else if (strcmp(name, WMNWorkspaceDestroyed) == 0) { updateWorkspaceCount(scr); updateWorkspaceNames(scr); wNETWMUpdateWorkarea(scr); } else if (strcmp(name, WMNWorkspaceChanged) == 0) { updateCurrentWorkspace(scr); } else if (strcmp(name, WMNWorkspaceNameChanged) == 0) { updateWorkspaceNames(scr); } } void wNETFrameExtents(WWindow *wwin) { long extents[4] = { 0, 0, 0, 0 }; /* The extents array describes dimensions which are not * part of the client window. In our case that means * widths of the border and heights of the titlebar and resizebar. * * Index 0 = left * 1 = right * 2 = top * 3 = bottom */ if (wwin->frame->titlebar) extents[2] = wwin->frame->titlebar->height; if (wwin->frame->resizebar) extents[3] = wwin->frame->resizebar->height; if (HAS_BORDER(wwin)) { extents[0] += wwin->screen_ptr->frame_border_width; extents[1] += wwin->screen_ptr->frame_border_width; extents[2] += wwin->screen_ptr->frame_border_width; extents[3] += wwin->screen_ptr->frame_border_width; } XChangeProperty(dpy, wwin->client_win, net_frame_extents, XA_CARDINAL, 32, PropModeReplace, (unsigned char *) extents, 4); } void wNETCleanupFrameExtents(WWindow *wwin) { XDeleteProperty(dpy, wwin->client_win, net_frame_extents); }
roblillack/wmaker
a98680cd149606210f776eb68d02cecfc69e61e2
Patch for GetCommandForPid() in osdep_darwin.c
diff --git a/src/osdep_darwin.c b/src/osdep_darwin.c index b3a7b4f..0191749 100644 --- a/src/osdep_darwin.c +++ b/src/osdep_darwin.c @@ -1,97 +1,121 @@ - #include <sys/types.h> #include <sys/sysctl.h> #include <assert.h> #include <stdlib.h> #include <string.h> #include <WINGs/WUtil.h> #include "wconfig.h" #include "osdep.h" /* * copy argc and argv for an existing process identified by `pid' * into suitable storage given in ***argv and *argc. * * subsequent calls use the same static area for argv and argc. * * returns 0 for failure, in which case argc := 0 and argv := NULL * returns 1 for success */ Bool GetCommandForPid(int pid, char ***argv, int *argc) #ifdef KERN_PROCARGS2 { - int j, mib[4]; - unsigned int i, idx; + int mib[4]; + unsigned int idx; size_t count; static char *args = NULL; static int argmax = 0; *argv = NULL; *argc = 0; /* the system-wide limit */ if (argmax == 0) { /* it hopefully doesn't change at runtime *g* */ mib[0] = CTL_KERN; mib[1] = KERN_ARGMAX; mib[2] = 0; mib[3] = 0; count = sizeof(argmax); if (sysctl(mib, 2, &argmax, &count, NULL, 0) == -1) return False; } /* if argmax is still 0, something went very seriously wrong */ assert(argmax > 0); /* space for args; no need to free before returning even on errors */ if (args == NULL) args = (char *)wmalloc(argmax); /* get process args */ mib[0] = CTL_KERN; mib[1] = KERN_PROCARGS2; mib[2] = pid; count = argmax; if (sysctl(mib, 3, args, &count, NULL, 0) == -1 || count == 0) return False; /* get argc, skip */ memcpy(argc, args, sizeof(*argc)); idx = sizeof(*argc); while (args[idx++] != '\0') /* skip execname */ ; while (args[idx] == '\0') /* padding too */ idx++; /* args[idx] is at at begininng of args now */ - *argv = (char **)wmalloc(sizeof(char *) * (*argc + 1 /* term. null ptr */)); - (*argv)[0] = args + idx; - - /* go through args, set argv[$next] to the beginning of each string */ - for (i = 0, j = 1; i < count - idx /* do not overrun */; i++) { - if (args[idx + i] != '\0') - continue; - if (args[idx + i] == '\0') - (*argv)[j++] = &args[idx + i + 1]; - if (j == *argc) - break; - } - - /* the list of arguments must be terminated by a null pointer */ - (*argv)[j] = NULL; + int found = 0; + char *p = &args[idx]; + while(found < *argc) + { + while(*p != '\0') p++; // look for the next \0 + while(*p == '\0') p++; // skip over padding \0s + found++; + + // Don’t overrun! + if (p-args >= argmax) + { + return False; + } + } + // At this point, p points to the last \0 in the source array. + + // Buffer needed for the strings + unsigned stringbuf_size = p - &args[idx]; + + // Buffer needed for the pointers (plus one terminating NULL) + unsigned pointerbuf_size = sizeof(char *) * (*argc + 1); + + *argv = wmalloc(pointerbuf_size + stringbuf_size); + char* stringstart = (char *)(*argv) + pointerbuf_size; + + memcpy(stringstart, &args[idx], stringbuf_size); + + found = 0; + p = stringstart; + while(found < *argc) + { + (*argv)[found] = p; + + while(*p != '\0') p++; // look for the next \0 + while(*p == '\0') p++; // skip over padding \0s + + found++; + } + (*argv)[found] = NULL; // Terminating NULL + return True; } #else /* !KERN_PROCARGS2 */ { *argv = NULL; *argc = 0; return False; } #endif
roblillack/wmaker
7d423a3a0ff5e0c70bac83585b593b910f627d15
Added Expert option: "Close rootmenu when mouse (left or right) is clicked outside focus.
diff --git a/WPrefs.app/Expert.c b/WPrefs.app/Expert.c index b1a8e9b..157bc39 100644 --- a/WPrefs.app/Expert.c +++ b/WPrefs.app/Expert.c @@ -1,341 +1,344 @@ /* Expert.c- expert user options * * WPrefs - Window Maker Preferences Program * * Copyright (c) 2014 Window Maker Team * Copyright (c) 1998-2003 Alfredo K. Kojima * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "WPrefs.h" /* This structure containts the list of all the check-buttons to display in the * expert tab of the window with the corresponding information for effect */ static const struct { const char *label; /* Text displayed to user */ int def_state; /* True/False: the default value, if not defined in current config */ enum { OPTION_WMAKER, OPTION_WMAKER_ARRAY, OPTION_USERDEF, OPTION_WMAKER_INT } class; const char *op_name; /* The identifier for the option in the config file */ } expert_options[] = { { N_("Disable miniwindows (icons for minimized windows). For use with KDE/GNOME."), /* default: */ False, OPTION_WMAKER, "DisableMiniwindows" }, { N_("Ignore decoration hints for GTK applications."), /* default: */ False, OPTION_WMAKER, "IgnoreGtkHints" }, { N_("Enable workspace pager."), /* default: */ False, OPTION_WMAKER, "EnableWorkspacePager" }, { N_("Do not set non-WindowMaker specific parameters (do not use xset)."), /* default: */ False, OPTION_USERDEF, "NoXSetStuff" }, { N_("Automatically save session when exiting Window Maker."), /* default: */ False, OPTION_WMAKER, "SaveSessionOnExit" }, { N_("Use SaveUnder in window frames, icons, menus and other objects."), /* default: */ False, OPTION_WMAKER, "UseSaveUnders" }, { N_("Disable confirmation panel for the Kill command."), /* default: */ False, OPTION_WMAKER, "DontConfirmKill" }, { N_("Disable selection animation for selected icons."), /* default: */ False, OPTION_WMAKER, "DisableBlinking" }, { N_("Smooth font edges (needs restart)."), /* default: */ True, OPTION_WMAKER, "AntialiasedText" }, { N_("Cycle windows only on the active head."), /* default: */ False, OPTION_WMAKER, "CycleActiveHeadOnly" }, { N_("Ignore minimized windows when cycling."), /* default: */ False, OPTION_WMAKER, "CycleIgnoreMinimized" }, { N_("Show switch panel when cycling windows."), /* default: */ True, OPTION_WMAKER_ARRAY, "SwitchPanelImages" }, { N_("Show workspace title on Clip."), /* default: */ True, OPTION_WMAKER, "ShowClipTitle" }, { N_("Highlight the icon of the application when it has the focus."), /* default: */ True, OPTION_WMAKER, "HighlightActiveApp" }, #ifdef XKB_MODELOCK { N_("Enable keyboard language switch button in window titlebars."), /* default: */ False, OPTION_WMAKER, "KbdModeLock" }, #endif /* XKB_MODELOCK */ { N_("Maximize (snap) a window to edge or corner by dragging."), /* default: */ False, OPTION_WMAKER, "WindowSnapping" }, { N_("Distance from edge to begin window snap."), /* default: */ 1, OPTION_WMAKER_INT, "SnapEdgeDetect" }, { N_("Distance from corner to begin window snap."), /* default: */ 10, OPTION_WMAKER_INT, "SnapCornerDetect" }, { N_("Snapping a window to the top maximizes it to the full screen."), /* default: */ False, OPTION_WMAKER, "SnapToTopMaximizesFullscreen" }, { N_("Allow move half-maximized windows between multiple screens."), /* default: */ False, OPTION_WMAKER, "MoveHalfMaximizedWindowsBetweenScreens" }, { N_("Alternative transitions between states for half maximized windows."), /* default: */ False, OPTION_WMAKER, "AlternativeHalfMaximized" }, { N_("Move mouse pointer with half maximized windows."), /* default: */ False, OPTION_WMAKER, "PointerWithHalfMaxWindows" }, { N_("Open dialogs in the same workspace as their owners."), /* default: */ False, OPTION_WMAKER, "OpenTransientOnOwnerWorkspace" }, { N_("Wrap dock-attached icons around the screen edges."), /* default: */ True, OPTION_WMAKER, "WrapAppiconsInDock" }, { N_("Double click on titlebar maximize a window to full screen."), - /* default: */ False, OPTION_WMAKER, "DbClickFullScreen" } + /* default: */ False, OPTION_WMAKER, "DbClickFullScreen" }, + + { N_("Close rootmenu when mouse (left or right) is clicked outside focus."), + /* default: */ False, OPTION_WMAKER, "CloseRootMenuByLeftOrRightMouseClick" } }; typedef struct _Panel { WMBox *box; char *sectionName; char *description; CallbackRec callbacks; WMWidget *parent; WMButton *swi[wlengthof_nocheck(expert_options)]; WMTextField *textfield[wlengthof_nocheck(expert_options)]; } _Panel; #define ICON_FILE "expert" static void changeIntTextfield(void *data, int delta) { WMTextField *textfield; char *text; int value; textfield = (WMTextField *)data; text = WMGetTextFieldText(textfield); value = atoi(text); value += delta; sprintf(text, "%d", value); WMSetTextFieldText(textfield, text); } static void downButtonCallback(WMWidget *self, void *data) { (void) self; changeIntTextfield(data, -1); } static void upButtonCallback(WMWidget *self, void *data) { (void) self; changeIntTextfield(data, 1); } static void createPanel(Panel *p) { _Panel *panel = (_Panel *) p; WMScrollView *sv; WMFrame *f; WMUserDefaults *udb; int i, state; panel->box = WMCreateBox(panel->parent); WMSetViewExpandsToParent(WMWidgetView(panel->box), 2, 2, 2, 2); sv = WMCreateScrollView(panel->box); WMResizeWidget(sv, 500, 215); WMMoveWidget(sv, 12, 10); WMSetScrollViewRelief(sv, WRSunken); WMSetScrollViewHasVerticalScroller(sv, True); WMSetScrollViewHasHorizontalScroller(sv, False); f = WMCreateFrame(panel->box); WMResizeWidget(f, 495, wlengthof(expert_options) * 25 + 8); WMSetFrameRelief(f, WRFlat); udb = WMGetStandardUserDefaults(); for (i = 0; i < wlengthof(expert_options); i++) { if (expert_options[i].class != OPTION_WMAKER_INT) { panel->swi[i] = WMCreateSwitchButton(f); WMResizeWidget(panel->swi[i], FRAME_WIDTH - 40, 25); WMMoveWidget(panel->swi[i], 5, 5 + i * 25); WMSetButtonText(panel->swi[i], _(expert_options[i].label)); } switch (expert_options[i].class) { case OPTION_WMAKER: if (GetStringForKey(expert_options[i].op_name)) state = GetBoolForKey(expert_options[i].op_name); else state = expert_options[i].def_state; break; case OPTION_WMAKER_ARRAY: { char *str = GetStringForKey(expert_options[i].op_name); state = expert_options[i].def_state; if (str && strcasecmp(str, "None") == 0) state = False; } break; case OPTION_USERDEF: state = WMGetUDBoolForKey(udb, expert_options[i].op_name); break; case OPTION_WMAKER_INT: { char tmp[10]; WMButton *up, *down; WMLabel *label; panel->textfield[i] = WMCreateTextField(f); WMResizeWidget(panel->textfield[i], 41, 20); WMMoveWidget(panel->textfield[i], 22, 7 + i * 25); down = WMCreateCommandButton(f); WMSetButtonImage(down, WMGetSystemPixmap(WMWidgetScreen(down), WSIArrowDown)); WMSetButtonAltImage(down, WMGetSystemPixmap(WMWidgetScreen(down), WSIHighlightedArrowDown)); WMSetButtonImagePosition(down, WIPImageOnly); WMSetButtonAction(down, downButtonCallback, panel->textfield[i]); WMResizeWidget(down, 16, 16); WMMoveWidget(down, 5, 9 + i * 25); up = WMCreateCommandButton(f); WMSetButtonImage(up, WMGetSystemPixmap(WMWidgetScreen(up), WSIArrowUp)); WMSetButtonAltImage(up, WMGetSystemPixmap(WMWidgetScreen(up), WSIHighlightedArrowUp)); WMSetButtonImagePosition(up, WIPImageOnly); WMSetButtonAction(up, upButtonCallback, panel->textfield[i]); WMResizeWidget(up, 16, 16); WMMoveWidget(up, 64, 9 + i * 25); label = WMCreateLabel(f); WMSetLabelText(label, _(expert_options[i].label)); WMResizeWidget(label, FRAME_WIDTH - 99, 25); WMMoveWidget(label, 85, 5 + i * 25); if (GetStringForKey(expert_options[i].op_name)) state = GetIntegerForKey(expert_options[i].op_name); else state = expert_options[i].def_state; sprintf(tmp, "%d", state); WMSetTextFieldText(panel->textfield[i], tmp); break; } default: #ifdef DEBUG wwarning("export_options[%d].class = %d, this should not happen\n", i, expert_options[i].class); #endif state = expert_options[i].def_state; break; } if (expert_options[i].class != OPTION_WMAKER_INT) WMSetButtonSelected(panel->swi[i], state); } WMMapSubwidgets(panel->box); WMSetScrollViewContentView(sv, WMWidgetView(f)); WMRealizeWidget(panel->box); } static void storeDefaults(_Panel *panel) { WMUserDefaults *udb = WMGetStandardUserDefaults(); int i; for (i = 0; i < wlengthof(expert_options); i++) { switch (expert_options[i].class) { case OPTION_WMAKER: SetBoolForKey(WMGetButtonSelected(panel->swi[i]), expert_options[i].op_name); break; case OPTION_WMAKER_ARRAY: if (WMGetButtonSelected(panel->swi[i])) { /* check if the array was not manually modified */ char *str = GetStringForKey(expert_options[i].op_name); if (str && strcasecmp(str, "None") == 0) RemoveObjectForKey(expert_options[i].op_name); } else SetStringForKey("None", expert_options[i].op_name); break; case OPTION_USERDEF: WMSetUDBoolForKey(udb, WMGetButtonSelected(panel->swi[i]), expert_options[i].op_name); break; case OPTION_WMAKER_INT: { char *text; int value; text = WMGetTextFieldText(panel->textfield[i]); value = atoi(text); SetIntegerForKey(value, expert_options[i].op_name); break; } } } } Panel *InitExpert(WMWidget *parent) { _Panel *panel; panel = wmalloc(sizeof(_Panel)); panel->sectionName = _("Expert User Preferences"); panel->description = _("Options for people who know what they're doing...\n" "Also has some other misc. options."); panel->parent = parent; panel->callbacks.createWidgets = createPanel; panel->callbacks.updateDomain = storeDefaults; AddSection(panel, ICON_FILE); return panel; } diff --git a/WPrefs.app/po/ru.po b/WPrefs.app/po/ru.po index c5dbd06..7515628 100644 --- a/WPrefs.app/po/ru.po +++ b/WPrefs.app/po/ru.po @@ -1,951 +1,954 @@ # Igor P. Roboul <[email protected]> # Andrew W. Nosenko <[email protected]> # # Краткий словарь: # options параметры # preferences ??? (не устоялось) # settings установки msgid "" msgstr "" "Project-Id-Version: WPrefs.app 0.45\n" "POT-Creation-Date: 2002-09-12 16:18+0300\n" "PO-Revision-Date: 2002-09-12 17:45+0300\n" "Last-Translator: [email protected]\n" "Language-Team: Russian\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" #: ../../WPrefs.app/Appearance.c:1131 msgid "Select File" msgstr "Укажите файл" #: ../../WPrefs.app/Appearance.c:1533 msgid "Focused Window" msgstr "Активное окно" #: ../../WPrefs.app/Appearance.c:1537 msgid "Unfocused Window" msgstr "Неактивное окно" #: ../../WPrefs.app/Appearance.c:1541 msgid "Owner of Focused Window" msgstr "Владелец активного окна" # awn: если перевести, то не помещается в картинку #: ../../WPrefs.app/Appearance.c:1545 ../../WPrefs.app/Appearance.c:1862 msgid "Menu Title" msgstr "" #: ../../WPrefs.app/Appearance.c:1549 ../../WPrefs.app/Appearance.c:1551 msgid "Normal Item" msgstr "Нормальный" #: ../../WPrefs.app/Appearance.c:1555 msgid "Disabled Item" msgstr "Запрещенный" #: ../../WPrefs.app/Appearance.c:1564 msgid "Highlighted" msgstr "Подсвеченный" #: ../../WPrefs.app/Appearance.c:1755 msgid "Texture" msgstr "Текстура" #: ../../WPrefs.app/Appearance.c:1763 msgid "Titlebar of Focused Window" msgstr "Заголовок активного окна" #: ../../WPrefs.app/Appearance.c:1764 msgid "Titlebar of Unfocused Windows" msgstr "Заголовок неактивных окон" #: ../../WPrefs.app/Appearance.c:1765 msgid "Titlebar of Focused Window's Owner" msgstr "Заголовок владельца активного окна" #: ../../WPrefs.app/Appearance.c:1766 msgid "Window Resizebar" msgstr "Рамка изменения размера окна" #: ../../WPrefs.app/Appearance.c:1767 msgid "Titlebar of Menus" msgstr "Заголовок меню" #: ../../WPrefs.app/Appearance.c:1768 msgid "Menu Items" msgstr "Элементы меню" #: ../../WPrefs.app/Appearance.c:1769 msgid "Icon Background" msgstr "Фон иконки" #: ../../WPrefs.app/Appearance.c:1784 msgid "" "Double click in the texture you want to use\n" "for the selected item." msgstr "" "Щелкните дважды на текстуре, которую вы хотите\n" "использовать для выбранного элемента." #: ../../WPrefs.app/Appearance.c:1798 msgid "New" msgstr "Новый" #: ../../WPrefs.app/Appearance.c:1802 msgid "Create a new texture." msgstr "Создать новую текстуру." #: ../../WPrefs.app/Appearance.c:1810 msgid "Extract..." msgstr "Извлечь..." #: ../../WPrefs.app/Appearance.c:1814 msgid "Extract texture(s) from a theme or a style file." msgstr "Извлечь текстуру (текстуры) из темы или файла стиля." #: ../../WPrefs.app/Appearance.c:1824 msgid "Edit" msgstr "Редактировать" #: ../../WPrefs.app/Appearance.c:1827 msgid "Edit the highlighted texture." msgstr "Редактировать выбранную текстуру." #: ../../WPrefs.app/Appearance.c:1835 ../../WPrefs.app/TexturePanel.c:1316 msgid "Delete" msgstr "Стереть" #: ../../WPrefs.app/Appearance.c:1839 msgid "Delete the highlighted texture." msgstr "Удалить выбранную текстуру." #: ../../WPrefs.app/Appearance.c:1852 msgid "Color" msgstr "Цвет" #: ../../WPrefs.app/Appearance.c:1859 msgid "Focused Window Title" msgstr "Заголовок активного окна" #: ../../WPrefs.app/Appearance.c:1860 msgid "Unfocused Window Title" msgstr "Заголовок неактивного окна" #: ../../WPrefs.app/Appearance.c:1861 msgid "Owner of Focused Window Title" msgstr "Владелец активного окна" #: ../../WPrefs.app/Appearance.c:1863 msgid "Menu Item Text" msgstr "Текст элемента меню" #: ../../WPrefs.app/Appearance.c:1864 msgid "Disabled Menu Item Text" msgstr "Текст запрещенного элемента меню" #: ../../WPrefs.app/Appearance.c:1865 msgid "Menu Highlight Color" msgstr "Фон подсвеченного элемента меню" #: ../../WPrefs.app/Appearance.c:1866 msgid "Highlighted Menu Text Color" msgstr "Текст подсвеченного элемента меню" #: ../../WPrefs.app/Appearance.c:1905 msgid "Background" msgstr "Фон" #: ../../WPrefs.app/Appearance.c:1917 ../../WPrefs.app/TexturePanel.c:1503 msgid "Browse..." msgstr "Выбрать" #: ../../WPrefs.app/Appearance.c:1930 msgid "Options" msgstr "Параметры" #: ../../WPrefs.app/Appearance.c:1937 msgid "Menu Style" msgstr "Стиль меню" #: ../../WPrefs.app/Appearance.c:1965 ../../WPrefs.app/Configurations.c:242 #: ../../WPrefs.app/Configurations.c:254 ../../WPrefs.app/Focus.c:288 #: ../../WPrefs.app/Focus.c:299 ../../WPrefs.app/MenuPreferences.c:134 #: ../../WPrefs.app/MenuPreferences.c:145 #: ../../WPrefs.app/MenuPreferences.c:173 #: ../../WPrefs.app/MenuPreferences.c:188 ../../WPrefs.app/MouseSettings.c:560 #: ../../WPrefs.app/MouseSettings.c:571 ../../WPrefs.app/WPrefs.c:558 #: ../../WPrefs.app/WPrefs.c:583 #, c-format msgid "could not load icon file %s" msgstr "не могу загрузить иконку %s" # awn: правильно -- "Выравнивание заголовка", но места нет. #: ../../WPrefs.app/Appearance.c:1979 msgid "Title Alignment" msgstr "Заголовок" #: ../../WPrefs.app/Appearance.c:1986 msgid "Left" msgstr "Влево" #: ../../WPrefs.app/Appearance.c:1989 ../../WPrefs.app/TexturePanel.c:1517 #: ../../WPrefs.app/Workspace.c:270 msgid "Center" msgstr "По центру" #: ../../WPrefs.app/Appearance.c:1992 msgid "Right" msgstr "Вправо" #: ../../WPrefs.app/Appearance.c:2216 msgid "Appearance Preferences" msgstr "Внешний вид" #: ../../WPrefs.app/Appearance.c:2218 msgid "" "Background texture configuration for windows,\n" "menus and icons." msgstr "" "Конфигурация фоновых текстур для окон,\n" "меню и иконок." #: ../../WPrefs.app/Appearance.c:2263 msgid "Extract Texture" msgstr "Извлечь текстуру" #: ../../WPrefs.app/Appearance.c:2283 msgid "Textures" msgstr "Текстуры" #: ../../WPrefs.app/Appearance.c:2294 ../../WPrefs.app/WPrefs.c:302 msgid "Close" msgstr "Закрыть" #: ../../WPrefs.app/Appearance.c:2299 msgid "Extract" msgstr "Извлечь" #: ../../WPrefs.app/Configurations.c:150 ../../WPrefs.app/Configurations.c:156 #: ../../WPrefs.app/MouseSettings.c:490 ../../WPrefs.app/WindowHandling.c:339 #: ../../WPrefs.app/WindowHandling.c:351 ../../WPrefs.app/Workspace.c:90 #: ../../WPrefs.app/Workspace.c:101 #, c-format msgid "could not load icon %s" msgstr "не могу загрузить иконку %s" #: ../../WPrefs.app/Configurations.c:164 ../../WPrefs.app/Workspace.c:109 #, c-format msgid "could not process icon %s: %s" msgstr "не могу обработать иконку %s: %s" #: ../../WPrefs.app/Configurations.c:189 ../../WPrefs.app/Workspace.c:164 #, c-format msgid "could not load image file %s" msgstr "не могу загрузить файл изображения %s" #: ../../WPrefs.app/Configurations.c:203 msgid "Icon Slide Speed" msgstr "Скорость сдвига иконки" #: ../../WPrefs.app/Configurations.c:209 msgid "Shade Animation Speed" msgstr "Скорость сворачивания" # awn: как это нормально перевести, да так, чтобы поместилось? #: ../../WPrefs.app/Configurations.c:271 msgid "Smooth Scaling" msgstr "Гладкое масштабирование" #: ../../WPrefs.app/Configurations.c:272 msgid "" "Smooth scaled background images, neutralizing\n" "the `pixelization' effect. This will slow\n" "down loading of background images considerably." msgstr "" "Сглаживать (нажато) или нет (отпущено) масштабированные\n" "фоновые изображения. С одной стороны, это делает\n" "изображение более \"гладкими\", скрывая отдельные,\n" "увеличившиеся в размерах точки, но с другой стороны,\n" "увеличивает время, необходимое для загрузки фонового\n" "изображения." #: ../../WPrefs.app/Configurations.c:313 msgid "Titlebar Style" msgstr "Стиль заголовка" #: ../../WPrefs.app/Configurations.c:351 msgid "Animations and Sound" msgstr "Анимация и звук" #: ../../WPrefs.app/Configurations.c:357 msgid "Animations" msgstr "Анимация" #: ../../WPrefs.app/Configurations.c:368 msgid "" "Disable/enable animations such as those shown\n" "for window miniaturization, shading etc." msgstr "" "Запрещает/разрешает анимацию при сворачивании\n" "окон в иконку, линейку и т.п." #: ../../WPrefs.app/Configurations.c:376 msgid "Superfluous" msgstr "Излишества" #: ../../WPrefs.app/Configurations.c:387 msgid "" "Disable/enable `superfluous' features and\n" "animations. These include the `ghosting' of the\n" "dock when it's being moved to another side and\n" "the explosion animation when undocking icons." msgstr "" "Запрещает/разрешает различные `излишества'.\n" "Например, анимированный `взрыв' иконки при\n" "удалении ее из Дока." #: ../../WPrefs.app/Configurations.c:397 msgid "Sounds" msgstr "Звуки" #: ../../WPrefs.app/Configurations.c:408 msgid "" "Disable/enable support for sound effects played\n" "for actions like shading and closing a window.\n" "You will need a module distributed separately\n" "for this. You can get it at:\n" "http://shadowmere.student.utwente.nl/" msgstr "" "Запретить/разрешить звуковые эффекты для действий,\n" "наподобие свертки или закрытия окна. Для этого\n" "вам понадобится модуль, поставляемый отдельно.\n" "Вы можете загрузить его с:\n" "http://shadowmere.student.utwente.nl/" #: ../../WPrefs.app/Configurations.c:419 msgid "" "Note: sound requires a module distributed\n" "separately" msgstr "" "Замечание: для звука требуется отдельно\n" "поставляемый модуль" #: ../../WPrefs.app/Configurations.c:429 msgid "Dithering colormap for 8bpp" msgstr "Приведение палитры для 8bpp" #: ../../WPrefs.app/Configurations.c:431 msgid "" "Number of colors to reserve for Window Maker\n" "on displays that support only 8bpp (PseudoColor)." msgstr "" "Количество цветов, которое будет зарезервировано\n" "за Window Maker'ом в режиме 8bpp (PseudoColor)." #: ../../WPrefs.app/Configurations.c:438 msgid "Disable dithering in any visual/depth" msgstr "Запретить приведение палитры вообще" #: ../../WPrefs.app/Configurations.c:459 msgid "" "More colors for\n" "applications" msgstr "" "Больше цветов\n" "для\n" "приложений" #: ../../WPrefs.app/Configurations.c:466 msgid "" "More colors for\n" "Window Maker" msgstr "" "Больше цветов\n" "для\n" "Window Maker'а" #: ../../WPrefs.app/Configurations.c:521 msgid "Other Configurations" msgstr "Другие настройки" #: ../../WPrefs.app/Configurations.c:523 msgid "" "Animation speeds, titlebar styles, various option\n" "toggling and number of colors to reserve for\n" "Window Maker on 8bit displays." msgstr "" "Скорость анимации, стили заголовков, переключение различных\n" "параметров и количества цветов для резервирования за\n" "Window Maker'ом при работе с 8bit'ным цветом (8bpp)." #: ../../WPrefs.app/Expert.c:44 msgid "Disable miniwindows (icons for minimized windows). For use with KDE/GNOME." msgstr "Запретить миниокна иконки для минимизированных окон. Для использования с KDE/GNOME." #: ../../WPrefs.app/Expert.c:47 msgid "Ignore decoration hints for GTK applications." msgstr "Игнорировать декорацию окон для GTK приложений." #: ../../WPrefs.app/Expert.c:53 msgid "Do not set non-WindowMaker specific parameters (do not use xset)." msgstr "" "Не устанавливать параметры, не относящиеся непосредственно к\n" "Window Maker'у (не использовать xset)." #: ../../WPrefs.app/Expert.c:56 msgid "Automatically save session when exiting Window Maker." msgstr "Автоматически сохранять сессию при выходе из Window Maker'а." #: ../../WPrefs.app/Expert.c:59 msgid "Use SaveUnder in window frames, icons, menus and other objects." msgstr "Использовать SaveUnder для окон, иконок, меню и других объектов." #: ../../WPrefs.app/Expert.c:62 msgid "Disable confirmation panel for the Kill command." msgstr "Запретить диалог подтверждения для команды `Убить'." msgid "Disable selection animation for selected icons." msgstr "Запретить анимацию выбора для выбранных иконок." msgid "Show switch panel when cycling windows." msgstr "Показывать панель переключения окон." #: ../../WPrefs.app/Expert.c:68 msgid "Smooth font edges (needs restart)." msgstr "Cглаживание шрифтов (требуется перезагрузка)." #: ../../WPrefs.app/Expert.c:80 msgid "Show workspace title on Clip." msgstr "Показывать имя рабочего места на скрепке." #: ../../WPrefs.app/Expert.c:83 msgid "Highlight the icon of the application when it has the focus." msgstr "Подсвечивание иконок при нажатии (в фокусе)." #: ../../WPrefs.app/Expert.c:91 msgid "Maximize (snap) a window to edge or corner by dragging." msgstr "Прилипания окон по краям и углам." #: ../../WPrefs.app/Expert.c:100 msgid "Snapping a window to the top maximizes it to the full screen." msgstr "Распахнуть окно при перетаскивании к верхнему краю." - #: ../../WPrefs.app/Expert.c:118 msgid "Double click on titlebar maximize a window to full screen." msgstr "Распахнуть окно двойным щелчком." +#: ../../WPrefs.app/Expert.c:121 +msgid "Close rootmenu when mouse (left or right) is clicked outside focus." +msgstr "Закрывать меню приложений правым или левым щелчком мыши вне фокуса." + #: ../../WPrefs.app/Expert.c:328 msgid "Expert User Preferences" msgstr "Установки для опытного пользователя" #: ../../WPrefs.app/Expert.c:330 msgid "" "Options for people who know what they're doing...\n" "Also have some other misc. options." msgstr "" "Параметры, предназначенные для людей,\n" "которые знают, что делают...\n" "Также содержит некоторые другие,\n" "редко используемые параметры." #: ../../WPrefs.app/Focus.c:80 #, c-format msgid "bad option value %s for option FocusMode. Using default Manual" msgstr "неверное значение %s для FocusMode. Используем Manual" #: ../../WPrefs.app/Focus.c:94 #, c-format msgid "bad option value %s for option ColormapMode. Using default Auto" msgstr "неверное значение %s для ColormapMode. Используем Auto" #: ../../WPrefs.app/Focus.c:214 msgid "Input Focus Mode" msgstr "Режим фокуса ввода" #: ../../WPrefs.app/Focus.c:222 msgid "Manual: Click on the window to set keyboard input focus" msgstr "Вручную: Щелкните на окне, для передачи ему фокуса ввода" #: ../../WPrefs.app/Focus.c:229 msgid "Auto: Set keyboard input focus to the window under the mouse pointer" msgstr "Автоматически: Фокус клавиатурного ввода передается окну, находящемуся под курсором мыши" #: ../../WPrefs.app/Focus.c:243 msgid "Install colormap from the window..." msgstr "Устанавливать палитру окна..." #: ../../WPrefs.app/Focus.c:248 msgid "...that has the input focus" msgstr "...имеющего фокус ввода" #: ../../WPrefs.app/Focus.c:253 msgid "...that's under the mouse pointer" msgstr "...находящегося под курсором мыши" #: ../../WPrefs.app/Focus.c:262 msgid "Automatic Window Raise Delay" msgstr "Всплывать через..." #: ../../WPrefs.app/Focus.c:319 ../../WPrefs.app/MouseSettings.c:601 msgid "ms" msgstr "Мсек" #: ../../WPrefs.app/Focus.c:336 msgid "Do not let applications receive the click used to focus windows" msgstr "Не передавать приложениям щелчок мыши,сделанный для фокусировки" #: ../../WPrefs.app/Focus.c:342 msgid "Automatically focus new windows" msgstr "Автоматически передавать фокус новым окнам" #: ../../WPrefs.app/Focus.c:363 msgid "Window Focus Preferences" msgstr "Параметры для фокусировки окна" #: ../../WPrefs.app/Focus.c:365 msgid "" "Keyboard focus switching policy, colormap switching\n" "policy for 8bpp displays and other related options." msgstr "" "Политика переключения фокуса клавиатуры,\n" "политика переключения цветовой палитры для 8bpp\n" "и тому подобные параметры." #: ../../WPrefs.app/Font.c:276 msgid "Could not locate font information file WPrefs.app/font.data" msgstr "" #: ../../WPrefs.app/Font.c:282 msgid "Could not read font information file WPrefs.app/font.data" msgstr "" #: ../../WPrefs.app/Font.c:293 msgid "" "Invalid data in font information file WPrefs.app/font.data.\n" "Encodings data not found." msgstr "" #: ../../WPrefs.app/Font.c:298 msgid "- Custom -" msgstr "" #: ../../WPrefs.app/Font.c:329 ../../WPrefs.app/Menu.c:1594 #: ../../WPrefs.app/MouseSettings.c:140 ../../WPrefs.app/MouseSettings.c:160 #: ../../WPrefs.app/TexturePanel.c:613 ../../WPrefs.app/TexturePanel.c:693 #: ../../WPrefs.app/Themes.c:96 ../../WPrefs.app/WPrefs.c:758 #: ../../WPrefs.app/WPrefs.c:763 ../../WPrefs.app/WPrefs.c:780 #: ../../WPrefs.app/WPrefs.c:790 ../../WPrefs.app/WPrefs.c:800 #: ../../WPrefs.app/WPrefs.c:838 ../../WPrefs.app/WPrefs.c:843 msgid "Error" msgstr "Ошибка" #: ../../WPrefs.app/Font.c:329 ../../WPrefs.app/Menu.c:1594 #: ../../WPrefs.app/MouseSettings.c:142 ../../WPrefs.app/MouseSettings.c:162 #: ../../WPrefs.app/TexturePanel.c:614 ../../WPrefs.app/TexturePanel.c:695 #: ../../WPrefs.app/TexturePanel.c:1528 ../../WPrefs.app/Themes.c:98 #: ../../WPrefs.app/WPrefs.c:758 ../../WPrefs.app/WPrefs.c:763 #: ../../WPrefs.app/WPrefs.c:782 ../../WPrefs.app/WPrefs.c:794 #: ../../WPrefs.app/WPrefs.c:800 ../../WPrefs.app/WPrefs.c:807 #: ../../WPrefs.app/WPrefs.c:838 ../../WPrefs.app/WPrefs.c:843 #: ../../WPrefs.app/imagebrowser.c:105 msgid "OK" msgstr "OK" #: ../../WPrefs.app/Font.c:376 msgid "Default Font Sets" msgstr "" #: ../../WPrefs.app/Font.c:389 msgid "Font Set" msgstr "" #: ../../WPrefs.app/Font.c:418 msgid "Add..." msgstr "Добавить..." #: ../../WPrefs.app/Font.c:423 ../../WPrefs.app/Font.c:438 msgid "Change..." msgstr "Изменить..." #: ../../WPrefs.app/Font.c:428 ../../WPrefs.app/Paths.c:288 #: ../../WPrefs.app/Paths.c:319 msgid "Remove" msgstr "Удалить" #: ../../WPrefs.app/Font.c:477 msgid "Font Preferences" msgstr "Установки для шрифтов" #: ../../WPrefs.app/Font.c:478 msgid "Font Configurations for Windows, Menus etc" msgstr "Конфигурация Шрифтов для Окон, Меню и т.п." #: ../../WPrefs.app/Icons.c:180 msgid "Icon Positioning" msgstr "Расположение иконок" #: ../../WPrefs.app/Icons.c:227 msgid "Iconification Animation" msgstr "Анимирование сворачивания" #: ../../WPrefs.app/Icons.c:238 msgid "Shrinking/Zooming" msgstr "Сжатие/Распахивание" #: ../../WPrefs.app/Icons.c:239 msgid "Spinning/Twisting" msgstr "Вращение в плоскости" #: ../../WPrefs.app/Icons.c:240 msgid "3D-flipping" msgstr "Трехмерное вращение" #: ../../WPrefs.app/Icons.c:241 ../../WPrefs.app/MouseSettings.c:838 #: ../../WPrefs.app/MouseSettings.c:843 msgid "None" msgstr "Без оного" #: ../../WPrefs.app/Icons.c:254 msgid "Auto-arrange icons" msgstr "Автоматически выравнивать иконки" #: ../../WPrefs.app/Icons.c:256 msgid "Keep icons and miniwindows arranged all the time." msgstr "Поддерживать иконки и миниокна постоянно выровненными." #: ../../WPrefs.app/Icons.c:262 msgid "Omnipresent miniwindows" msgstr "Миниокна присутствуют везде" #: ../../WPrefs.app/Icons.c:264 msgid "Make miniwindows be present in all workspaces." msgstr "" "Сделать миниокна присутствующими сразу на всех\n" "рабочих пространствах." #: ../../WPrefs.app/Icons.c:273 msgid "Icon Size" msgstr "Размер иконок" #: ../../WPrefs.app/Icons.c:275 msgid "The size of the dock/application icon and miniwindows" msgstr "Размер миниокон и иконок приложений/дока" #: ../../WPrefs.app/Icons.c:345 msgid "Icon Preferences" msgstr "Установки для иконок" #: ../../WPrefs.app/Icons.c:347 msgid "" "Icon/Miniwindow handling options. Icon positioning\n" "area, sizes of icons, miniaturization animation style." msgstr "" "Параметры обработки иконок и миниокон. Размещение иконок,\n" "размер иконок, в каком стиле анимировать сворачивание." #: ../../WPrefs.app/Icons.c:414 msgid "Single click activation" msgstr "Одинарный щелчок мыши" #: ../../WPrefs.app/imagebrowser.c:95 msgid "View" msgstr "" #: ../../WPrefs.app/KeyboardShortcuts.c:306 ../../WPrefs.app/Menu.c:360 #: ../../WPrefs.app/TexturePanel.c:1534 ../../WPrefs.app/imagebrowser.c:100 msgid "Cancel" msgstr "Отмена" #: ../../WPrefs.app/KeyboardSettings.c:73 msgid "Initial Key Repeat" msgstr "" #: ../../WPrefs.app/KeyboardSettings.c:114 msgid "Key Repeat Rate" msgstr "Скорость повторения клавиши" #: ../../WPrefs.app/KeyboardSettings.c:154 msgid "Type here to test" msgstr "Для теста пишите сюда" #: ../../WPrefs.app/KeyboardSettings.c:173 msgid "Keyboard Preferences" msgstr "Установки для клавиатуры" #: ../../WPrefs.app/KeyboardSettings.c:175 msgid "Not done" msgstr "Не закончено" #: ../../WPrefs.app/KeyboardShortcuts.c:307 msgid "Press the desired shortcut key(s) or click Cancel to stop capturing." msgstr "Нажмите клавишу(ы) или нажмите Отмена для остановки." #: ../../WPrefs.app/KeyboardShortcuts.c:327 #: ../../WPrefs.app/KeyboardShortcuts.c:577 ../../WPrefs.app/Menu.c:371 #: ../../WPrefs.app/Menu.c:830 msgid "Capture" msgstr "Захват" #: ../../WPrefs.app/KeyboardShortcuts.c:328 #: ../../WPrefs.app/KeyboardShortcuts.c:585 msgid "Click Capture to interactively define the shortcut key." msgstr "Нажмите \"Захват\" чтобы определить горячую клавишу(ы)." #: ../../WPrefs.app/KeyboardShortcuts.c:483 msgid "Actions" msgstr "Действия" #: ../../WPrefs.app/KeyboardShortcuts.c:499 msgid "Open applications menu" msgstr "Открыть меню приложений" #: ../../WPrefs.app/KeyboardShortcuts.c:500 msgid "Open window list menu" msgstr "Список окон" #: ../../WPrefs.app/KeyboardShortcuts.c:501 msgid "Open window commands menu" msgstr "Команды для окна" #: ../../WPrefs.app/KeyboardShortcuts.c:502 msgid "Hide active application" msgstr "Скрыть активное приложение" #: ../../WPrefs.app/KeyboardShortcuts.c:503 msgid "Hide other applications" msgstr "Скрыть другие приложения" #: ../../WPrefs.app/KeyboardShortcuts.c:504 msgid "Miniaturize active window" msgstr "Свернуть активное окно" #: ../../WPrefs.app/KeyboardShortcuts.c:505 msgid "Close active window" msgstr "Закрыть активное окно" #: ../../WPrefs.app/KeyboardShortcuts.c:506 msgid "Maximize active window" msgstr "Распахнуть активное окно" #: ../../WPrefs.app/KeyboardShortcuts.c:507 msgid "Maximize active window vertically" msgstr "Распахнуть активное окно по вертикали" #: ../../WPrefs.app/KeyboardShortcuts.c:508 msgid "Maximize active window horizontally" msgstr "Распахнуть активное окно по вертикали" #: ../../WPrefs.app/KeyboardShortcuts.c:509 msgid "Raise active window" msgstr "Активное окно наверх" #: ../../WPrefs.app/KeyboardShortcuts.c:510 msgid "Lower active window" msgstr "Активное окно вниз" #: ../../WPrefs.app/KeyboardShortcuts.c:511 msgid "Raise/Lower window under mouse pointer" msgstr "Вверх/Вниз активное окно" #: ../../WPrefs.app/KeyboardShortcuts.c:512 msgid "Shade active window" msgstr "Втянуть активное окно" #: ../../WPrefs.app/KeyboardShortcuts.c:513 msgid "Move/Resize active window" msgstr "Переместить/изменить размер" #: ../../WPrefs.app/KeyboardShortcuts.c:514 msgid "Select active window" msgstr "Пометить активное окно" #: ../../WPrefs.app/KeyboardShortcuts.c:515 msgid "Focus next window" msgstr "Следующее окно" #: ../../WPrefs.app/KeyboardShortcuts.c:516 msgid "Focus previous window" msgstr "Предыдущее окно" #: ../../WPrefs.app/KeyboardShortcuts.c:517 msgid "Switch to next workspace" msgstr "Следующее рабочее пространство" #: ../../WPrefs.app/KeyboardShortcuts.c:518 msgid "Switch to previous workspace" msgstr "Предыдущее рабочее пространство" #: ../../WPrefs.app/KeyboardShortcuts.c:519 msgid "Switch to next ten workspaces" msgstr "Следующие 10 рабочих пространств" #: ../../WPrefs.app/KeyboardShortcuts.c:520 msgid "Switch to previous ten workspaces" msgstr "Предыдущие 10 рабочих пространств" #: ../../WPrefs.app/KeyboardShortcuts.c:521 msgid "Switch to workspace 1" msgstr "Рабочее пространство 1" #: ../../WPrefs.app/KeyboardShortcuts.c:522 msgid "Switch to workspace 2" msgstr "Рабочее пространство 2" #: ../../WPrefs.app/KeyboardShortcuts.c:523 msgid "Switch to workspace 3" msgstr "Рабочее пространство 3" #: ../../WPrefs.app/KeyboardShortcuts.c:524 msgid "Switch to workspace 4" msgstr "Рабочее пространство 4" #: ../../WPrefs.app/KeyboardShortcuts.c:525 msgid "Switch to workspace 5" msgstr "Рабочее пространство 5" #: ../../WPrefs.app/KeyboardShortcuts.c:526 msgid "Switch to workspace 6" msgstr "Рабочее пространство 6" #: ../../WPrefs.app/KeyboardShortcuts.c:527 msgid "Switch to workspace 7" msgstr "Рабочее пространство 7" #: ../../WPrefs.app/KeyboardShortcuts.c:528 msgid "Switch to workspace 8" msgstr "Рабочее пространство 8" #: ../../WPrefs.app/KeyboardShortcuts.c:529 msgid "Switch to workspace 9" msgstr "Рабочее пространство 9" #: ../../WPrefs.app/KeyboardShortcuts.c:530 msgid "Switch to workspace 10" msgstr "Рабочее пространство 10" #: ../../WPrefs.app/KeyboardShortcuts.c:531 msgid "Shortcut for window 1" msgstr "Горячая клавиша 1" #: ../../WPrefs.app/KeyboardShortcuts.c:532 msgid "Shortcut for window 2" msgstr "Горячая клавиша 2" #: ../../WPrefs.app/KeyboardShortcuts.c:533 msgid "Shortcut for window 3" msgstr "Горячая клавиша 3" #: ../../WPrefs.app/KeyboardShortcuts.c:534 msgid "Shortcut for window 4" msgstr "Горячая клавиша 4" #: ../../WPrefs.app/KeyboardShortcuts.c:535 msgid "Shortcut for window 5" msgstr "Горячая клавиша 5" #: ../../WPrefs.app/KeyboardShortcuts.c:536 msgid "Shortcut for window 6" msgstr "Горячая клавиша 6" #: ../../WPrefs.app/KeyboardShortcuts.c:537 msgid "Shortcut for window 7" msgstr "Горячая клавиша 7" #: ../../WPrefs.app/KeyboardShortcuts.c:538 msgid "Shortcut for window 8" msgstr "Горячая клавиша 8" #: ../../WPrefs.app/KeyboardShortcuts.c:539 msgid "Shortcut for window 9" msgstr "Горячая клавиша 9" #: ../../WPrefs.app/KeyboardShortcuts.c:540 msgid "Shortcut for window 10" msgstr "Горячая клавиша 10" #: ../../WPrefs.app/KeyboardShortcuts.c:541 msgid "Switch to Next Screen/Monitor" msgstr "Следующий экран/монитор" #: ../../WPrefs.app/KeyboardShortcuts.c:542 msgid "Raise Clip" msgstr "Поднять Скрепку" #: ../../WPrefs.app/KeyboardShortcuts.c:543 msgid "Lower Clip" msgstr "Опустить Скрепку" #: ../../WPrefs.app/KeyboardShortcuts.c:544 msgid "Raise/Lower Clip" msgstr "Поднять/Опустить Скрепку" #: ../../WPrefs.app/KeyboardShortcuts.c:546 msgid "Toggle keyboard language" msgstr "Переключить язык клавиатуры" #: ../../WPrefs.app/KeyboardShortcuts.c:560 msgid "Shortcut" msgstr "Горячая клавиша" #: ../../WPrefs.app/KeyboardShortcuts.c:571 ../../WPrefs.app/Menu.c:836 msgid "Clear" msgstr "Очистить" #: ../../WPrefs.app/KeyboardShortcuts.c:633 msgid "Keyboard Shortcut Preferences" msgstr "Горячие клавиши" #: ../../WPrefs.app/KeyboardShortcuts.c:635 msgid "" "Change the keyboard shortcuts for actions such\n" "as changing workspaces and opening menus." msgstr "" "Изменить привязку клавиш для функций наподобие\n" "`переключить рабочее пространство' и `открыть меню'." #: ../../WPrefs.app/main.c:59 #, c-format msgid "usage: %s [options]\n" msgstr "Запуск: %s [параметры]\n" #: ../../WPrefs.app/main.c:60 msgid "options:" msgstr "Параметры:" #: ../../WPrefs.app/main.c:61 msgid " -display <display>\tdisplay to be used" msgstr " -display <дисплей>\tX дисплей для использования" #: ../../WPrefs.app/main.c:62 msgid " --version\t\tprint version number and exit" msgstr " --version\t\tпоказать номер версии и выйти" #: ../../WPrefs.app/main.c:63 msgid " --help\t\tprint this message and exit" msgstr " --help\t\tпоказать это сообщение и выйти" #: ../../WPrefs.app/main.c:122 #, c-format msgid "too few arguments for %s" msgstr "слишком мало аргументов для %s" #: ../../WPrefs.app/main.c:144 msgid "X server does not support locale" msgstr "X сервер не поддерживает locale" #: ../../WPrefs.app/main.c:147 msgid "cannot set locale modifiers" msgstr "не получается установить модификаторы локализации" #: ../../WPrefs.app/main.c:153 #, c-format msgid "could not open display %s" msgstr "не могу открыть дисплей %s" #: ../../WPrefs.app/main.c:161 msgid "could not initialize application" msgstr "не получается инициализировать приложение" diff --git a/src/WindowMaker.h b/src/WindowMaker.h index b4f3a88..fa04093 100644 --- a/src/WindowMaker.h +++ b/src/WindowMaker.h @@ -1,661 +1,662 @@ /* * Window Maker window manager * * Copyright (c) 1997-2003 Alfredo K. Kojima * Copyright (c) 2014 Window Maker Team * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef WINDOWMAKER_H_ #define WINDOWMAKER_H_ #include "wconfig.h" #include <assert.h> #include <limits.h> #include <WINGs/WINGs.h> /* class codes */ typedef enum { WCLASS_UNKNOWN = 0, WCLASS_WINDOW = 1, /* managed client windows */ WCLASS_MENU = 2, /* root menus */ WCLASS_APPICON = 3, WCLASS_DUMMYWINDOW = 4, /* window that holds window group leader */ WCLASS_MINIWINDOW = 5, WCLASS_DOCK_ICON = 6, WCLASS_PAGER = 7, WCLASS_TEXT_INPUT = 8, WCLASS_FRAME = 9 } WClassType; /* * generic window levels (a superset of the N*XTSTEP ones) * Applications should use levels between WMDesktopLevel and * WMScreensaverLevel anything boyond that range is allowed, * but discouraged. */ enum { WMBackLevel = INT_MIN+1, /* Very lowest level */ WMDesktopLevel = -1000, /* Lowest level of normal use */ WMSunkenLevel = -1, WMNormalLevel = 0, WMFloatingLevel = 3, WMDockLevel = 5, WMSubmenuLevel = 15, WMMainMenuLevel = 20, WMStatusLevel = 21, WMFullscreenLevel = 50, WMModalLevel = 100, WMPopUpLevel = 101, WMScreensaverLevel = 1000, WMOuterSpaceLevel = INT_MAX }; /* * WObjDescriptor will be used by the event dispatcher to * send events to a particular object through the methods in the * method table. If all objects of the same class share the * same methods, the class method table should be used, otherwise * a new method table must be created for each object. * It is also assigned to find the parent structure of a given * window (like the WWindow or WMenu for a button) */ typedef struct WObjDescriptor { void *self; /* the object that will be called */ /* event handlers */ void (*handle_expose)(struct WObjDescriptor *sender, XEvent *event); void (*handle_mousedown)(struct WObjDescriptor *sender, XEvent *event); void (*handle_enternotify)(struct WObjDescriptor *sender, XEvent *event); void (*handle_leavenotify)(struct WObjDescriptor *sender, XEvent *event); WClassType parent_type; /* type code of the parent */ void *parent; /* parent object (WWindow or WMenu) */ } WObjDescriptor; /* internal buttons */ #define WBUT_CLOSE 0 #define WBUT_BROKENCLOSE 1 #define WBUT_ICONIFY 2 #define WBUT_KILL 3 #ifdef XKB_BUTTON_HINT #define WBUT_XKBGROUP1 4 #define WBUT_XKBGROUP2 5 #define WBUT_XKBGROUP3 6 #define WBUT_XKBGROUP4 7 #define PRED_BPIXMAPS 8 /* reserved for 4 groups */ #else #define PRED_BPIXMAPS 4 /* count of WBUT icons */ #endif /* XKB_BUTTON_HINT */ /* Mouse cursors */ typedef enum { WCUR_NORMAL, WCUR_MOVE, WCUR_RESIZE, WCUR_TOPLEFTRESIZE, WCUR_TOPRIGHTRESIZE, WCUR_BOTTOMLEFTRESIZE, WCUR_BOTTOMRIGHTRESIZE, WCUR_VERTICALRESIZE, WCUR_HORIZONRESIZE, WCUR_WAIT, WCUR_ARROW, WCUR_QUESTION, WCUR_TEXT, WCUR_SELECT, WCUR_ROOT, WCUR_EMPTY, /* Count of the number of cursors defined */ WCUR_LAST } w_cursor; /* geometry displays */ #define WDIS_NEW 0 /* new style */ #define WDIS_CENTER 1 /* center of screen */ #define WDIS_TOPLEFT 2 /* top left corner of screen */ #define WDIS_FRAME_CENTER 3 /* center of the frame */ #define WDIS_NONE 4 /* keyboard input focus mode */ #define WKF_CLICK 0 #define WKF_SLOPPY 2 /* colormap change mode */ #define WCM_CLICK 0 #define WCM_POINTER 1 /* window placement mode */ #define WPM_MANUAL 0 #define WPM_CASCADE 1 #define WPM_SMART 2 #define WPM_RANDOM 3 #define WPM_AUTO 4 #define WPM_CENTER 5 /* text justification */ #define WTJ_CENTER 0 #define WTJ_LEFT 1 #define WTJ_RIGHT 2 /* iconification styles */ #define WIS_ZOOM 0 #define WIS_TWIST 1 #define WIS_FLIP 2 #define WIS_NONE 3 #define WIS_RANDOM 4 /* secret */ /* switchmenu actions */ #define ACTION_ADD 0 #define ACTION_REMOVE 1 #define ACTION_CHANGE 2 #define ACTION_CHANGE_WORKSPACE 3 #define ACTION_CHANGE_STATE 4 /* speeds */ #define SPEED_ULTRAFAST 0 #define SPEED_FAST 1 #define SPEED_MEDIUM 2 #define SPEED_SLOW 3 #define SPEED_ULTRASLOW 4 /* window states */ #define WS_FOCUSED 0 #define WS_UNFOCUSED 1 #define WS_PFOCUSED 2 /* clip title colors */ #define CLIP_NORMAL 0 #define CLIP_COLLAPSED 1 /* icon yard position */ #define IY_VERT 1 #define IY_HORIZ 0 #define IY_TOP 2 #define IY_BOTTOM 0 #define IY_RIGHT 4 #define IY_LEFT 0 /* menu styles */ #define MS_NORMAL 0 #define MS_SINGLE_TEXTURE 1 #define MS_FLAT 2 /* workspace actions */ #define WA_NONE 0 #define WA_SELECT_WINDOWS 1 #define WA_OPEN_APPMENU 2 #define WA_OPEN_WINLISTMENU 3 #define WA_SWITCH_WORKSPACES 4 #define WA_MOVE_PREVWORKSPACE 5 #define WA_MOVE_NEXTWORKSPACE 6 #define WA_SWITCH_WINDOWS 7 #define WA_MOVE_PREVWINDOW 8 #define WA_MOVE_NEXTWINDOW 9 /* workspace display position */ #define WD_NONE 0 #define WD_CENTER 1 #define WD_TOP 2 #define WD_BOTTOM 3 #define WD_TOPLEFT 4 #define WD_TOPRIGHT 5 #define WD_BOTTOMLEFT 6 #define WD_BOTTOMRIGHT 7 /* titlebar style */ #define TS_NEW 0 #define TS_OLD 1 #define TS_NEXT 2 /* workspace border position */ #define WB_NONE 0 #define WB_LEFTRIGHT 1 #define WB_TOPBOTTOM 2 #define WB_ALLDIRS (WB_LEFTRIGHT|WB_TOPBOTTOM) /* drag maximized window behaviors */ enum { DRAGMAX_MOVE, DRAGMAX_RESTORE, DRAGMAX_UNMAXIMIZE, DRAGMAX_NOMOVE }; /* program states */ typedef enum { WSTATE_NORMAL = 0, WSTATE_NEED_EXIT = 1, WSTATE_NEED_RESTART = 2, WSTATE_EXITING = 3, WSTATE_RESTARTING = 4, WSTATE_MODAL = 5, WSTATE_NEED_REREAD = 6 } wprog_state; #define WCHECK_STATE(chk_state) (w_global.program.state == (chk_state)) #define WCHANGE_STATE(nstate) {\ if (w_global.program.state == WSTATE_NORMAL \ || (nstate) != WSTATE_MODAL) \ w_global.program.state = (nstate); \ if (w_global.program.signal_state != 0) \ w_global.program.state = w_global.program.signal_state; \ } /* only call inside signal handlers, with signals blocked */ #define SIG_WCHANGE_STATE(nstate) {\ w_global.program.signal_state = (nstate); \ w_global.program.state = (nstate); \ } /* Flags for the Window Maker state when restarting/crash situations */ #define WFLAGS_NONE (0) #define WFLAGS_CRASHED (1<<0) /* notifications */ #ifdef MAINFILE #define NOTIFICATION(n) const char WN##n [] = #n #else #define NOTIFICATION(n) extern const char WN##n [] #endif NOTIFICATION(WindowAppearanceSettingsChanged); NOTIFICATION(IconAppearanceSettingsChanged); NOTIFICATION(IconTileSettingsChanged); NOTIFICATION(MenuAppearanceSettingsChanged); NOTIFICATION(MenuTitleAppearanceSettingsChanged); /* appearance settings clientdata flags */ enum { WFontSettings = 1 << 0, WTextureSettings = 1 << 1, WColorSettings = 1 << 2 }; typedef struct { int x1, y1; int x2, y2; } WArea; typedef struct WCoord { int x, y; } WCoord; extern struct WPreferences { char *pixmap_path; /* : separated list of paths to find pixmaps */ char *icon_path; /* : separated list of paths to find icons */ WMArray *fallbackWMs; /* fallback window manager list */ char *logger_shell; /* shell to log child stdi/o */ RImage *button_images; /* titlebar button images */ char smooth_workspace_back; signed char size_display; /* display type for resize geometry */ signed char move_display; /* display type for move geometry */ signed char window_placement; /* window placement mode */ signed char colormap_mode; /* colormap focus mode */ signed char focus_mode; /* window focusing mode */ char opaque_move; /* update window position during move */ char opaque_resize; /* update window position during resize */ char opaque_move_resize_keyboard; /* update window position during move,resize with keyboard */ char wrap_menus; /* wrap menus at edge of screen */ char scrollable_menus; /* let them be scrolled */ char vi_key_menus; /* use h/j/k/l to select */ char align_menus; /* align menu with their parents */ char use_saveunders; /* turn on SaveUnders for menus, icons etc. */ char no_window_over_dock; char no_window_over_icons; WCoord window_place_origin; /* Offset for windows placed on screen */ char constrain_window_size; /* don't let windows get bigger than screen */ char windows_cycling; /* windoze cycling */ char circ_raise; /* raise window after Alt-tabbing */ char ignore_focus_click; char open_transients_with_parent; /* open transient window in same workspace as parent */ signed char title_justification; /* titlebar text alignment */ int window_title_clearance; int window_title_min_height; int window_title_max_height; int menu_title_clearance; int menu_title_min_height; int menu_title_max_height; int menu_text_clearance; char multi_byte_text; #ifdef KEEP_XKB_LOCK_STATUS char modelock; #endif char no_dithering; /* use dithering or not */ char no_animations; /* enable/disable animations */ char no_autowrap; /* wrap workspace when window is moved to the edge */ char window_snapping; /* enable window snapping */ int snap_edge_detect; /* how far from edge to begin snap */ int snap_corner_detect; /* how far from corner to begin snap */ char snap_to_top_maximizes_fullscreen; char drag_maximized_window; /* behavior when a maximized window is dragged */ char move_half_max_between_heads; /* move half maximized window between available heads */ char alt_half_maximize; /* alternative half-maximize feature behavior */ char pointer_with_half_max_windows; char highlight_active_app; /* show the focused app by highlighting its icon */ char auto_arrange_icons; /* automagically arrange icons */ char icon_box_position; /* position to place icons */ signed char iconification_style; /* position to place icons */ char disable_root_mouse; /* disable button events in root window */ char auto_focus; /* focus window when it's mapped */ char *icon_back_file; /* background image for icons */ char enforce_icon_margin; /* auto-shrink icon images */ WCoord *root_menu_pos; /* initial position of the root menu*/ WCoord *app_menu_pos; WCoord *win_menu_pos; signed char icon_yard; /* aka iconbox */ int raise_delay; /* delay for autoraise. 0 is disabled */ int cmap_size; /* size of dithering colormap in colors per channel */ int icon_size; /* size of the icon */ signed char menu_style; /* menu decoration style */ signed char workspace_name_display_position; unsigned int modifier_mask; /* mask to use as kbd modifier */ char *modifier_labels[7]; /* Names of the modifiers */ unsigned int supports_tiff; /* Use tiff files */ char ws_advance; /* Create new workspace and advance */ char ws_cycle; /* Cycle existing workspaces */ char save_session_on_exit; /* automatically save session on exit */ char sticky_icons; /* If miniwindows will be onmipresent */ char dont_confirm_kill; /* do not confirm Kill application */ char disable_miniwindows; char enable_workspace_pager; char ignore_gtk_decoration_hints; char dont_blink; /* do not blink icon selection */ /* Appearance options */ char new_style; /* Use newstyle buttons */ char superfluous; /* Use superfluous things */ /* root window mouse bindings */ signed char mouse_button1; /* action for left mouse button */ signed char mouse_button2; /* action for middle mouse button */ signed char mouse_button3; /* action for right mouse button */ signed char mouse_button8; /* action for 4th button aka backward mouse button */ signed char mouse_button9; /* action for 5th button aka forward mouse button */ signed char mouse_wheel_scroll; /* action for mouse wheel scroll */ signed char mouse_wheel_tilt; /* action for mouse wheel tilt */ /* balloon text */ char window_balloon; char miniwin_title_balloon; char miniwin_preview_balloon; char appicon_balloon; char help_balloon; /* some constants */ int dblclick_time; /* double click delay time in ms */ /* animate menus */ signed char menu_scroll_speed; /* how fast menus are scrolled */ /* animate icon sliding */ signed char icon_slide_speed; /* icon slide animation speed */ /* shading animation */ signed char shade_speed; /* bouncing animation */ char bounce_appicons_when_urgent; char raise_appicons_when_bouncing; char do_not_make_appicons_bounce; int edge_resistance; int resize_increment; char attract; unsigned int workspace_border_size; /* Size in pixels of the workspace border */ char workspace_border_position; /* Where to leave a workspace border */ char single_click; /* single click to lauch applications */ int history_lines; /* history of "Run..." dialog */ char cycle_active_head_only; /* Cycle only windows on the active head */ char cycle_ignore_minimized; /* Ignore minimized windows when cycling */ char double_click_fullscreen; /* Double click on titlebar maximize a window to full screen*/ + char close_rootmenu_left_right_click;/* Close application menu when mouse (left or right) is clicked outside focus */ char strict_windoze_cycle; /* don't close switch panel when shift is released */ char panel_only_open; /* Only open the switch panel; don't switch */ int minipreview_size; /* Size of Mini-Previews in pixels */ /* All delays here are in ms. 0 means instant auto-action. */ int clip_auto_raise_delay; /* Delay after which the clip will be raised when entered */ int clip_auto_lower_delay; /* Delay after which the clip will be lowered when leaved */ int clip_auto_expand_delay; /* Delay after which the clip will expand when entered */ int clip_auto_collapse_delay; /* Delay after which the clip will collapse when leaved */ RImage *swtileImage; RImage *swbackImage[9]; union WTexture *wsmbackTexture; char show_clip_title; struct { #ifdef USE_ICCCM_WMREPLACE unsigned int replace:1; /* replace existing window manager */ #endif unsigned int nodock:1; /* don't display the dock */ unsigned int noclip:1; /* don't display the clip */ unsigned int clip_merged_in_dock:1; /* disable clip, switch workspaces with dock */ unsigned int nodrawer:1; /* don't use drawers */ unsigned int wrap_appicons_in_dock:1; /* Whether to wrap appicons when Dock is moved up and down */ unsigned int noupdates:1; /* don't require ~/GNUstep (-static) */ unsigned int noautolaunch:1; /* don't autolaunch apps */ unsigned int norestore:1; /* don't restore session */ unsigned int restarting:2; } flags; /* internal flags */ /* Map table between w_cursor and actual X id */ Cursor cursor[WCUR_LAST]; int switch_panel_icon_size; /* icon size in switch panel */ } wPreferences; /****** Global Variables ******/ extern Display *dpy; extern struct wmaker_global_variables { /* Tracking of the state of the program */ struct { wprog_state state; wprog_state signal_state; } program; /* locale to use. NULL==POSIX or C */ const char *locale; /* Tracking of X events timestamps */ struct { /* ts of the last event we received */ Time last_event; /* ts on the last time we did XSetInputFocus() */ Time focus_change; } timestamp; /* Global Domains, for storing dictionaries */ struct { /* Note: you must #include <defaults.h> if you want to use them */ struct WDDomain *wmaker; struct WDDomain *window_attr; struct WDDomain *root_menu; } domain; /* Screens related */ int screen_count; /* * Ignore Workspace Change: * this variable is used to prevent workspace switch while certain * operations are ongoing. */ Bool ignore_workspace_change; /* * Process WorkspaceMap Event: * this variable is set when the Workspace Map window is being displayed, * it is mainly used to avoid re-opening another one at the same time */ Bool process_workspacemap_event; #ifdef HAVE_INOTIFY struct { int fd_event_queue; /* Inotify's queue file descriptor */ int wd_defaults; /* Watch Descriptor for the 'Defaults' configuration file */ } inotify; #endif /* definition for X Atoms */ struct { /* Window-Manager related */ struct { Atom state; Atom change_state; Atom protocols; Atom take_focus; Atom delete_window; Atom save_yourself; Atom client_leader; Atom colormap_windows; Atom colormap_notify; Atom ignore_focus_events; } wm; /* GNUStep related */ struct { Atom wm_attr; Atom wm_miniaturize_window; Atom wm_resizebar; Atom titlebar_state; } gnustep; /* Destkop-environment related */ struct { Atom gtk_object_path; } desktop; /* WindowMaker specific */ struct { Atom menu; Atom wm_protocols; Atom state; Atom wm_function; Atom noticeboard; Atom command; Atom icon_size; Atom icon_tile; } wmaker; } atom; /* X Contexts */ struct { XContext client_win; XContext app_win; XContext stack; } context; /* X Extensions */ struct { #ifdef USE_XSHAPE struct { Bool supported; int event_base; } shape; #endif #ifdef KEEP_XKB_LOCK_STATUS struct { Bool supported; int event_base; } xkb; #endif #ifdef USE_RANDR struct { Bool supported; int event_base; } randr; #endif /* * If no extension were activated, we would end up with an empty * structure, which old compilers may not appreciate, so let's * work around this with a simple: */ int dummy; } xext; /* Keyboard and shortcuts */ struct { /* * Bit-mask to hide special key modifiers which we don't want to * impact the shortcuts (typically: CapsLock, NumLock, ScrollLock) */ unsigned int modifiers_mask; } shortcut; } w_global; /****** Notifications ******/ extern const char WMNManaged[]; extern const char WMNUnmanaged[]; extern const char WMNChangedWorkspace[]; extern const char WMNChangedState[]; extern const char WMNChangedFocus[]; extern const char WMNChangedStacking[]; extern const char WMNChangedName[]; extern const char WMNWorkspaceCreated[]; extern const char WMNWorkspaceDestroyed[]; extern const char WMNWorkspaceChanged[]; extern const char WMNWorkspaceNameChanged[]; extern const char WMNResetStacking[]; #endif diff --git a/src/defaults.c b/src/defaults.c index 11c438f..2f68539 100644 --- a/src/defaults.c +++ b/src/defaults.c @@ -318,1025 +318,1027 @@ static WOptionEnumeration seDragMaximizedWindow[] = { * * Also add the default key/value pair to WindowMaker/Defaults/WindowMaker.in */ /* these options will only affect the window manager on startup * * static defaults can't access the screen data, because it is * created after these defaults are read */ WDefaultEntry staticOptionList[] = { {"ColormapSize", "4", NULL, &wPreferences.cmap_size, getInt, NULL, NULL, NULL}, {"DisableDithering", "NO", NULL, &wPreferences.no_dithering, getBool, NULL, NULL, NULL}, {"IconSize", "64", NULL, &wPreferences.icon_size, getInt, NULL, NULL, NULL}, {"ModifierKey", "Mod1", NULL, &wPreferences.modifier_mask, getModMask, NULL, NULL, NULL}, {"FocusMode", "manual", seFocusModes, /* have a problem when switching from */ &wPreferences.focus_mode, getEnum, NULL, NULL, NULL}, /* manual to sloppy without restart */ {"NewStyle", "new", seTitlebarModes, &wPreferences.new_style, getEnum, NULL, NULL, NULL}, {"DisableDock", "NO", (void *)WM_DOCK, NULL, getBool, setIfDockPresent, NULL, NULL}, {"DisableClip", "NO", (void *)WM_CLIP, NULL, getBool, setIfDockPresent, NULL, NULL}, {"DisableDrawers", "NO", (void *)WM_DRAWER, NULL, getBool, setIfDockPresent, NULL, NULL}, {"ClipMergedInDock", "NO", NULL, NULL, getBool, setClipMergedInDock, NULL, NULL}, {"DisableMiniwindows", "NO", NULL, &wPreferences.disable_miniwindows, getBool, NULL, NULL, NULL}, {"EnableWorkspacePager", "NO", NULL, &wPreferences.enable_workspace_pager, getBool, NULL, NULL, NULL}, {"SwitchPanelIconSize", "64", NULL, &wPreferences.switch_panel_icon_size, getInt, NULL, NULL, NULL}, }; #define NUM2STRING_(x) #x #define NUM2STRING(x) NUM2STRING_(x) WDefaultEntry optionList[] = { /* dynamic options */ {"IconPosition", "blh", seIconPositions, &wPreferences.icon_yard, getEnum, setIconPosition, NULL, NULL}, {"IconificationStyle", "Zoom", seIconificationStyles, &wPreferences.iconification_style, getEnum, NULL, NULL, NULL}, {"EnforceIconMargin", "NO", NULL, &wPreferences.enforce_icon_margin, getBool, NULL, NULL, NULL}, {"DisableWSMouseActions", "NO", NULL, &wPreferences.disable_root_mouse, getBool, NULL, NULL, NULL}, {"MouseLeftButtonAction", "SelectWindows", seMouseButtonActions, &wPreferences.mouse_button1, getEnum, NULL, NULL, NULL}, {"MouseMiddleButtonAction", "OpenWindowListMenu", seMouseButtonActions, &wPreferences.mouse_button2, getEnum, NULL, NULL, NULL}, {"MouseRightButtonAction", "OpenApplicationsMenu", seMouseButtonActions, &wPreferences.mouse_button3, getEnum, NULL, NULL, NULL}, {"MouseBackwardButtonAction", "None", seMouseButtonActions, &wPreferences.mouse_button8, getEnum, NULL, NULL, NULL}, {"MouseForwardButtonAction", "None", seMouseButtonActions, &wPreferences.mouse_button9, getEnum, NULL, NULL, NULL}, {"MouseWheelAction", "None", seMouseWheelActions, &wPreferences.mouse_wheel_scroll, getEnum, NULL, NULL, NULL}, {"MouseWheelTiltAction", "None", seMouseWheelActions, &wPreferences.mouse_wheel_tilt, getEnum, NULL, NULL, NULL}, {"PixmapPath", DEF_PIXMAP_PATHS, NULL, &wPreferences.pixmap_path, getPathList, NULL, NULL, NULL}, {"IconPath", DEF_ICON_PATHS, NULL, &wPreferences.icon_path, getPathList, NULL, NULL, NULL}, {"ColormapMode", "auto", seColormapModes, &wPreferences.colormap_mode, getEnum, NULL, NULL, NULL}, {"AutoFocus", "YES", NULL, &wPreferences.auto_focus, getBool, NULL, NULL, NULL}, {"RaiseDelay", "0", NULL, &wPreferences.raise_delay, getInt, NULL, NULL, NULL}, {"CirculateRaise", "NO", NULL, &wPreferences.circ_raise, getBool, NULL, NULL, NULL}, {"Superfluous", "YES", NULL, &wPreferences.superfluous, getBool, NULL, NULL, NULL}, {"AdvanceToNewWorkspace", "NO", NULL, &wPreferences.ws_advance, getBool, NULL, NULL, NULL}, {"CycleWorkspaces", "NO", NULL, &wPreferences.ws_cycle, getBool, NULL, NULL, NULL}, {"WorkspaceNameDisplayPosition", "center", seDisplayPositions, &wPreferences.workspace_name_display_position, getEnum, NULL, NULL, NULL}, {"WorkspaceBorder", "None", seWorkspaceBorder, &wPreferences.workspace_border_position, getEnum, updateUsableArea, NULL, NULL}, {"WorkspaceBorderSize", "0", NULL, &wPreferences.workspace_border_size, getInt, updateUsableArea, NULL, NULL}, {"StickyIcons", "NO", NULL, &wPreferences.sticky_icons, getBool, setStickyIcons, NULL, NULL}, {"SaveSessionOnExit", "NO", NULL, &wPreferences.save_session_on_exit, getBool, NULL, NULL, NULL}, {"WrapMenus", "NO", NULL, &wPreferences.wrap_menus, getBool, NULL, NULL, NULL}, {"ScrollableMenus", "YES", NULL, &wPreferences.scrollable_menus, getBool, NULL, NULL, NULL}, {"MenuScrollSpeed", "fast", seSpeeds, &wPreferences.menu_scroll_speed, getEnum, NULL, NULL, NULL}, {"IconSlideSpeed", "fast", seSpeeds, &wPreferences.icon_slide_speed, getEnum, NULL, NULL, NULL}, {"ShadeSpeed", "fast", seSpeeds, &wPreferences.shade_speed, getEnum, NULL, NULL, NULL}, {"BounceAppIconsWhenUrgent", "YES", NULL, &wPreferences.bounce_appicons_when_urgent, getBool, NULL, NULL, NULL}, {"RaiseAppIconsWhenBouncing", "NO", NULL, &wPreferences.raise_appicons_when_bouncing, getBool, NULL, NULL, NULL}, {"DoNotMakeAppIconsBounce", "NO", NULL, &wPreferences.do_not_make_appicons_bounce, getBool, NULL, NULL, NULL}, {"DoubleClickTime", "250", (void *)&wPreferences.dblclick_time, &wPreferences.dblclick_time, getInt, setDoubleClick, NULL, NULL}, {"ClipAutoraiseDelay", "600", NULL, &wPreferences.clip_auto_raise_delay, getInt, NULL, NULL, NULL}, {"ClipAutolowerDelay", "1000", NULL, &wPreferences.clip_auto_lower_delay, getInt, NULL, NULL, NULL}, {"ClipAutoexpandDelay", "600", NULL, &wPreferences.clip_auto_expand_delay, getInt, NULL, NULL, NULL}, {"ClipAutocollapseDelay", "1000", NULL, &wPreferences.clip_auto_collapse_delay, getInt, NULL, NULL, NULL}, {"WrapAppiconsInDock", "YES", NULL, NULL, getBool, setWrapAppiconsInDock, NULL, NULL}, {"AlignSubmenus", "NO", NULL, &wPreferences.align_menus, getBool, NULL, NULL, NULL}, {"ViKeyMenus", "NO", NULL, &wPreferences.vi_key_menus, getBool, NULL, NULL, NULL}, {"OpenTransientOnOwnerWorkspace", "NO", NULL, &wPreferences.open_transients_with_parent, getBool, NULL, NULL, NULL}, {"WindowPlacement", "auto", sePlacements, &wPreferences.window_placement, getEnum, NULL, NULL, NULL}, {"IgnoreFocusClick", "NO", NULL, &wPreferences.ignore_focus_click, getBool, NULL, NULL, NULL}, {"UseSaveUnders", "NO", NULL, &wPreferences.use_saveunders, getBool, NULL, NULL, NULL}, {"OpaqueMove", "YES", NULL, &wPreferences.opaque_move, getBool, NULL, NULL, NULL}, {"OpaqueResize", "NO", NULL, &wPreferences.opaque_resize, getBool, NULL, NULL, NULL}, {"OpaqueMoveResizeKeyboard", "NO", NULL, &wPreferences.opaque_move_resize_keyboard, getBool, NULL, NULL, NULL}, {"DisableAnimations", "NO", NULL, &wPreferences.no_animations, getBool, NULL, NULL, NULL}, {"DontLinkWorkspaces", "YES", NULL, &wPreferences.no_autowrap, getBool, NULL, NULL, NULL}, {"WindowSnapping", "NO", NULL, &wPreferences.window_snapping, getBool, NULL, NULL, NULL}, {"SnapEdgeDetect", "1", NULL, &wPreferences.snap_edge_detect, getInt, NULL, NULL, NULL}, {"SnapCornerDetect", "10", NULL, &wPreferences.snap_corner_detect, getInt, NULL, NULL, NULL}, {"SnapToTopMaximizesFullscreen", "NO", NULL, &wPreferences.snap_to_top_maximizes_fullscreen, getBool, NULL, NULL, NULL}, {"DragMaximizedWindow", "Move", seDragMaximizedWindow, &wPreferences.drag_maximized_window, getEnum, NULL, NULL, NULL}, {"MoveHalfMaximizedWindowsBetweenScreens", "NO", NULL, &wPreferences.move_half_max_between_heads, getBool, NULL, NULL, NULL}, {"AlternativeHalfMaximized", "NO", NULL, &wPreferences.alt_half_maximize, getBool, NULL, NULL, NULL}, {"PointerWithHalfMaxWindows", "NO", NULL, &wPreferences.pointer_with_half_max_windows, getBool, NULL, NULL, NULL}, {"HighlightActiveApp", "YES", NULL, &wPreferences.highlight_active_app, getBool, NULL, NULL, NULL}, {"AutoArrangeIcons", "NO", NULL, &wPreferences.auto_arrange_icons, getBool, NULL, NULL, NULL}, {"NoWindowOverDock", "NO", NULL, &wPreferences.no_window_over_dock, getBool, updateUsableArea, NULL, NULL}, {"NoWindowOverIcons", "NO", NULL, &wPreferences.no_window_over_icons, getBool, updateUsableArea, NULL, NULL}, {"WindowPlaceOrigin", "(64, 0)", NULL, &wPreferences.window_place_origin, getCoord, NULL, NULL, NULL}, {"ResizeDisplay", "center", seGeomDisplays, &wPreferences.size_display, getEnum, NULL, NULL, NULL}, {"MoveDisplay", "floating", seGeomDisplays, &wPreferences.move_display, getEnum, NULL, NULL, NULL}, {"DontConfirmKill", "NO", NULL, &wPreferences.dont_confirm_kill, getBool, NULL, NULL, NULL}, {"WindowTitleBalloons", "YES", NULL, &wPreferences.window_balloon, getBool, NULL, NULL, NULL}, {"MiniwindowTitleBalloons", "NO", NULL, &wPreferences.miniwin_title_balloon, getBool, NULL, NULL, NULL}, {"MiniwindowPreviewBalloons", "NO", NULL, &wPreferences.miniwin_preview_balloon, getBool, NULL, NULL, NULL}, {"AppIconBalloons", "NO", NULL, &wPreferences.appicon_balloon, getBool, NULL, NULL, NULL}, {"HelpBalloons", "NO", NULL, &wPreferences.help_balloon, getBool, NULL, NULL, NULL}, {"EdgeResistance", "30", NULL, &wPreferences.edge_resistance, getInt, NULL, NULL, NULL}, {"ResizeIncrement", "0", NULL, &wPreferences.resize_increment, getInt, NULL, NULL, NULL}, {"Attraction", "NO", NULL, &wPreferences.attract, getBool, NULL, NULL, NULL}, {"DisableBlinking", "NO", NULL, &wPreferences.dont_blink, getBool, NULL, NULL, NULL}, {"SingleClickLaunch", "NO", NULL, &wPreferences.single_click, getBool, NULL, NULL, NULL}, {"StrictWindozeCycle", "YES", NULL, &wPreferences.strict_windoze_cycle, getBool, NULL, NULL, NULL}, {"SwitchPanelOnlyOpen", "NO", NULL, &wPreferences.panel_only_open, getBool, NULL, NULL, NULL}, {"MiniPreviewSize", "128", NULL, &wPreferences.minipreview_size, getInt, NULL, NULL, NULL}, {"IgnoreGtkHints", "NO", NULL, &wPreferences.ignore_gtk_decoration_hints, getBool, NULL, NULL, NULL}, /* style options */ {"MenuStyle", "normal", seMenuStyles, &wPreferences.menu_style, getEnum, setMenuStyle, NULL, NULL}, {"WidgetColor", "(solid, gray)", NULL, NULL, getTexture, setWidgetColor, NULL, NULL}, {"WorkspaceSpecificBack", "()", NULL, NULL, getWSSpecificBackground, setWorkspaceSpecificBack, NULL, NULL}, /* WorkspaceBack must come after WorkspaceSpecificBack or * WorkspaceBack won't know WorkspaceSpecificBack was also * specified and 2 copies of wmsetbg will be launched */ {"WorkspaceBack", "(solid, \"rgb:50/50/75\")", NULL, NULL, getWSBackground, setWorkspaceBack, NULL, NULL}, {"SmoothWorkspaceBack", "NO", NULL, NULL, getBool, NULL, NULL, NULL}, {"IconBack", "(dgradient, \"rgb:a6/a6/b6\", \"rgb:51/55/61\")", NULL, NULL, getTexture, setIconTile, NULL, NULL}, {"TitleJustify", "center", seJustifications, &wPreferences.title_justification, getEnum, setJustify, NULL, NULL}, {"WindowTitleFont", DEF_TITLE_FONT, NULL, NULL, getFont, setWinTitleFont, NULL, NULL}, {"WindowTitleExtendSpace", DEF_WINDOW_TITLE_EXTEND_SPACE, NULL, &wPreferences.window_title_clearance, getInt, setClearance, NULL, NULL}, {"WindowTitleMinHeight", "0", NULL, &wPreferences.window_title_min_height, getInt, setClearance, NULL, NULL}, {"WindowTitleMaxHeight", NUM2STRING(INT_MAX), NULL, &wPreferences.window_title_max_height, getInt, setClearance, NULL, NULL}, {"MenuTitleExtendSpace", DEF_MENU_TITLE_EXTEND_SPACE, NULL, &wPreferences.menu_title_clearance, getInt, setClearance, NULL, NULL}, {"MenuTitleMinHeight", "0", NULL, &wPreferences.menu_title_min_height, getInt, setClearance, NULL, NULL}, {"MenuTitleMaxHeight", NUM2STRING(INT_MAX), NULL, &wPreferences.menu_title_max_height, getInt, setClearance, NULL, NULL}, {"MenuTextExtendSpace", DEF_MENU_TEXT_EXTEND_SPACE, NULL, &wPreferences.menu_text_clearance, getInt, setClearance, NULL, NULL}, {"MenuTitleFont", DEF_MENU_TITLE_FONT, NULL, NULL, getFont, setMenuTitleFont, NULL, NULL}, {"MenuTextFont", DEF_MENU_ENTRY_FONT, NULL, NULL, getFont, setMenuTextFont, NULL, NULL}, {"IconTitleFont", DEF_ICON_TITLE_FONT, NULL, NULL, getFont, setIconTitleFont, NULL, NULL}, {"ClipTitleFont", DEF_CLIP_TITLE_FONT, NULL, NULL, getFont, setClipTitleFont, NULL, NULL}, {"ShowClipTitle", "YES", NULL, &wPreferences.show_clip_title, getBool, NULL, NULL, NULL}, {"LargeDisplayFont", DEF_WORKSPACE_NAME_FONT, NULL, NULL, getFont, setLargeDisplayFont, NULL, NULL}, {"HighlightColor", "white", NULL, NULL, getColor, setHightlight, NULL, NULL}, {"HighlightTextColor", "black", NULL, NULL, getColor, setHightlightText, NULL, NULL}, {"ClipTitleColor", "black", (void *)CLIP_NORMAL, NULL, getColor, setClipTitleColor, NULL, NULL}, {"CClipTitleColor", "\"rgb:61/61/61\"", (void *)CLIP_COLLAPSED, NULL, getColor, setClipTitleColor, NULL, NULL}, {"FTitleColor", "white", (void *)WS_FOCUSED, NULL, getColor, setWTitleColor, NULL, NULL}, {"PTitleColor", "white", (void *)WS_PFOCUSED, NULL, getColor, setWTitleColor, NULL, NULL}, {"UTitleColor", "black", (void *)WS_UNFOCUSED, NULL, getColor, setWTitleColor, NULL, NULL}, {"FTitleBack", "(solid, black)", NULL, NULL, getTexture, setFTitleBack, NULL, NULL}, {"PTitleBack", "(solid, gray40)", NULL, NULL, getTexture, setPTitleBack, NULL, NULL}, {"UTitleBack", "(solid, \"rgb:aa/aa/aa\")", NULL, NULL, getTexture, setUTitleBack, NULL, NULL}, {"ResizebarBack", "(solid, \"rgb:aa/aa/aa\")", NULL, NULL, getTexture, setResizebarBack, NULL, NULL}, {"MenuTitleColor", "white", NULL, NULL, getColor, setMenuTitleColor, NULL, NULL}, {"MenuTextColor", "black", NULL, NULL, getColor, setMenuTextColor, NULL, NULL}, {"MenuDisabledColor", "gray50", NULL, NULL, getColor, setMenuDisabledColor, NULL, NULL}, {"MenuTitleBack", "(solid, black)", NULL, NULL, getTexture, setMenuTitleBack, NULL, NULL}, {"MenuTextBack", "(solid, \"rgb:aa/aa/aa\")", NULL, NULL, getTexture, setMenuTextBack, NULL, NULL}, {"IconTitleColor", "white", NULL, NULL, getColor, setIconTitleColor, NULL, NULL}, {"IconTitleBack", "black", NULL, NULL, getColor, setIconTitleBack, NULL, NULL}, {"SwitchPanelImages", "(swtile.png, swback.png, 30, 40)", &wPreferences, NULL, getPropList, setSwPOptions, NULL, NULL}, {"ModifierKeyLabels", "(\"Shift+\", \"Control+\", \"Mod1+\", \"Mod2+\", \"Mod3+\", \"Mod4+\", \"Mod5+\")", &wPreferences, NULL, getPropList, setModifierKeyLabels, NULL, NULL}, {"FrameBorderWidth", "1", NULL, NULL, getInt, setFrameBorderWidth, NULL, NULL}, {"FrameBorderColor", "black", NULL, NULL, getColor, setFrameBorderColor, NULL, NULL}, {"FrameFocusedBorderColor", "black", NULL, NULL, getColor, setFrameFocusedBorderColor, NULL, NULL}, {"FrameSelectedBorderColor", "white", NULL, NULL, getColor, setFrameSelectedBorderColor, NULL, NULL}, {"WorkspaceMapBack", "(solid, black)", NULL, NULL, getTexture, setWorkspaceMapBackground, NULL, NULL}, /* keybindings */ {"RootMenuKey", "F12", (void *)WKBD_ROOTMENU, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowListKey", "F11", (void *)WKBD_WINDOWLIST, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowMenuKey", "Control+Escape", (void *)WKBD_WINDOWMENU, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"DockRaiseLowerKey", "None", (void*)WKBD_DOCKRAISELOWER, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"ClipRaiseLowerKey", "None", (void *)WKBD_CLIPRAISELOWER, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MiniaturizeKey", "Mod1+M", (void *)WKBD_MINIATURIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MinimizeAllKey", "None", (void *)WKBD_MINIMIZEALL, NULL, getKeybind, setKeyGrab, NULL, NULL }, {"HideKey", "Mod1+H", (void *)WKBD_HIDE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"HideOthersKey", "None", (void *)WKBD_HIDE_OTHERS, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveResizeKey", "None", (void *)WKBD_MOVERESIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"CloseKey", "None", (void *)WKBD_CLOSE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MaximizeKey", "None", (void *)WKBD_MAXIMIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"VMaximizeKey", "None", (void *)WKBD_VMAXIMIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"HMaximizeKey", "None", (void *)WKBD_HMAXIMIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"LHMaximizeKey", "None", (void*)WKBD_LHMAXIMIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"RHMaximizeKey", "None", (void*)WKBD_RHMAXIMIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"THMaximizeKey", "None", (void*)WKBD_THMAXIMIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"BHMaximizeKey", "None", (void*)WKBD_BHMAXIMIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"LTCMaximizeKey", "None", (void*)WKBD_LTCMAXIMIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"RTCMaximizeKey", "None", (void*)WKBD_RTCMAXIMIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"LBCMaximizeKey", "None", (void*)WKBD_LBCMAXIMIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"RBCMaximizeKey", "None", (void*)WKBD_RBCMAXIMIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MaximusKey", "None", (void*)WKBD_MAXIMUS, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"KeepOnTopKey", "None", (void *)WKBD_KEEP_ON_TOP, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"KeepAtBottomKey", "None", (void *)WKBD_KEEP_AT_BOTTOM, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"OmnipresentKey", "None", (void *)WKBD_OMNIPRESENT, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"RaiseKey", "Mod1+Up", (void *)WKBD_RAISE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"LowerKey", "Mod1+Down", (void *)WKBD_LOWER, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"RaiseLowerKey", "None", (void *)WKBD_RAISELOWER, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"ShadeKey", "None", (void *)WKBD_SHADE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"SelectKey", "None", (void *)WKBD_SELECT, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WorkspaceMapKey", "None", (void *)WKBD_WORKSPACEMAP, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"FocusNextKey", "Mod1+Tab", (void *)WKBD_FOCUSNEXT, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"FocusPrevKey", "Mod1+Shift+Tab", (void *)WKBD_FOCUSPREV, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"GroupNextKey", "None", (void *)WKBD_GROUPNEXT, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"GroupPrevKey", "None", (void *)WKBD_GROUPPREV, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"NextWorkspaceKey", "Mod1+Control+Right", (void *)WKBD_NEXTWORKSPACE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"PrevWorkspaceKey", "Mod1+Control+Left", (void *)WKBD_PREVWORKSPACE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"LastWorkspaceKey", "None", (void *)WKBD_LASTWORKSPACE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"NextWorkspaceLayerKey", "None", (void *)WKBD_NEXTWSLAYER, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"PrevWorkspaceLayerKey", "None", (void *)WKBD_PREVWSLAYER, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"Workspace1Key", "Mod1+1", (void *)WKBD_WORKSPACE1, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"Workspace2Key", "Mod1+2", (void *)WKBD_WORKSPACE2, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"Workspace3Key", "Mod1+3", (void *)WKBD_WORKSPACE3, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"Workspace4Key", "Mod1+4", (void *)WKBD_WORKSPACE4, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"Workspace5Key", "Mod1+5", (void *)WKBD_WORKSPACE5, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"Workspace6Key", "Mod1+6", (void *)WKBD_WORKSPACE6, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"Workspace7Key", "Mod1+7", (void *)WKBD_WORKSPACE7, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"Workspace8Key", "Mod1+8", (void *)WKBD_WORKSPACE8, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"Workspace9Key", "Mod1+9", (void *)WKBD_WORKSPACE9, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"Workspace10Key", "Mod1+0", (void *)WKBD_WORKSPACE10, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToWorkspace1Key", "None", (void *)WKBD_MOVE_WORKSPACE1, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToWorkspace2Key", "None", (void *)WKBD_MOVE_WORKSPACE2, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToWorkspace3Key", "None", (void *)WKBD_MOVE_WORKSPACE3, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToWorkspace4Key", "None", (void *)WKBD_MOVE_WORKSPACE4, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToWorkspace5Key", "None", (void *)WKBD_MOVE_WORKSPACE5, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToWorkspace6Key", "None", (void *)WKBD_MOVE_WORKSPACE6, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToWorkspace7Key", "None", (void *)WKBD_MOVE_WORKSPACE7, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToWorkspace8Key", "None", (void *)WKBD_MOVE_WORKSPACE8, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToWorkspace9Key", "None", (void *)WKBD_MOVE_WORKSPACE9, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToWorkspace10Key", "None", (void *)WKBD_MOVE_WORKSPACE10, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToNextWorkspaceKey", "None", (void *)WKBD_MOVE_NEXTWORKSPACE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToPrevWorkspaceKey", "None", (void *)WKBD_MOVE_PREVWORKSPACE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToLastWorkspaceKey", "None", (void *)WKBD_MOVE_LASTWORKSPACE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToNextWorkspaceLayerKey", "None", (void *)WKBD_MOVE_NEXTWSLAYER, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToPrevWorkspaceLayerKey", "None", (void *)WKBD_MOVE_PREVWSLAYER, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowShortcut1Key", "None", (void *)WKBD_WINDOW1, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowShortcut2Key", "None", (void *)WKBD_WINDOW2, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowShortcut3Key", "None", (void *)WKBD_WINDOW3, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowShortcut4Key", "None", (void *)WKBD_WINDOW4, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowShortcut5Key", "None", (void *)WKBD_WINDOW5, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowShortcut6Key", "None", (void *)WKBD_WINDOW6, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowShortcut7Key", "None", (void *)WKBD_WINDOW7, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowShortcut8Key", "None", (void *)WKBD_WINDOW8, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowShortcut9Key", "None", (void *)WKBD_WINDOW9, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowShortcut10Key", "None", (void *)WKBD_WINDOW10, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveTo12to6Head", "None", (void *)WKBD_MOVE_12_TO_6_HEAD, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveTo6to12Head", "None", (void *)WKBD_MOVE_6_TO_12_HEAD, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowRelaunchKey", "None", (void *)WKBD_RELAUNCH, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"ScreenSwitchKey", "None", (void *)WKBD_SWITCH_SCREEN, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"RunKey", "None", (void *)WKBD_RUN, NULL, getKeybind, setKeyGrab, NULL, NULL}, #ifdef KEEP_XKB_LOCK_STATUS {"ToggleKbdModeKey", "None", (void *)WKBD_TOGGLE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"KbdModeLock", "NO", NULL, &wPreferences.modelock, getBool, NULL, NULL, NULL}, #endif /* KEEP_XKB_LOCK_STATUS */ {"NormalCursor", "(builtin, left_ptr)", (void *)WCUR_ROOT, NULL, getCursor, setCursor, NULL, NULL}, {"ArrowCursor", "(builtin, top_left_arrow)", (void *)WCUR_ARROW, NULL, getCursor, setCursor, NULL, NULL}, {"MoveCursor", "(builtin, fleur)", (void *)WCUR_MOVE, NULL, getCursor, setCursor, NULL, NULL}, {"ResizeCursor", "(builtin, sizing)", (void *)WCUR_RESIZE, NULL, getCursor, setCursor, NULL, NULL}, {"TopLeftResizeCursor", "(builtin, top_left_corner)", (void *)WCUR_TOPLEFTRESIZE, NULL, getCursor, setCursor, NULL, NULL}, {"TopRightResizeCursor", "(builtin, top_right_corner)", (void *)WCUR_TOPRIGHTRESIZE, NULL, getCursor, setCursor, NULL, NULL}, {"BottomLeftResizeCursor", "(builtin, bottom_left_corner)", (void *)WCUR_BOTTOMLEFTRESIZE, NULL, getCursor, setCursor, NULL, NULL}, {"BottomRightResizeCursor", "(builtin, bottom_right_corner)", (void *)WCUR_BOTTOMRIGHTRESIZE, NULL, getCursor, setCursor, NULL, NULL}, {"VerticalResizeCursor", "(builtin, sb_v_double_arrow)", (void *)WCUR_VERTICALRESIZE, NULL, getCursor, setCursor, NULL, NULL}, {"HorizontalResizeCursor", "(builtin, sb_h_double_arrow)", (void *)WCUR_HORIZONRESIZE, NULL, getCursor, setCursor, NULL, NULL}, {"WaitCursor", "(builtin, watch)", (void *)WCUR_WAIT, NULL, getCursor, setCursor, NULL, NULL}, {"QuestionCursor", "(builtin, question_arrow)", (void *)WCUR_QUESTION, NULL, getCursor, setCursor, NULL, NULL}, {"TextCursor", "(builtin, xterm)", (void *)WCUR_TEXT, NULL, getCursor, setCursor, NULL, NULL}, {"SelectCursor", "(builtin, cross)", (void *)WCUR_SELECT, NULL, getCursor, setCursor, NULL, NULL}, {"DialogHistoryLines", "500", NULL, &wPreferences.history_lines, getInt, NULL, NULL, NULL}, {"CycleActiveHeadOnly", "NO", NULL, &wPreferences.cycle_active_head_only, getBool, NULL, NULL, NULL}, {"CycleIgnoreMinimized", "NO", NULL, &wPreferences.cycle_ignore_minimized, getBool, NULL, NULL, NULL}, {"DbClickFullScreen", "NO", NULL, - &wPreferences.double_click_fullscreen, getBool, NULL, NULL, NULL} + &wPreferences.double_click_fullscreen, getBool, NULL, NULL, NULL}, + {"CloseRootMenuByLeftOrRightMouseClick", "NO", NULL, + &wPreferences.close_rootmenu_left_right_click, getBool, NULL, NULL, NULL} }; static void initDefaults(void) { unsigned int i; WDefaultEntry *entry; WMPLSetCaseSensitive(False); for (i = 0; i < wlengthof(optionList); i++) { entry = &optionList[i]; entry->plkey = WMCreatePLString(entry->key); if (entry->default_value) entry->plvalue = WMCreatePropListFromDescription(entry->default_value); else entry->plvalue = NULL; } for (i = 0; i < wlengthof(staticOptionList); i++) { entry = &staticOptionList[i]; entry->plkey = WMCreatePLString(entry->key); if (entry->default_value) entry->plvalue = WMCreatePropListFromDescription(entry->default_value); else entry->plvalue = NULL; } } static WMPropList *readGlobalDomain(const char *domainName, Bool requireDictionary) { WMPropList *globalDict = NULL; char path[PATH_MAX]; struct stat stbuf; snprintf(path, sizeof(path), "%s/%s", DEFSDATADIR, domainName); if (stat(path, &stbuf) >= 0) { globalDict = WMReadPropListFromFile(path); if (globalDict && requireDictionary && !WMIsPLDictionary(globalDict)) { wwarning(_("Domain %s (%s) of global defaults database is corrupted!"), domainName, path); WMReleasePropList(globalDict); globalDict = NULL; } else if (!globalDict) { wwarning(_("could not load domain %s from global defaults database"), domainName); } } return globalDict; } #if defined(GLOBAL_PREAMBLE_MENU_FILE) || defined(GLOBAL_EPILOGUE_MENU_FILE) static void prependMenu(WMPropList * destarr, WMPropList * array) { WMPropList *item; int i; for (i = 0; i < WMGetPropListItemCount(array); i++) { item = WMGetFromPLArray(array, i); if (item) WMInsertInPLArray(destarr, i + 1, item); } } static void appendMenu(WMPropList * destarr, WMPropList * array) { WMPropList *item; int i; for (i = 0; i < WMGetPropListItemCount(array); i++) { item = WMGetFromPLArray(array, i); if (item) WMAddToPLArray(destarr, item); } } #endif void wDefaultsMergeGlobalMenus(WDDomain * menuDomain) { WMPropList *menu = menuDomain->dictionary; WMPropList *submenu; if (!menu || !WMIsPLArray(menu)) return; #ifdef GLOBAL_PREAMBLE_MENU_FILE submenu = WMReadPropListFromFile(DEFSDATADIR "/" GLOBAL_PREAMBLE_MENU_FILE); if (submenu && !WMIsPLArray(submenu)) { wwarning(_("invalid global menu file %s"), GLOBAL_PREAMBLE_MENU_FILE); WMReleasePropList(submenu); submenu = NULL; } if (submenu) { prependMenu(menu, submenu); WMReleasePropList(submenu); } #endif #ifdef GLOBAL_EPILOGUE_MENU_FILE submenu = WMReadPropListFromFile(DEFSDATADIR "/" GLOBAL_EPILOGUE_MENU_FILE); if (submenu && !WMIsPLArray(submenu)) { wwarning(_("invalid global menu file %s"), GLOBAL_EPILOGUE_MENU_FILE); WMReleasePropList(submenu); submenu = NULL; } if (submenu) { appendMenu(menu, submenu); WMReleasePropList(submenu); } #endif menuDomain->dictionary = menu; } WDDomain *wDefaultsInitDomain(const char *domain, Bool requireDictionary) { WDDomain *db; struct stat stbuf; static int inited = 0; WMPropList *shared_dict = NULL; if (!inited) { inited = 1; initDefaults(); } db = wmalloc(sizeof(WDDomain)); db->domain_name = domain; db->path = wdefaultspathfordomain(domain); if (stat(db->path, &stbuf) >= 0) { db->dictionary = WMReadPropListFromFile(db->path); if (db->dictionary) { if (requireDictionary && !WMIsPLDictionary(db->dictionary)) { WMReleasePropList(db->dictionary); db->dictionary = NULL; wwarning(_("Domain %s (%s) of defaults database is corrupted!"), domain, db->path); } db->timestamp = stbuf.st_mtime; } else { wwarning(_("could not load domain %s from user defaults database"), domain); } } /* global system dictionary */ shared_dict = readGlobalDomain(domain, requireDictionary); if (shared_dict && db->dictionary && WMIsPLDictionary(shared_dict) && WMIsPLDictionary(db->dictionary)) { WMMergePLDictionaries(shared_dict, db->dictionary, True); WMReleasePropList(db->dictionary); db->dictionary = shared_dict; if (stbuf.st_mtime > db->timestamp) db->timestamp = stbuf.st_mtime; } else if (!db->dictionary) { db->dictionary = shared_dict; if (stbuf.st_mtime > db->timestamp) db->timestamp = stbuf.st_mtime; } return db; } void wReadStaticDefaults(WMPropList * dict) { WMPropList *plvalue; WDefaultEntry *entry; unsigned int i; void *tdata; for (i = 0; i < wlengthof(staticOptionList); i++) { entry = &staticOptionList[i]; if (dict) plvalue = WMGetFromPLDictionary(dict, entry->plkey); else plvalue = NULL; /* no default in the DB. Use builtin default */ if (!plvalue) plvalue = entry->plvalue; if (plvalue) { /* convert data */ (*entry->convert) (NULL, entry, plvalue, entry->addr, &tdata); if (entry->update) (*entry->update) (NULL, entry, tdata, entry->extra_data); } } } void wDefaultsCheckDomains(void* arg) { WScreen *scr; struct stat stbuf; WMPropList *shared_dict = NULL; WMPropList *dict; int i; /* Parameter not used, but tell the compiler that it is ok */ (void) arg; if (stat(w_global.domain.wmaker->path, &stbuf) >= 0 && w_global.domain.wmaker->timestamp < stbuf.st_mtime) { w_global.domain.wmaker->timestamp = stbuf.st_mtime; /* Global dictionary */ shared_dict = readGlobalDomain("WindowMaker", True); /* User dictionary */ dict = WMReadPropListFromFile(w_global.domain.wmaker->path); if (dict) { if (!WMIsPLDictionary(dict)) { WMReleasePropList(dict); dict = NULL; wwarning(_("Domain %s (%s) of defaults database is corrupted!"), "WindowMaker", w_global.domain.wmaker->path); } else { if (shared_dict) { WMMergePLDictionaries(shared_dict, dict, True); WMReleasePropList(dict); dict = shared_dict; shared_dict = NULL; } for (i = 0; i < w_global.screen_count; i++) { scr = wScreenWithNumber(i); if (scr) wReadDefaults(scr, dict); } if (w_global.domain.wmaker->dictionary) WMReleasePropList(w_global.domain.wmaker->dictionary); w_global.domain.wmaker->dictionary = dict; } } else { wwarning(_("could not load domain %s from user defaults database"), "WindowMaker"); } if (shared_dict) WMReleasePropList(shared_dict); } if (stat(w_global.domain.window_attr->path, &stbuf) >= 0 && w_global.domain.window_attr->timestamp < stbuf.st_mtime) { /* global dictionary */ shared_dict = readGlobalDomain("WMWindowAttributes", True); /* user dictionary */ dict = WMReadPropListFromFile(w_global.domain.window_attr->path); if (dict) { if (!WMIsPLDictionary(dict)) { WMReleasePropList(dict); dict = NULL; wwarning(_("Domain %s (%s) of defaults database is corrupted!"), "WMWindowAttributes", w_global.domain.window_attr->path); } else { if (shared_dict) { WMMergePLDictionaries(shared_dict, dict, True); WMReleasePropList(dict); dict = shared_dict; shared_dict = NULL; } if (w_global.domain.window_attr->dictionary) WMReleasePropList(w_global.domain.window_attr->dictionary); w_global.domain.window_attr->dictionary = dict; for (i = 0; i < w_global.screen_count; i++) { scr = wScreenWithNumber(i); if (scr) { wDefaultUpdateIcons(scr); /* Update the panel image if changed */ /* Don't worry. If the image is the same these * functions will have no performance impact. */ create_logo_image(scr); } } } } else { wwarning(_("could not load domain %s from user defaults database"), "WMWindowAttributes"); } w_global.domain.window_attr->timestamp = stbuf.st_mtime; if (shared_dict) WMReleasePropList(shared_dict); } if (stat(w_global.domain.root_menu->path, &stbuf) >= 0 && w_global.domain.root_menu->timestamp < stbuf.st_mtime) { dict = WMReadPropListFromFile(w_global.domain.root_menu->path); if (dict) { if (!WMIsPLArray(dict) && !WMIsPLString(dict)) { WMReleasePropList(dict); dict = NULL; wwarning(_("Domain %s (%s) of defaults database is corrupted!"), "WMRootMenu", w_global.domain.root_menu->path); } else { if (w_global.domain.root_menu->dictionary) WMReleasePropList(w_global.domain.root_menu->dictionary); w_global.domain.root_menu->dictionary = dict; wDefaultsMergeGlobalMenus(w_global.domain.root_menu); } } else { wwarning(_("could not load domain %s from user defaults database"), "WMRootMenu"); } w_global.domain.root_menu->timestamp = stbuf.st_mtime; } #ifndef HAVE_INOTIFY if (!arg) WMAddTimerHandler(DEFAULTS_CHECK_INTERVAL, wDefaultsCheckDomains, arg); #endif } void wReadDefaults(WScreen * scr, WMPropList * new_dict) { WMPropList *plvalue, *old_value; WDefaultEntry *entry; unsigned int i; int update_workspace_back = 0; /* kluge :/ */ unsigned int needs_refresh; void *tdata; WMPropList *old_dict = (w_global.domain.wmaker->dictionary != new_dict ? w_global.domain.wmaker->dictionary : NULL); needs_refresh = 0; for (i = 0; i < wlengthof(optionList); i++) { entry = &optionList[i]; if (new_dict) plvalue = WMGetFromPLDictionary(new_dict, entry->plkey); else plvalue = NULL; if (!old_dict) old_value = NULL; else old_value = WMGetFromPLDictionary(old_dict, entry->plkey); if (!plvalue && !old_value) { /* no default in the DB. Use builtin default */ plvalue = entry->plvalue; if (plvalue && new_dict) WMPutInPLDictionary(new_dict, entry->plkey, plvalue); } else if (!plvalue) { /* value was deleted from DB. Keep current value */ continue; } else if (!old_value) { /* set value for the 1st time */ } else if (!WMIsPropListEqualTo(plvalue, old_value)) { /* value has changed */ } else { if (strcmp(entry->key, "WorkspaceBack") == 0 && update_workspace_back && scr->flags.backimage_helper_launched) { } else { /* value was not changed since last time */ continue; } } if (plvalue) { /* convert data */ if ((*entry->convert) (scr, entry, plvalue, entry->addr, &tdata)) { /* * If the WorkspaceSpecificBack data has been changed * so that the helper will be launched now, we must be * sure to send the default background texture config * to the helper. */ if (strcmp(entry->key, "WorkspaceSpecificBack") == 0 && !scr->flags.backimage_helper_launched) update_workspace_back = 1; if (entry->update) needs_refresh |= (*entry->update) (scr, entry, tdata, entry->extra_data); } } } if (needs_refresh != 0 && !scr->flags.startup) { int foo; foo = 0; if (needs_refresh & REFRESH_MENU_TITLE_TEXTURE) foo |= WTextureSettings; if (needs_refresh & REFRESH_MENU_TITLE_FONT) foo |= WFontSettings; if (needs_refresh & REFRESH_MENU_TITLE_COLOR) foo |= WColorSettings; if (foo) WMPostNotificationName(WNMenuTitleAppearanceSettingsChanged, NULL, (void *)(uintptr_t) foo); foo = 0; if (needs_refresh & REFRESH_MENU_TEXTURE) foo |= WTextureSettings; if (needs_refresh & REFRESH_MENU_FONT) foo |= WFontSettings; if (needs_refresh & REFRESH_MENU_COLOR) foo |= WColorSettings; if (foo) WMPostNotificationName(WNMenuAppearanceSettingsChanged, NULL, (void *)(uintptr_t) foo); foo = 0; if (needs_refresh & REFRESH_WINDOW_FONT) foo |= WFontSettings; if (needs_refresh & REFRESH_WINDOW_TEXTURES) foo |= WTextureSettings; if (needs_refresh & REFRESH_WINDOW_TITLE_COLOR) foo |= WColorSettings; if (foo) WMPostNotificationName(WNWindowAppearanceSettingsChanged, NULL, (void *)(uintptr_t) foo); if (!(needs_refresh & REFRESH_ICON_TILE)) { foo = 0; if (needs_refresh & REFRESH_ICON_FONT) foo |= WFontSettings; if (needs_refresh & REFRESH_ICON_TITLE_COLOR) foo |= WTextureSettings; if (needs_refresh & REFRESH_ICON_TITLE_BACK) foo |= WTextureSettings; if (foo) WMPostNotificationName(WNIconAppearanceSettingsChanged, NULL, (void *)(uintptr_t) foo); } if (needs_refresh & REFRESH_ICON_TILE) WMPostNotificationName(WNIconTileSettingsChanged, NULL, NULL); if (needs_refresh & REFRESH_WORKSPACE_MENU) { if (scr->workspace_menu) wWorkspaceMenuUpdate(scr, scr->workspace_menu); if (scr->clip_ws_menu) wWorkspaceMenuUpdate(scr, scr->clip_ws_menu); if (scr->workspace_submenu) scr->workspace_submenu->flags.realized = 0; if (scr->clip_submenu) scr->clip_submenu->flags.realized = 0; } } } void wDefaultUpdateIcons(WScreen *scr) { WAppIcon *aicon = scr->app_icon_list; WDrawerChain *dc; WWindow *wwin = scr->focused_window; while (aicon) { /* Get the application icon, default included */ wIconChangeImageFile(aicon->icon, NULL); wAppIconPaint(aicon); aicon = aicon->next; } if (!wPreferences.flags.noclip || wPreferences.flags.clip_merged_in_dock) wClipIconPaint(scr->clip_icon); for (dc = scr->drawers; dc != NULL; dc = dc->next) wDrawerIconPaint(dc->adrawer->icon_array[0]); while (wwin) { if (wwin->icon && wwin->flags.miniaturized) wIconChangeImageFile(wwin->icon, NULL); wwin = wwin->prev; } } /* --------------------------- Local ----------------------- */ #define GET_STRING_OR_DEFAULT(x, var) if (!WMIsPLString(value)) { \ wwarning(_("Wrong option format for key \"%s\". Should be %s."), \ entry->key, x); \ wwarning(_("using default \"%s\" instead"), entry->default_value); \ var = entry->default_value;\ } else var = WMGetFromPLString(value)\ static int string2index(WMPropList *key, WMPropList *val, const char *def, WOptionEnumeration * values) { char *str; WOptionEnumeration *v; char buffer[TOTAL_VALUES_LENGTH]; if (WMIsPLString(val) && (str = WMGetFromPLString(val))) { for (v = values; v->string != NULL; v++) { if (strcasecmp(v->string, str) == 0) return v->value; } } buffer[0] = 0; for (v = values; v->string != NULL; v++) { if (!v->is_alias) { if (buffer[0] != 0) strcat(buffer, ", "); snprintf(buffer+strlen(buffer), sizeof(buffer)-strlen(buffer)-1, "\"%s\"", v->string); } } wwarning(_("wrong option value for key \"%s\"; got \"%s\", should be one of %s."), WMGetFromPLString(key), WMIsPLString(val) ? WMGetFromPLString(val) : "(unknown)", buffer); if (def) { return string2index(key, val, NULL, values); } diff --git a/src/event.c b/src/event.c index 007b10b..f5014e3 100644 --- a/src/event.c +++ b/src/event.c @@ -250,1024 +250,1036 @@ void DispatchEvent(XEvent * event) break; case ClientMessage: handleClientMessage(event); break; case ColormapNotify: handleColormapNotify(event); break; case MappingNotify: if (event->xmapping.request == MappingKeyboard || event->xmapping.request == MappingModifier) XRefreshKeyboardMapping(&event->xmapping); break; case FocusIn: handleFocusIn(event); break; case VisibilityNotify: handleVisibilityNotify(event); break; case ConfigureNotify: #ifdef USE_RANDR if (event->xconfigure.window == DefaultRootWindow(dpy)) XRRUpdateConfiguration(event); #endif break; case SelectionRequest: handle_selection_request(&event->xselectionrequest); break; case SelectionClear: handle_selection_clear(&event->xselectionclear); break; default: handleExtensions(event); break; } } #ifdef HAVE_INOTIFY /* *---------------------------------------------------------------------- * handle_inotify_events- * Check for inotify events * * Returns: * After reading events for the given file descriptor (fd) and * watch descriptor (wd) * * Side effects: * Calls wDefaultsCheckDomains if config database is updated *---------------------------------------------------------------------- */ static void handle_inotify_events(void) { ssize_t eventQLength; size_t i = 0; /* Make room for at lease 5 simultaneous events, with path + filenames */ char buff[ (sizeof(struct inotify_event) + NAME_MAX + 1) * 5 ]; /* Check config only once per read of the event queue */ int oneShotFlag = 0; /* * Read off the queued events * queue overflow is not checked (IN_Q_OVERFLOW). In practise this should * not occur; the block is on Xevents, but a config file change will normally * occur as a result of an Xevent - so the event queue should never have more than * a few entries before a read(). */ eventQLength = read(w_global.inotify.fd_event_queue, buff, sizeof(buff) ); if (eventQLength < 0) { wwarning(_("read problem when trying to get INotify event: %s"), strerror(errno)); return; } /* check what events occurred */ /* Should really check wd here too, but for now we only have one watch! */ while (i < eventQLength) { struct inotify_event *pevent = (struct inotify_event *)&buff[i]; /* * see inotify.h for event types. */ if (pevent->mask & IN_DELETE_SELF) { wwarning(_("the defaults database has been deleted!" " Restart Window Maker to create the database" " with the default settings")); if (w_global.inotify.fd_event_queue >= 0) { close(w_global.inotify.fd_event_queue); w_global.inotify.fd_event_queue = -1; } } if (pevent->mask & IN_UNMOUNT) { wwarning(_("the unit containing the defaults database has" " been unmounted. Setting --static mode." " Any changes will not be saved.")); if (w_global.inotify.fd_event_queue >= 0) { close(w_global.inotify.fd_event_queue); w_global.inotify.fd_event_queue = -1; } wPreferences.flags.noupdates = 1; } if ((pevent->mask & IN_MODIFY) && oneShotFlag == 0) { wwarning(_("Inotify: Reading config files in defaults database.")); wDefaultsCheckDomains(NULL); oneShotFlag = 1; } /* move to next event in the buffer */ i += sizeof(struct inotify_event) + pevent->len; } } #endif /* HAVE_INOTIFY */ /* *---------------------------------------------------------------------- * EventLoop- * Processes X and internal events indefinitely. * * Returns: * Never returns * * Side effects: * The LastTimestamp global variable is updated. * Calls inotifyGetEvents if defaults database changes. *---------------------------------------------------------------------- */ noreturn void EventLoop(void) { XEvent event; #ifdef HAVE_INOTIFY struct timeval time; fd_set rfds; int retVal = 0; if (w_global.inotify.fd_event_queue < 0 || w_global.inotify.wd_defaults < 0) retVal = -1; #endif for (;;) { WMNextEvent(dpy, &event); /* Blocks here */ WMHandleEvent(&event); #ifdef HAVE_INOTIFY if (retVal != -1) { time.tv_sec = 0; time.tv_usec = 0; FD_ZERO(&rfds); FD_SET(w_global.inotify.fd_event_queue, &rfds); /* check for available read data from inotify - don't block! */ retVal = select(w_global.inotify.fd_event_queue + 1, &rfds, NULL, NULL, &time); if (retVal < 0) { /* an error has occurred */ wwarning(_("select failed. The inotify instance will be closed." " Changes to the defaults database will require" " a restart to take effect.")); close(w_global.inotify.fd_event_queue); w_global.inotify.fd_event_queue = -1; continue; } if (FD_ISSET(w_global.inotify.fd_event_queue, &rfds)) handle_inotify_events(); } #endif } } /* *---------------------------------------------------------------------- * ProcessPendingEvents -- * Processes the events that are currently pending (at the time * this function is called) in the display's queue. * * Returns: * After the pending events that were present at the function call * are processed. * * Side effects: * Many -- whatever handling events may involve. * *---------------------------------------------------------------------- */ void ProcessPendingEvents(void) { XEvent event; int count; XSync(dpy, False); /* Take a snapshot of the event count in the queue */ count = XPending(dpy); while (count > 0 && XPending(dpy)) { WMNextEvent(dpy, &event); WMHandleEvent(&event); count--; } } Bool IsDoubleClick(WScreen * scr, XEvent * event) { if ((scr->last_click_time > 0) && (event->xbutton.time - scr->last_click_time <= wPreferences.dblclick_time) && (event->xbutton.button == scr->last_click_button) && (event->xbutton.window == scr->last_click_window)) { scr->flags.next_click_is_not_double = 1; scr->last_click_time = 0; scr->last_click_window = event->xbutton.window; return True; } return False; } void NotifyDeadProcess(pid_t pid, unsigned char status) { if (deadProcessPtr >= MAX_DEAD_PROCESSES - 1) { wwarning("stack overflow: too many dead processes"); return; } /* stack the process to be handled later, * as this is called from the signal handler */ deadProcesses[deadProcessPtr].pid = pid; deadProcesses[deadProcessPtr].exit_status = status; deadProcessPtr++; } static void handleDeadProcess(void) { DeathHandler *tmp; int i; for (i = 0; i < deadProcessPtr; i++) { wWindowDeleteSavedStatesForPID(deadProcesses[i].pid); } if (!deathHandlers) { deadProcessPtr = 0; return; } /* get the pids on the queue and call handlers */ while (deadProcessPtr > 0) { deadProcessPtr--; for (i = WMGetArrayItemCount(deathHandlers) - 1; i >= 0; i--) { tmp = WMGetFromArray(deathHandlers, i); if (!tmp) continue; if (tmp->pid == deadProcesses[deadProcessPtr].pid) { (*tmp->callback) (tmp->pid, deadProcesses[deadProcessPtr].exit_status, tmp->client_data); wdelete_death_handler(tmp); } } } } static void saveTimestamp(XEvent * event) { /* * Never save CurrentTime as LastTimestamp because CurrentTime * it's not a real timestamp (it's the 0L constant) */ switch (event->type) { case ButtonRelease: case ButtonPress: w_global.timestamp.last_event = event->xbutton.time; break; case KeyPress: case KeyRelease: w_global.timestamp.last_event = event->xkey.time; break; case MotionNotify: w_global.timestamp.last_event = event->xmotion.time; break; case PropertyNotify: w_global.timestamp.last_event = event->xproperty.time; break; case EnterNotify: case LeaveNotify: w_global.timestamp.last_event = event->xcrossing.time; break; case SelectionClear: w_global.timestamp.last_event = event->xselectionclear.time; break; case SelectionRequest: w_global.timestamp.last_event = event->xselectionrequest.time; break; case SelectionNotify: w_global.timestamp.last_event = event->xselection.time; #ifdef USE_DOCK_XDND wXDNDProcessSelection(event); #endif break; } } static int matchWindow(const void *item, const void *cdata) { return (((WFakeGroupLeader *) item)->origLeader == (Window) cdata); } static void handleExtensions(XEvent * event) { #ifdef USE_XSHAPE if (w_global.xext.shape.supported && event->type == (w_global.xext.shape.event_base + ShapeNotify)) { handleShapeNotify(event); } #endif #ifdef KEEP_XKB_LOCK_STATUS if (wPreferences.modelock && (event->type == w_global.xext.xkb.event_base)) { handleXkbIndicatorStateNotify((XkbEvent *) event); } #endif /*KEEP_XKB_LOCK_STATUS */ #ifdef USE_RANDR if (w_global.xext.randr.supported && event->type == (w_global.xext.randr.event_base + RRScreenChangeNotify)) { /* From xrandr man page: "Clients must call back into Xlib using * XRRUpdateConfiguration when screen configuration change notify * events are generated */ XRRUpdateConfiguration(event); WCHANGE_STATE(WSTATE_RESTARTING); Shutdown(WSRestartPreparationMode); Restart(NULL,True); } #endif } static void handleMapRequest(XEvent * ev) { WWindow *wwin; WScreen *scr = NULL; Window window = ev->xmaprequest.window; wwin = wWindowFor(window); if (wwin != NULL) { if (wwin->flags.shaded) { wUnshadeWindow(wwin); } /* deiconify window */ if (wwin->flags.miniaturized) { wDeiconifyWindow(wwin); } else if (wwin->flags.hidden) { WApplication *wapp = wApplicationOf(wwin->main_window); /* go to the last workspace that the user worked on the app */ if (wapp) { wWorkspaceChange(wwin->screen_ptr, wapp->last_workspace); } wUnhideApplication(wapp, False, False); } return; } scr = wScreenForRootWindow(ev->xmaprequest.parent); wwin = wManageWindow(scr, window); /* * This is to let the Dock know that the application it launched * has already been mapped (eg: it has finished launching). * It is not necessary for normally docked apps, but is needed for * apps that were forcedly docked (like with dockit). */ if (scr->last_dock) { if (wwin && wwin->main_window != None && wwin->main_window != window) wDockTrackWindowLaunch(scr->last_dock, wwin->main_window); else wDockTrackWindowLaunch(scr->last_dock, window); } if (wwin) { wClientSetState(wwin, NormalState, None); if (wwin->flags.maximized) { wMaximizeWindow(wwin, wwin->flags.maximized, wGetHeadForWindow(wwin)); } if (wwin->flags.shaded) { wwin->flags.shaded = 0; wwin->flags.skip_next_animation = 1; wShadeWindow(wwin); } if (wwin->flags.miniaturized) { wwin->flags.miniaturized = 0; wwin->flags.skip_next_animation = 1; wIconifyWindow(wwin); } if (wwin->flags.fullscreen) { wwin->flags.fullscreen = 0; wFullscreenWindow(wwin); } if (wwin->flags.hidden) { WApplication *wapp = wApplicationOf(wwin->main_window); wwin->flags.hidden = 0; wwin->flags.skip_next_animation = 1; if (wapp) { wHideApplication(wapp); } } } } static void handleDestroyNotify(XEvent * event) { WWindow *wwin; WApplication *app; Window window = event->xdestroywindow.window; WScreen *scr = wScreenForRootWindow(event->xdestroywindow.event); int widx; wwin = wWindowFor(window); if (wwin) { wUnmanageWindow(wwin, False, True); } if (scr != NULL) { while ((widx = WMFindInArray(scr->fakeGroupLeaders, matchWindow, (void *)window)) != WANotFound) { WFakeGroupLeader *fPtr; fPtr = WMGetFromArray(scr->fakeGroupLeaders, widx); if (fPtr->retainCount > 0) { fPtr->retainCount--; if (fPtr->retainCount == 0 && fPtr->leader != None) { XDestroyWindow(dpy, fPtr->leader); fPtr->leader = None; XFlush(dpy); } } fPtr->origLeader = None; } } app = wApplicationOf(window); if (app) { if (window == app->main_window) { app->refcount = 0; wwin = app->main_window_desc->screen_ptr->focused_window; while (wwin) { if (wwin->main_window == window) { wwin->main_window = None; } wwin = wwin->prev; } } wApplicationDestroy(app); } } static void handleExpose(XEvent * event) { WObjDescriptor *desc; XEvent ev; while (XCheckTypedWindowEvent(dpy, event->xexpose.window, Expose, &ev)) ; if (XFindContext(dpy, event->xexpose.window, w_global.context.client_win, (XPointer *) & desc) == XCNOENT) { return; } if (desc->handle_expose) { (*desc->handle_expose) (desc, event); } } static void executeWheelAction(WScreen *scr, XEvent *event, int action) { WWindow *wwin; Bool next_direction; if (event->xbutton.button == Button5 || event->xbutton.button == Button6) next_direction = False; else next_direction = True; switch (action) { case WA_SWITCH_WORKSPACES: if (next_direction) wWorkspaceRelativeChange(scr, 1); else wWorkspaceRelativeChange(scr, -1); break; case WA_SWITCH_WINDOWS: wwin = scr->focused_window; if (next_direction) wWindowFocusNext(wwin, True); else wWindowFocusPrev(wwin, True); break; } } static void executeButtonAction(WScreen *scr, XEvent *event, int action) { WWindow *wwin; switch (action) { case WA_SELECT_WINDOWS: wUnselectWindows(scr); wSelectWindows(scr, event); + if (wPreferences.close_rootmenu_left_right_click){ + WMenu *menu = NULL; + WMPropList *definition; + menu = scr->root_menu; + if (scr->root_menu){ + wMenuDestroy(menu,True); + scr->root_menu = NULL; + definition = w_global.domain.root_menu->dictionary; + menu = configureMenu(scr, definition); + scr->root_menu = menu; + } + } break; case WA_OPEN_APPMENU: OpenRootMenu(scr, event->xbutton.x_root, event->xbutton.y_root, False); /* ugly hack */ if (scr->root_menu) { if (scr->root_menu->brother->flags.mapped) event->xbutton.window = scr->root_menu->brother->frame->core->window; else event->xbutton.window = scr->root_menu->frame->core->window; } break; case WA_OPEN_WINLISTMENU: OpenSwitchMenu(scr, event->xbutton.x_root, event->xbutton.y_root, False); if (scr->switch_menu) { if (scr->switch_menu->brother->flags.mapped) event->xbutton.window = scr->switch_menu->brother->frame->core->window; else event->xbutton.window = scr->switch_menu->frame->core->window; } break; case WA_MOVE_PREVWORKSPACE: wWorkspaceRelativeChange(scr, -1); break; case WA_MOVE_NEXTWORKSPACE: wWorkspaceRelativeChange(scr, 1); break; case WA_MOVE_PREVWINDOW: wwin = scr->focused_window; wWindowFocusPrev(wwin, True); break; case WA_MOVE_NEXTWINDOW: wwin = scr->focused_window; wWindowFocusNext(wwin, True); break; } } /* bindable */ static void handleButtonPress(XEvent * event) { WObjDescriptor *desc; WScreen *scr; scr = wScreenForRootWindow(event->xbutton.root); #ifdef BALLOON_TEXT wBalloonHide(scr); #endif if (!wPreferences.disable_root_mouse && event->xbutton.window == scr->root_win) { if (event->xbutton.button == Button1 && wPreferences.mouse_button1 != WA_NONE) { executeButtonAction(scr, event, wPreferences.mouse_button1); } else if (event->xbutton.button == Button2 && wPreferences.mouse_button2 != WA_NONE) { executeButtonAction(scr, event, wPreferences.mouse_button2); } else if (event->xbutton.button == Button3 && wPreferences.mouse_button3 != WA_NONE) { executeButtonAction(scr, event, wPreferences.mouse_button3); } else if (event->xbutton.button == Button8 && wPreferences.mouse_button8 != WA_NONE) { executeButtonAction(scr, event, wPreferences.mouse_button8); }else if (event->xbutton.button == Button9 && wPreferences.mouse_button9 != WA_NONE) { executeButtonAction(scr, event, wPreferences.mouse_button9); } else if (event->xbutton.button == Button4 && wPreferences.mouse_wheel_scroll != WA_NONE) { executeWheelAction(scr, event, wPreferences.mouse_wheel_scroll); } else if (event->xbutton.button == Button5 && wPreferences.mouse_wheel_scroll != WA_NONE) { executeWheelAction(scr, event, wPreferences.mouse_wheel_scroll); } else if (event->xbutton.button == Button6 && wPreferences.mouse_wheel_tilt != WA_NONE) { executeWheelAction(scr, event, wPreferences.mouse_wheel_tilt); } else if (event->xbutton.button == Button7 && wPreferences.mouse_wheel_tilt != WA_NONE) { executeWheelAction(scr, event, wPreferences.mouse_wheel_tilt); } } desc = NULL; if (XFindContext(dpy, event->xbutton.subwindow, w_global.context.client_win, (XPointer *) & desc) == XCNOENT) { if (XFindContext(dpy, event->xbutton.window, w_global.context.client_win, (XPointer *) & desc) == XCNOENT) { return; } } if (desc->parent_type == WCLASS_WINDOW) { XSync(dpy, 0); if (event->xbutton.state & ( MOD_MASK | ControlMask )) { XAllowEvents(dpy, AsyncPointer, CurrentTime); } else { /* if (wPreferences.focus_mode == WKF_CLICK) { */ if (wPreferences.ignore_focus_click) { XAllowEvents(dpy, AsyncPointer, CurrentTime); } XAllowEvents(dpy, ReplayPointer, CurrentTime); /* } */ } XSync(dpy, 0); } else if (desc->parent_type == WCLASS_APPICON || desc->parent_type == WCLASS_MINIWINDOW || desc->parent_type == WCLASS_DOCK_ICON) { if (event->xbutton.state & MOD_MASK) { XSync(dpy, 0); XAllowEvents(dpy, AsyncPointer, CurrentTime); XSync(dpy, 0); } } if (desc->handle_mousedown != NULL) { (*desc->handle_mousedown) (desc, event); } /* save double-click information */ if (scr->flags.next_click_is_not_double) { scr->flags.next_click_is_not_double = 0; } else { scr->last_click_time = event->xbutton.time; scr->last_click_button = event->xbutton.button; scr->last_click_window = event->xbutton.window; } } static void handleMapNotify(XEvent * event) { WWindow *wwin; wwin = wWindowFor(event->xmap.event); if (wwin && wwin->client_win == event->xmap.event) { if (wwin->flags.miniaturized) { wDeiconifyWindow(wwin); } else { XGrabServer(dpy); wWindowMap(wwin); wClientSetState(wwin, NormalState, None); XUngrabServer(dpy); } } } static void handleUnmapNotify(XEvent * event) { WWindow *wwin; XEvent ev; Bool withdraw = False; /* only process windows with StructureNotify selected * (ignore SubstructureNotify) */ wwin = wWindowFor(event->xunmap.window); if (!wwin) return; /* whether the event is a Withdrawal request */ if (event->xunmap.event == wwin->screen_ptr->root_win && event->xunmap.send_event) withdraw = True; if (wwin->client_win != event->xunmap.event && !withdraw) return; if (!wwin->flags.mapped && !withdraw && wwin->frame->workspace == wwin->screen_ptr->current_workspace && !wwin->flags.miniaturized && !wwin->flags.hidden) return; XGrabServer(dpy); XUnmapWindow(dpy, wwin->frame->core->window); wwin->flags.mapped = 0; XSync(dpy, 0); /* check if the window was destroyed */ if (XCheckTypedWindowEvent(dpy, wwin->client_win, DestroyNotify, &ev)) { DispatchEvent(&ev); } else { Bool reparented = False; if (XCheckTypedWindowEvent(dpy, wwin->client_win, ReparentNotify, &ev)) reparented = True; /* withdraw window */ wwin->flags.mapped = 0; if (!reparented) wClientSetState(wwin, WithdrawnState, None); /* if the window was reparented, do not reparent it back to the * root window */ wUnmanageWindow(wwin, !reparented, False); } XUngrabServer(dpy); } static void handleConfigureRequest(XEvent * event) { WWindow *wwin; wwin = wWindowFor(event->xconfigurerequest.window); if (wwin == NULL) { /* * Configure request for unmapped window */ wClientConfigure(NULL, &(event->xconfigurerequest)); } else { wClientConfigure(wwin, &(event->xconfigurerequest)); } } static void handlePropertyNotify(XEvent * event) { WWindow *wwin; WApplication *wapp; Window jr; int ji; unsigned int ju; wwin = wWindowFor(event->xproperty.window); if (wwin) { if (!XGetGeometry(dpy, wwin->client_win, &jr, &ji, &ji, &ju, &ju, &ju, &ju)) { return; } wClientCheckProperty(wwin, &event->xproperty); } wapp = wApplicationOf(event->xproperty.window); if (wapp) { wClientCheckProperty(wapp->main_window_desc, &event->xproperty); } } static void handleClientMessage(XEvent * event) { WWindow *wwin; WObjDescriptor *desc; /* handle transition from Normal to Iconic state */ if (event->xclient.message_type == w_global.atom.wm.change_state && event->xclient.format == 32 && event->xclient.data.l[0] == IconicState) { wwin = wWindowFor(event->xclient.window); if (!wwin) return; if (!wwin->flags.miniaturized) wIconifyWindow(wwin); } else if (event->xclient.message_type == w_global.atom.wm.colormap_notify && event->xclient.format == 32) { WScreen *scr = wScreenForRootWindow(event->xclient.window); if (!scr) return; if (event->xclient.data.l[1] == 1) { /* starting */ wColormapAllowClientInstallation(scr, True); } else { /* stopping */ wColormapAllowClientInstallation(scr, False); } } else if (event->xclient.message_type == w_global.atom.wmaker.command) { char *command; size_t len; len = sizeof(event->xclient.data.b); command = wmalloc(len + 1); strncpy(command, event->xclient.data.b, len); if (strncmp(command, "Reconfigure", sizeof("Reconfigure")) == 0) { wwarning(_("Got Reconfigure command")); wDefaultsCheckDomains(NULL); } else { wwarning(_("Got unknown command %s"), command); } wfree(command); } else if (event->xclient.message_type == w_global.atom.wmaker.wm_function) { WApplication *wapp; int done = 0; wapp = wApplicationOf(event->xclient.window); if (wapp) { switch (event->xclient.data.l[0]) { case WMFHideOtherApplications: wHideOtherApplications(wapp->main_window_desc); done = 1; break; case WMFHideApplication: wHideApplication(wapp); done = 1; break; } } if (!done) { wwin = wWindowFor(event->xclient.window); if (wwin) { switch (event->xclient.data.l[0]) { case WMFHideOtherApplications: wHideOtherApplications(wwin); break; case WMFHideApplication: wHideApplication(wApplicationOf(wwin->main_window)); break; } } } } else if (event->xclient.message_type == w_global.atom.gnustep.wm_attr) { wwin = wWindowFor(event->xclient.window); if (!wwin) return; switch (event->xclient.data.l[0]) { case GSWindowLevelAttr: { int level = (int)event->xclient.data.l[1]; if (WINDOW_LEVEL(wwin) != level) { ChangeStackingLevel(wwin->frame->core, level); } } break; } } else if (event->xclient.message_type == w_global.atom.gnustep.titlebar_state) { wwin = wWindowFor(event->xclient.window); if (!wwin) return; switch (event->xclient.data.l[0]) { case WMTitleBarNormal: wFrameWindowChangeState(wwin->frame, WS_UNFOCUSED); break; case WMTitleBarMain: wFrameWindowChangeState(wwin->frame, WS_PFOCUSED); break; case WMTitleBarKey: wFrameWindowChangeState(wwin->frame, WS_FOCUSED); break; } } else if (event->xclient.message_type == w_global.atom.wm.ignore_focus_events) { WScreen *scr = wScreenForRootWindow(event->xclient.window); if (!scr) return; scr->flags.ignore_focus_events = event->xclient.data.l[0] ? 1 : 0; } else if (wNETWMProcessClientMessage(&event->xclient)) { /* do nothing */ #ifdef USE_DOCK_XDND } else if (wXDNDProcessClientMessage(&event->xclient)) { /* do nothing */ #endif /* USE_DOCK_XDND */ } else { /* * Non-standard thing, but needed by OffiX DND. * For when the icon frame gets a ClientMessage * that should have gone to the icon_window. */ if (XFindContext(dpy, event->xbutton.window, w_global.context.client_win, (XPointer *) & desc) != XCNOENT) { struct WIcon *icon = NULL; if (desc->parent_type == WCLASS_MINIWINDOW) { icon = (WIcon *) desc->parent; } else if (desc->parent_type == WCLASS_DOCK_ICON || desc->parent_type == WCLASS_APPICON) { icon = ((WAppIcon *) desc->parent)->icon; } if (icon && (wwin = icon->owner)) { if (wwin->client_win != event->xclient.window) { event->xclient.window = wwin->client_win; XSendEvent(dpy, wwin->client_win, False, NoEventMask, event); } } } } } static void raiseWindow(WScreen * scr) { WWindow *wwin; scr->autoRaiseTimer = NULL; wwin = wWindowFor(scr->autoRaiseWindow); if (!wwin) return; if (!wwin->flags.destroyed && wwin->flags.focused) { wRaiseFrame(wwin->frame->core); /* this is needed or a race condition will occur */ XSync(dpy, False); } } static void handleEnterNotify(XEvent * event) { WWindow *wwin; WObjDescriptor *desc = NULL; XEvent ev; WScreen *scr = wScreenForRootWindow(event->xcrossing.root); if (XCheckTypedWindowEvent(dpy, event->xcrossing.window, LeaveNotify, &ev)) { /* already left the window... */ saveTimestamp(&ev); if (ev.xcrossing.mode == event->xcrossing.mode && ev.xcrossing.detail == event->xcrossing.detail) { return; } } if (XFindContext(dpy, event->xcrossing.window, w_global.context.client_win, (XPointer *) & desc) != XCNOENT) { if (desc->handle_enternotify) (*desc->handle_enternotify) (desc, event); } /* enter to window */ wwin = wWindowFor(event->xcrossing.window); if (!wwin) { if (wPreferences.colormap_mode == WCM_POINTER) { wColormapInstallForWindow(scr, NULL); } if (scr->autoRaiseTimer && event->xcrossing.root == event->xcrossing.window) { WMDeleteTimerHandler(scr->autoRaiseTimer); scr->autoRaiseTimer = NULL; } } else { /* set auto raise timer even if in focus-follows-mouse mode * and the event is for the frame window, even if the window * has focus already. useful if you move the pointer from a focused * window to the root window and back pretty fast * * set focus if in focus-follows-mouse mode and the event * is for the frame window and window doesn't have focus yet */ if (wPreferences.focus_mode == WKF_SLOPPY && wwin->frame->core->window == event->xcrossing.window && !scr->flags.doing_alt_tab) { if (!wwin->flags.focused && !WFLAGP(wwin, no_focusable)) wSetFocusTo(scr, wwin); if (scr->autoRaiseTimer) WMDeleteTimerHandler(scr->autoRaiseTimer); scr->autoRaiseTimer = NULL; if (wPreferences.raise_delay && !WFLAGP(wwin, no_focusable)) { scr->autoRaiseWindow = wwin->frame->core->window; scr->autoRaiseTimer = WMAddTimerHandler(wPreferences.raise_delay, (WMCallback *) raiseWindow, scr); } } /* Install colormap for window, if the colormap installation mode * is colormap_follows_mouse */ if (wPreferences.colormap_mode == WCM_POINTER) { if (wwin->client_win == event->xcrossing.window) wColormapInstallForWindow(scr, wwin); else wColormapInstallForWindow(scr, NULL); } } if (event->xcrossing.window == event->xcrossing.root && event->xcrossing.detail == NotifyNormal && event->xcrossing.detail != NotifyInferior && wPreferences.focus_mode != WKF_CLICK) { wSetFocusTo(scr, scr->focused_window); } #ifdef BALLOON_TEXT wBalloonEnteredObject(scr, desc); #endif } static void handleLeaveNotify(XEvent * event) { WObjDescriptor *desc = NULL; if (XFindContext(dpy, event->xcrossing.window, w_global.context.client_win, (XPointer *) & desc) != XCNOENT) { if (desc->handle_leavenotify) (*desc->handle_leavenotify) (desc, event); } } #ifdef USE_XSHAPE static void handleShapeNotify(XEvent * event) { XShapeEvent *shev = (XShapeEvent *) event; WWindow *wwin; union { XEvent xevent; XShapeEvent xshape; } ev; while (XCheckTypedWindowEvent(dpy, shev->window, event->type, &ev.xevent)) { if (ev.xshape.kind == ShapeBounding) { if (ev.xshape.shaped == shev->shaped) { *shev = ev.xshape; } else { XPutBackEvent(dpy, &ev.xevent); break; } } } wwin = wWindowFor(shev->window); if (!wwin || shev->kind != ShapeBounding) return; if (!shev->shaped && wwin->flags.shaped) { wwin->flags.shaped = 0; wWindowClearShape(wwin); } else if (shev->shaped) { wwin->flags.shaped = 1; wWindowSetShape(wwin); } } #endif /* USE_XSHAPE */ #ifdef KEEP_XKB_LOCK_STATUS /* please help ]d if you know what to do */ static void handleXkbIndicatorStateNotify(XkbEvent *event) { WWindow *wwin; WScreen *scr; XkbStateRec staterec; int i; for (i = 0; i < w_global.screen_count; i++) { scr = wScreenWithNumber(i); wwin = scr->focused_window; if (wwin && wwin->flags.focused) { XkbGetState(dpy, XkbUseCoreKbd, &staterec); if (wwin->frame->languagemode != staterec.group) { wwin->frame->last_languagemode = wwin->frame->languagemode; diff --git a/src/rootmenu.c b/src/rootmenu.c index fc8774e..f391fc6 100644 --- a/src/rootmenu.c +++ b/src/rootmenu.c @@ -1,581 +1,580 @@ /* rootmenu.c- user defined menu * * Window Maker window manager * * Copyright (c) 1997-2003 Alfredo K. Kojima * Copyright (c) 1998-2003 Dan Pascu * Copyright (c) 2014 Window Maker Team * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "wconfig.h" #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/stat.h> #include <sys/wait.h> #include <sys/types.h> #include <string.h> #include <strings.h> #include <ctype.h> #include <time.h> #include <dirent.h> #include <errno.h> #include <X11/Xlib.h> #include <X11/Xutil.h> #include <X11/Xatom.h> #include "WindowMaker.h" #include "actions.h" #include "menu.h" #include "misc.h" #include "main.h" #include "dialog.h" #include "keybind.h" #include "stacking.h" #include "workspace.h" #include "defaults.h" #include "framewin.h" #include "session.h" #include "shutdown.h" #include "xmodifier.h" #include "rootmenu.h" #include "startup.h" #include "switchmenu.h" #include <WINGs/WUtil.h> #define MAX_SHORTCUT_LENGTH 32 static WMenu *readMenuPipe(WScreen * scr, char **file_name); static WMenu *readPLMenuPipe(WScreen * scr, char **file_name); static WMenu *readMenuFile(WScreen *scr, const char *file_name); static WMenu *readMenuDirectory(WScreen *scr, const char *title, char **file_name, const char *command); -static WMenu *configureMenu(WScreen *scr, WMPropList *definition); static void menu_parser_register_macros(WMenuParser parser); typedef struct Shortcut { struct Shortcut *next; int modifier; KeyCode keycode; WMenuEntry *entry; WMenu *menu; } Shortcut; static Shortcut *shortcutList = NULL; /* * Syntax: * # main menu * "Menu Name" MENU * "Title" EXEC command_to_exec -params * "Submenu" MENU * "Title" EXEC command_to_exec -params * "Submenu" END * "Workspaces" WORKSPACE_MENU * "Title" built_in_command * "Quit" EXIT * "Quick Quit" EXIT QUICK * "Menu Name" END * * Commands may be preceded by SHORTCUT key * * Built-in commands: * * INFO_PANEL - shows the Info Panel * LEGAL_PANEL - shows the Legal info panel * SHUTDOWN [QUICK] - closes the X server [without confirmation] * REFRESH - forces the desktop to be repainted * EXIT [QUICK] - exit the window manager [without confirmation] * EXEC <program> - execute an external program * SHEXEC <command> - execute a shell command * WORKSPACE_MENU - places the workspace submenu * ARRANGE_ICONS * RESTART [<window manager>] - restarts the window manager * SHOW_ALL - unhide all windows on workspace * HIDE_OTHERS - hides all windows excep the focused one * OPEN_MENU file - read menu data from file which must be a valid menu file. * OPEN_MENU /some/dir [/some/other/dir ...] [WITH command -options] * - read menu data from directory(ies) and * eventually precede each with a command. * OPEN_MENU | command * - opens command and uses its stdout to construct and insert * the resulting menu in current position. The output of * command must be a valid menu description. * The space between '|' and command is optional. * || will do the same, but will not cache the contents. * OPEN_PLMENU | command * - opens command and uses its stdout which must be in proplist * fromat to construct and insert the resulting menu in current * position. * The space between '|' and command is optional. * || will do the same, but will not cache the contents. * SAVE_SESSION - saves the current state of the desktop, which include * all running applications, all their hints (geometry, * position on screen, workspace they live on, the dock * or clip from where they were launched, and * if minimized, shaded or hidden. Also saves the current * workspace the user is on. All will be restored on every * start of windowmaker until another SAVE_SESSION or * CLEAR_SESSION is used. If SaveSessionOnExit = Yes; in * WindowMaker domain file, then saving is automatically * done on every windowmaker exit, overwriting any * SAVE_SESSION or CLEAR_SESSION (see below). Also save * dock state now. * CLEAR_SESSION - clears any previous saved session. This will not have * any effect if SaveSessionOnExit is True. * */ #define M_QUICK 1 /* menu commands */ static void execCommand(WMenu * menu, WMenuEntry * entry) { char *cmdline; cmdline = ExpandOptions(menu->frame->screen_ptr, (char *)entry->clientdata); XGrabPointer(dpy, menu->frame->screen_ptr->root_win, True, 0, GrabModeAsync, GrabModeAsync, None, wPreferences.cursor[WCUR_WAIT], CurrentTime); XSync(dpy, 0); if (cmdline) { ExecuteShellCommand(menu->frame->screen_ptr, cmdline); wfree(cmdline); } XUngrabPointer(dpy, CurrentTime); XSync(dpy, 0); } static void exitCommand(WMenu * menu, WMenuEntry * entry) { static int inside = 0; int result; /* prevent reentrant calls */ if (inside) return; inside = 1; #define R_CANCEL 0 #define R_EXIT 1 result = R_CANCEL; if ((long)entry->clientdata == M_QUICK) { result = R_EXIT; } else { int r, oldSaveSessionFlag; oldSaveSessionFlag = wPreferences.save_session_on_exit; r = wExitDialog(menu->frame->screen_ptr, _("Exit"), _("Exit window manager?"), _("Exit"), _("Cancel"), NULL); if (r == WAPRDefault) { result = R_EXIT; } else if (r == WAPRAlternate) { /* Don't modify the "save session on exit" flag if the * user canceled the operation. */ wPreferences.save_session_on_exit = oldSaveSessionFlag; } } if (result == R_EXIT) Shutdown(WSExitMode); #undef R_EXIT #undef R_CANCEL inside = 0; } static void shutdownCommand(WMenu * menu, WMenuEntry * entry) { static int inside = 0; int result; /* prevent reentrant calls */ if (inside) return; inside = 1; #define R_CANCEL 0 #define R_CLOSE 1 #define R_KILL 2 result = R_CANCEL; if ((long)entry->clientdata == M_QUICK) result = R_CLOSE; else { int r, oldSaveSessionFlag; oldSaveSessionFlag = wPreferences.save_session_on_exit; r = wExitDialog(menu->frame->screen_ptr, _("Kill X session"), _("Kill Window System session?\n" "(all applications will be closed)"), _("Kill"), _("Cancel"), NULL); if (r == WAPRDefault) { result = R_KILL; } else if (r == WAPRAlternate) { /* Don't modify the "save session on exit" flag if the * user canceled the operation. */ wPreferences.save_session_on_exit = oldSaveSessionFlag; } } if (result != R_CANCEL) { Shutdown(WSKillMode); } #undef R_CLOSE #undef R_CANCEL #undef R_KILL inside = 0; } static void restartCommand(WMenu * menu, WMenuEntry * entry) { /* Parameter not used, but tell the compiler that it is ok */ (void) menu; (void) entry; Shutdown(WSRestartPreparationMode); Restart((char *)entry->clientdata, False); Restart(NULL, True); } static void refreshCommand(WMenu * menu, WMenuEntry * entry) { /* Parameter not used, but tell the compiler that it is ok */ (void) entry; wRefreshDesktop(menu->frame->screen_ptr); } static void arrangeIconsCommand(WMenu * menu, WMenuEntry * entry) { /* Parameter not used, but tell the compiler that it is ok */ (void) entry; wArrangeIcons(menu->frame->screen_ptr, True); } static void showAllCommand(WMenu * menu, WMenuEntry * entry) { /* Parameter not used, but tell the compiler that it is ok */ (void) entry; wShowAllWindows(menu->frame->screen_ptr); } static void hideOthersCommand(WMenu * menu, WMenuEntry * entry) { /* Parameter not used, but tell the compiler that it is ok */ (void) entry; wHideOtherApplications(menu->frame->screen_ptr->focused_window); } static void saveSessionCommand(WMenu * menu, WMenuEntry * entry) { /* Parameter not used, but tell the compiler that it is ok */ (void) entry; if (!wPreferences.save_session_on_exit) wSessionSaveState(menu->frame->screen_ptr); wScreenSaveState(menu->frame->screen_ptr); } static void clearSessionCommand(WMenu * menu, WMenuEntry * entry) { /* Parameter not used, but tell the compiler that it is ok */ (void) entry; wSessionClearState(menu->frame->screen_ptr); wScreenSaveState(menu->frame->screen_ptr); } static void infoPanelCommand(WMenu * menu, WMenuEntry * entry) { /* Parameter not used, but tell the compiler that it is ok */ (void) entry; wShowInfoPanel(menu->frame->screen_ptr); } static void legalPanelCommand(WMenu * menu, WMenuEntry * entry) { /* Parameter not used, but tell the compiler that it is ok */ (void) entry; wShowLegalPanel(menu->frame->screen_ptr); } /********************************************************************/ static char *getLocalizedMenuFile(const char *menu) { char *buffer, *ptr, *locale; int len; if (!w_global.locale) return NULL; len = strlen(menu) + strlen(w_global.locale) + 8; buffer = wmalloc(len); /* try menu.locale_name */ snprintf(buffer, len, "%s.%s", menu, w_global.locale); if (access(buffer, F_OK) == 0) return buffer; /* position of locale in our buffer */ locale = buffer + strlen(menu) + 1; /* check if it is in the form aa_bb.encoding and check for aa_bb */ ptr = strchr(locale, '.'); if (ptr) { *ptr = 0; if (access(buffer, F_OK) == 0) return buffer; } /* now check for aa */ ptr = strchr(locale, '_'); if (ptr) { *ptr = 0; if (access(buffer, F_OK) == 0) return buffer; } wfree(buffer); return NULL; } Bool wRootMenuPerformShortcut(XEvent * event) { WScreen *scr = wScreenForRootWindow(event->xkey.root); Shortcut *ptr; int modifiers; int done = 0; /* ignore CapsLock */ modifiers = event->xkey.state & w_global.shortcut.modifiers_mask; for (ptr = shortcutList; ptr != NULL; ptr = ptr->next) { if (ptr->keycode == 0 || ptr->menu->menu->screen_ptr != scr) continue; if (ptr->keycode == event->xkey.keycode && ptr->modifier == modifiers) { (*ptr->entry->callback) (ptr->menu, ptr->entry); done = True; } } return done; } void wRootMenuBindShortcuts(Window window) { Shortcut *ptr; ptr = shortcutList; while (ptr) { if (ptr->modifier != AnyModifier) { XGrabKey(dpy, ptr->keycode, ptr->modifier | LockMask, window, True, GrabModeAsync, GrabModeAsync); #ifdef NUMLOCK_HACK wHackedGrabKey(ptr->keycode, ptr->modifier, window, True, GrabModeAsync, GrabModeAsync); #endif } XGrabKey(dpy, ptr->keycode, ptr->modifier, window, True, GrabModeAsync, GrabModeAsync); ptr = ptr->next; } } static void rebindKeygrabs(WScreen * scr) { WWindow *wwin; wwin = scr->focused_window; while (wwin != NULL) { XUngrabKey(dpy, AnyKey, AnyModifier, wwin->frame->core->window); if (!WFLAGP(wwin, no_bind_keys)) { wWindowSetKeyGrabs(wwin); } wwin = wwin->prev; } } static void removeShortcutsForMenu(WMenu * menu) { Shortcut *ptr, *tmp; Shortcut *newList = NULL; ptr = shortcutList; while (ptr != NULL) { tmp = ptr->next; if (ptr->menu == menu) { wfree(ptr); } else { ptr->next = newList; newList = ptr; } ptr = tmp; } shortcutList = newList; menu->menu->screen_ptr->flags.root_menu_changed_shortcuts = 1; } static Bool addShortcut(const char *file, const char *shortcutDefinition, WMenu *menu, WMenuEntry *entry) { Shortcut *ptr; KeySym ksym; char *k; char buf[MAX_SHORTCUT_LENGTH], *b; ptr = wmalloc(sizeof(Shortcut)); wstrlcpy(buf, shortcutDefinition, MAX_SHORTCUT_LENGTH); b = (char *)buf; /* get modifiers */ ptr->modifier = 0; while ((k = strchr(b, '+')) != NULL) { int mod; *k = 0; mod = wXModifierFromKey(b); if (mod < 0) { wwarning(_("%s: invalid key modifier \"%s\""), file, b); wfree(ptr); return False; } ptr->modifier |= mod; b = k + 1; } /* get key */ ksym = XStringToKeysym(b); if (ksym == NoSymbol) { wwarning(_("%s:invalid kbd shortcut specification \"%s\" for entry %s"), file, shortcutDefinition, entry->text); wfree(ptr); return False; } ptr->keycode = XKeysymToKeycode(dpy, ksym); if (ptr->keycode == 0) { wwarning(_("%s:invalid key in shortcut \"%s\" for entry %s"), file, shortcutDefinition, entry->text); wfree(ptr); return False; } ptr->menu = menu; ptr->entry = entry; ptr->next = shortcutList; shortcutList = ptr; menu->menu->screen_ptr->flags.root_menu_changed_shortcuts = 1; return True; } static char *next_token(char *line, char **next) { char *tmp, c; char *ret; *next = NULL; while (*line == ' ' || *line == '\t') line++; tmp = line; if (*tmp == '"') { tmp++; line++; while (*tmp != 0 && *tmp != '"') tmp++; if (*tmp != '"') { wwarning(_("%s: unmatched '\"' in menu file"), line); return NULL; } } else { do { if (*tmp == '\\') tmp++; if (*tmp != 0) tmp++; } while (*tmp != 0 && *tmp != ' ' && *tmp != '\t'); } c = *tmp; *tmp = 0; ret = wstrdup(line); *tmp = c; if (c == 0) return ret; else tmp++; /* skip blanks */ while (*tmp == ' ' || *tmp == '\t') tmp++; if (*tmp != 0) *next = tmp; return ret; } static void separateCommand(char *line, char ***file, char **command) { char *token, *tmp = line; WMArray *array = WMCreateArray(4); int count, i; *file = NULL; *command = NULL; do { token = next_token(tmp, &tmp); if (token) { if (strcmp(token, "WITH") == 0) { if (tmp != NULL && *tmp != 0) *command = wstrdup(tmp); else wwarning(_("%s: missing command"), line); wfree(token); break; } WMAddToArray(array, token); } } while (token != NULL && tmp != NULL); @@ -958,759 +957,759 @@ static WMenuEntry *addMenuEntry(WMenu *menu, const char *title, const char *shor } else if (strcmp(command, "HIDE_OTHERS") == 0) { entry = wMenuAddCallback(menu, title, hideOthersCommand, NULL); shortcutOk = True; } else if (strcmp(command, "SHOW_ALL") == 0) { entry = wMenuAddCallback(menu, title, showAllCommand, NULL); shortcutOk = True; } else if (strcmp(command, "RESTART") == 0) { entry = wMenuAddCallback(menu, title, restartCommand, params ? wstrdup(params) : NULL); entry->free_cdata = wfree; shortcutOk = True; } else if (strcmp(command, "SAVE_SESSION") == 0) { entry = wMenuAddCallback(menu, title, saveSessionCommand, NULL); shortcutOk = True; } else if (strcmp(command, "CLEAR_SESSION") == 0) { entry = wMenuAddCallback(menu, title, clearSessionCommand, NULL); shortcutOk = True; } else if (strcmp(command, "INFO_PANEL") == 0) { entry = wMenuAddCallback(menu, title, infoPanelCommand, NULL); shortcutOk = True; } else if (strcmp(command, "LEGAL_PANEL") == 0) { entry = wMenuAddCallback(menu, title, legalPanelCommand, NULL); shortcutOk = True; } else { wwarning(_("%s:unknown command \"%s\" in menu config."), file_name, command); return NULL; } if (shortcut && entry) { if (!shortcutOk) { wwarning(_("%s:can't add shortcut for entry \"%s\""), file_name, title); } else { if (addShortcut(file_name, shortcut, menu, entry)) { entry->rtext = GetShortcutString(shortcut); /* entry->rtext = wstrdup(shortcut); */ } } } return entry; } /******************* Menu Configuration From File *******************/ static void freeline(char *title, char *command, char *parameter, char *shortcut) { wfree(title); wfree(command); wfree(parameter); wfree(shortcut); } static WMenu *parseCascade(WScreen * scr, WMenu * menu, WMenuParser parser) { char *command, *params, *shortcut, *title; while (WMenuParserGetLine(parser, &title, &command, &params, &shortcut)) { if (command == NULL || !command[0]) { WMenuParserError(parser, _("missing command in menu config") ); freeline(title, command, params, shortcut); goto error; } if (strcasecmp(command, "MENU") == 0) { WMenu *cascade; /* start submenu */ cascade = wMenuCreate(scr, M_(title), False); cascade->on_destroy = removeShortcutsForMenu; if (!parseCascade(scr, cascade, parser)) { wMenuDestroy(cascade, True); } else { wMenuEntrySetCascade(menu, wMenuAddCallback(menu, M_(title), NULL, NULL), cascade); } } else if (strcasecmp(command, "END") == 0) { /* end of menu */ freeline(title, command, params, shortcut); return menu; } else { /* normal items */ addMenuEntry(menu, M_(title), shortcut, command, params, WMenuParserGetFilename(parser)); } freeline(title, command, params, shortcut); } WMenuParserError(parser, _("syntax error in menu file: END declaration missing") ); error: return NULL; } static WMenu *readMenu(WScreen *scr, const char *flat_file, FILE *file) { WMenu *menu = NULL; WMenuParser parser; char *title, *command, *params, *shortcut; parser = WMenuParserCreate(flat_file, file, DEF_CONFIG_PATHS); menu_parser_register_macros(parser); while (WMenuParserGetLine(parser, &title, &command, &params, &shortcut)) { if (command == NULL || !command[0]) { WMenuParserError(parser, _("missing command in menu config") ); freeline(title, command, params, shortcut); break; } if (strcasecmp(command, "MENU") == 0) { menu = wMenuCreate(scr, M_(title), True); menu->on_destroy = removeShortcutsForMenu; if (!parseCascade(scr, menu, parser)) { wMenuDestroy(menu, True); menu = NULL; } freeline(title, command, params, shortcut); break; } else { WMenuParserError(parser, _("invalid menu, no menu title given") ); freeline(title, command, params, shortcut); break; } freeline(title, command, params, shortcut); } WMenuParserDelete(parser); return menu; } static WMenu *readMenuFile(WScreen *scr, const char *file_name) { WMenu *menu = NULL; FILE *file = NULL; file = fopen(file_name, "rb"); if (!file) { werror(_("could not open menu file \"%s\": %s"), file_name, strerror(errno)); return NULL; } menu = readMenu(scr, file_name, file); fclose(file); return menu; } static inline int generate_command_from_list(char *buffer, size_t buffer_size, char **command_elements) { char *rd; int wr_idx; int i; wr_idx = 0; for (i = 0; command_elements[i] != NULL; i++) { if (i > 0) if (wr_idx < buffer_size - 1) buffer[wr_idx++] = ' '; for (rd = command_elements[i]; *rd != '\0'; rd++) { if (wr_idx < buffer_size - 1) buffer[wr_idx++] = *rd; else return 1; } } buffer[wr_idx] = '\0'; return 0; } /************ Menu Configuration From Pipe *************/ static WMenu *readPLMenuPipe(WScreen * scr, char **file_name) { WMPropList *plist = NULL; WMenu *menu = NULL; char *filename; char flat_file[MAXLINE]; if (generate_command_from_list(flat_file, sizeof(flat_file), file_name)) { werror(_("could not open menu file \"%s\": %s"), file_name[0], _("pipe command for PropertyList is too long")); return NULL; } filename = flat_file + (flat_file[1] == '|' ? 2 : 1); plist = WMReadPropListFromPipe(filename); if (!plist) return NULL; menu = configureMenu(scr, plist); WMReleasePropList(plist); if (!menu) return NULL; menu->on_destroy = removeShortcutsForMenu; return menu; } static WMenu *readMenuPipe(WScreen * scr, char **file_name) { WMenu *menu = NULL; FILE *file = NULL; char *filename; char flat_file[MAXLINE]; if (generate_command_from_list(flat_file, sizeof(flat_file), file_name)) { werror(_("could not open menu file \"%s\": %s"), file_name[0], _("pipe command is too long")); return NULL; } filename = flat_file + (flat_file[1] == '|' ? 2 : 1); /* * In case of memory problem, 'popen' will not set the errno, so we initialise it * to be able to display a meaningful message. For other problems, 'popen' will * properly set errno, so we'll still get a good message */ errno = ENOMEM; file = popen(filename, "r"); if (!file) { werror(_("could not open menu file \"%s\": %s"), filename, strerror(errno)); return NULL; } menu = readMenu(scr, flat_file, file); pclose(file); return menu; } typedef struct { char *name; int index; } dir_data; static int myCompare(const void *d1, const void *d2) { dir_data *p1 = *(dir_data **) d1; dir_data *p2 = *(dir_data **) d2; return strcmp(p1->name, p2->name); } /***** Preset some macro for file parser *****/ static void menu_parser_register_macros(WMenuParser parser) { Visual *visual; char buf[32]; // Used to return CPP verion, now returns wmaker's version WMenuParserRegisterSimpleMacro(parser, "__VERSION__", VERSION); // All macros below were historically defined by WindowMaker visual = DefaultVisual(dpy, DefaultScreen(dpy)); snprintf(buf, sizeof(buf), "%d", visual->class); WMenuParserRegisterSimpleMacro(parser, "VISUAL", buf); snprintf(buf, sizeof(buf), "%d", DefaultDepth(dpy, DefaultScreen(dpy)) ); WMenuParserRegisterSimpleMacro(parser, "DEPTH", buf); snprintf(buf, sizeof(buf), "%d", WidthOfScreen(DefaultScreenOfDisplay(dpy)) ); WMenuParserRegisterSimpleMacro(parser, "SCR_WIDTH", buf); snprintf(buf, sizeof(buf), "%d", HeightOfScreen(DefaultScreenOfDisplay(dpy)) ); WMenuParserRegisterSimpleMacro(parser, "SCR_HEIGHT", buf); WMenuParserRegisterSimpleMacro(parser, "DISPLAY", XDisplayName(DisplayString(dpy)) ); WMenuParserRegisterSimpleMacro(parser, "WM_VERSION", "\"" VERSION "\""); } /************ Menu Configuration From Directory *************/ static Bool isFilePackage(const char *file) { int l; /* check if the extension indicates this file is a * file package. For now, only recognize .themed */ l = strlen(file); if (l > 7 && strcmp(&(file[l - 7]), ".themed") == 0) { return True; } else { return False; } } static WMenu *readMenuDirectory(WScreen *scr, const char *title, char **path, const char *command) { DIR *dir; struct dirent *dentry; struct stat stat_buf; WMenu *menu = NULL; char *buffer; WMArray *dirs = NULL, *files = NULL; WMArrayIterator iter; int length, i, have_space = 0; dir_data *data; int stripExtension = 0; dirs = WMCreateArray(16); files = WMCreateArray(16); i = 0; while (path[i] != NULL) { if (strcmp(path[i], "-noext") == 0) { stripExtension = 1; i++; continue; } dir = opendir(path[i]); if (!dir) { i++; continue; } while ((dentry = readdir(dir))) { if (strcmp(dentry->d_name, ".") == 0 || strcmp(dentry->d_name, "..") == 0) continue; if (dentry->d_name[0] == '.') continue; buffer = malloc(strlen(path[i]) + strlen(dentry->d_name) + 4); if (!buffer) { werror(_("out of memory while constructing directory menu %s"), path[i]); break; } strcpy(buffer, path[i]); strcat(buffer, "/"); strcat(buffer, dentry->d_name); if (stat(buffer, &stat_buf) != 0) { werror(_("%s:could not stat file \"%s\" in menu directory"), path[i], dentry->d_name); } else { Bool isFilePack = False; data = NULL; if (S_ISDIR(stat_buf.st_mode) && !(isFilePack = isFilePackage(dentry->d_name))) { /* access always returns success for user root */ if (access(buffer, X_OK) == 0) { /* Directory is accesible. Add to directory list */ data = (dir_data *) wmalloc(sizeof(dir_data)); data->name = wstrdup(dentry->d_name); data->index = i; WMAddToArray(dirs, data); } } else if (S_ISREG(stat_buf.st_mode) || isFilePack) { /* Hack because access always returns X_OK success for user root */ #define S_IXANY (S_IXUSR | S_IXGRP | S_IXOTH) if ((command != NULL && access(buffer, R_OK) == 0) || (command == NULL && access(buffer, X_OK) == 0 && (stat_buf.st_mode & S_IXANY))) { data = (dir_data *) wmalloc(sizeof(dir_data)); data->name = wstrdup(dentry->d_name); data->index = i; WMAddToArray(files, data); } } } free(buffer); } closedir(dir); i++; } if (!WMGetArrayItemCount(dirs) && !WMGetArrayItemCount(files)) { WMFreeArray(dirs); WMFreeArray(files); return NULL; } WMSortArray(dirs, myCompare); WMSortArray(files, myCompare); menu = wMenuCreate(scr, M_(title), False); menu->on_destroy = removeShortcutsForMenu; WM_ITERATE_ARRAY(dirs, data, iter) { /* New directory. Use same OPEN_MENU command that was used * for the current directory. */ length = strlen(path[data->index]) + strlen(data->name) + 6; if (stripExtension) length += 7; if (command) length += strlen(command) + 6; buffer = malloc(length); if (!buffer) { werror(_("out of memory while constructing directory menu %s"), path[data->index]); break; } buffer[0] = '\0'; if (stripExtension) strcat(buffer, "-noext "); have_space = strchr(path[data->index], ' ') != NULL || strchr(data->name, ' ') != NULL; if (have_space) strcat(buffer, "\""); strcat(buffer, path[data->index]); strcat(buffer, "/"); strcat(buffer, data->name); if (have_space) strcat(buffer, "\""); if (command) { strcat(buffer, " WITH "); strcat(buffer, command); } addMenuEntry(menu, M_(data->name), NULL, "OPEN_MENU", buffer, path[data->index]); wfree(buffer); wfree(data->name); wfree(data); } WM_ITERATE_ARRAY(files, data, iter) { /* executable: add as entry */ length = strlen(path[data->index]) + strlen(data->name) + 6; if (command) length += strlen(command); buffer = malloc(length); if (!buffer) { werror(_("out of memory while constructing directory menu %s"), path[data->index]); break; } have_space = strchr(path[data->index], ' ') != NULL || strchr(data->name, ' ') != NULL; if (command != NULL) { strcpy(buffer, command); strcat(buffer, " "); if (have_space) strcat(buffer, "\""); strcat(buffer, path[data->index]); } else { if (have_space) { buffer[0] = '"'; buffer[1] = 0; strcat(buffer, path[data->index]); } else { strcpy(buffer, path[data->index]); } } strcat(buffer, "/"); strcat(buffer, data->name); if (have_space) strcat(buffer, "\""); if (stripExtension) { char *ptr = strrchr(data->name, '.'); if (ptr && ptr != data->name) *ptr = 0; } addMenuEntry(menu, M_(data->name), NULL, "SHEXEC", buffer, path[data->index]); wfree(buffer); wfree(data->name); wfree(data); } WMFreeArray(files); WMFreeArray(dirs); return menu; } /************ Menu Configuration From WMRootMenu *************/ static WMenu *makeDefaultMenu(WScreen * scr) { WMenu *menu = NULL; menu = wMenuCreate(scr, _("Commands"), True); wMenuAddCallback(menu, M_("XTerm"), execCommand, "xterm"); wMenuAddCallback(menu, M_("rxvt"), execCommand, "rxvt"); wMenuAddCallback(menu, _("Restart"), restartCommand, NULL); wMenuAddCallback(menu, _("Exit..."), exitCommand, NULL); return menu; } /* *---------------------------------------------------------------------- * configureMenu-- * Reads root menu configuration from defaults database. * *---------------------------------------------------------------------- */ -static WMenu *configureMenu(WScreen *scr, WMPropList *definition) +WMenu *configureMenu(WScreen *scr, WMPropList *definition) { WMenu *menu = NULL; WMPropList *elem; int i, count; WMPropList *title, *command, *params; char *tmp, *mtitle; if (WMIsPLString(definition)) { struct stat stat_buf; char *path = NULL; Bool menu_is_default = False; /* menu definition is a string. Probably a path, so parse the file */ tmp = wexpandpath(WMGetFromPLString(definition)); path = getLocalizedMenuFile(tmp); if (!path) path = wfindfile(DEF_CONFIG_PATHS, tmp); if (!path) { path = wfindfile(DEF_CONFIG_PATHS, DEF_MENU_FILE); menu_is_default = True; } if (!path) { werror(_("could not find menu file \"%s\" referenced in WMRootMenu"), tmp); wfree(tmp); return NULL; } if (stat(path, &stat_buf) < 0) { werror(_("could not access menu \"%s\" referenced in WMRootMenu"), path); wfree(path); wfree(tmp); return NULL; } if (!scr->root_menu || stat_buf.st_mtime > scr->root_menu->timestamp /* if the pointer in WMRootMenu has changed */ || w_global.domain.root_menu->timestamp > scr->root_menu->timestamp) { WMPropList *menu_from_file = NULL; if (menu_is_default) { wwarning(_ ("using default menu file \"%s\" as the menu referenced in WMRootMenu could not be found "), path); } menu_from_file = WMReadPropListFromFile(path); if (menu_from_file == NULL) { /* old style menu */ menu = readMenuFile(scr, path); } else { menu = configureMenu(scr, menu_from_file); WMReleasePropList(menu_from_file); } if (menu) menu->timestamp = WMAX(stat_buf.st_mtime, w_global.domain.root_menu->timestamp); } else { menu = NULL; } wfree(path); wfree(tmp); return menu; } count = WMGetPropListItemCount(definition); if (count == 0) return NULL; elem = WMGetFromPLArray(definition, 0); if (!WMIsPLString(elem)) { tmp = WMGetPropListDescription(elem, False); wwarning(_("%s:format error in root menu configuration \"%s\""), "WMRootMenu", tmp); wfree(tmp); return NULL; } mtitle = WMGetFromPLString(elem); menu = wMenuCreate(scr, M_(mtitle), False); menu->on_destroy = removeShortcutsForMenu; for (i = 1; i < count; i++) { elem = WMGetFromPLArray(definition, i); #if 0 if (WMIsPLString(elem)) { char *file; file = WMGetFromPLString(elem); } #endif if (!WMIsPLArray(elem) || WMGetPropListItemCount(elem) < 2) goto error; if (WMIsPLArray(WMGetFromPLArray(elem, 1))) { WMenu *submenu; WMenuEntry *mentry; /* submenu */ submenu = configureMenu(scr, elem); if (submenu) { mentry = wMenuAddCallback(menu, submenu->frame->title, NULL, NULL); wMenuEntrySetCascade(menu, mentry, submenu); } } else { int idx = 0; WMPropList *shortcut; /* normal entry */ title = WMGetFromPLArray(elem, idx++); shortcut = WMGetFromPLArray(elem, idx++); if (strcmp(WMGetFromPLString(shortcut), "SHORTCUT") == 0) { shortcut = WMGetFromPLArray(elem, idx++); command = WMGetFromPLArray(elem, idx++); } else { command = shortcut; shortcut = NULL; } params = WMGetFromPLArray(elem, idx++); if (!title || !command) goto error; addMenuEntry(menu, M_(WMGetFromPLString(title)), shortcut ? WMGetFromPLString(shortcut) : NULL, WMGetFromPLString(command), params ? WMGetFromPLString(params) : NULL, "WMRootMenu"); } continue; error: tmp = WMGetPropListDescription(elem, False); wwarning(_("%s:format error in root menu configuration \"%s\""), "WMRootMenu", tmp); wfree(tmp); } return menu; } /* *---------------------------------------------------------------------- * OpenRootMenu-- * Opens the root menu, parsing the menu configuration from the * defaults database. * If the menu is already mapped and is not sticked to the * root window, it will be unmapped. * * Side effects: * The menu may be remade. * * Notes: * Construction of OPEN_MENU entries are delayed to the moment the * user map's them. *---------------------------------------------------------------------- */ void OpenRootMenu(WScreen * scr, int x, int y, int keyboard) { WMenu *menu = NULL; WMPropList *definition; /* static WMPropList *domain=NULL; if (!domain) { domain = WMCreatePLString("WMRootMenu"); } */ scr->flags.root_menu_changed_shortcuts = 0; scr->flags.added_workspace_menu = 0; scr->flags.added_windows_menu = 0; if (scr->root_menu && scr->root_menu->flags.mapped) { menu = scr->root_menu; if (!menu->flags.buttoned) { wMenuUnmap(menu); } else { wRaiseFrame(menu->frame->core); if (keyboard) wMenuMapAt(menu, 0, 0, True); else wMenuMapCopyAt(menu, x - menu->frame->core->width / 2, y); } return; } definition = w_global.domain.root_menu->dictionary; /* definition = PLGetDomain(domain); */ if (definition) { if (WMIsPLArray(definition)) { if (!scr->root_menu || w_global.domain.root_menu->timestamp > scr->root_menu->timestamp) { menu = configureMenu(scr, definition); if (menu) menu->timestamp = w_global.domain.root_menu->timestamp; } else menu = NULL; } else { menu = configureMenu(scr, definition); } } if (!menu) { /* menu hasn't changed or could not be read */ if (!scr->root_menu) { wMessageDialog(scr, _("Error"), _("The applications menu could not be loaded. " "Look at the console output for a detailed " "description of the errors."), _("OK"), NULL, NULL); menu = makeDefaultMenu(scr); scr->root_menu = menu; } menu = scr->root_menu; } else { /* new root menu */ if (scr->root_menu) { wMenuDestroy(scr->root_menu, True); } scr->root_menu = menu; } if (menu) { int newx, newy; if (keyboard && x == 0 && y == 0) { newx = newy = 0; } else if (keyboard && x == scr->scr_width / 2 && y == scr->scr_height / 2) { newx = x - menu->frame->core->width / 2; newy = y - menu->frame->core->height / 2; } else { newx = x - menu->frame->core->width / 2; newy = y; } wMenuMapAt(menu, newx, newy, keyboard); } if (scr->flags.root_menu_changed_shortcuts) rebindKeygrabs(scr); } diff --git a/src/rootmenu.h b/src/rootmenu.h index 497b526..44475b0 100644 --- a/src/rootmenu.h +++ b/src/rootmenu.h @@ -1,29 +1,30 @@ /* rootmenu.h- user defined menu * * Window Maker window manager * * Copyright (c) 2000-2003 Alfredo K. Kojima * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef WMROOTMENU_H #define WMROOTMENU_H Bool wRootMenuPerformShortcut(XEvent * event); void wRootMenuBindShortcuts(Window window); void OpenRootMenu(WScreen * scr, int x, int y, int keyboard); +WMenu *configureMenu(WScreen *scr, WMPropList *definition); #endif /* WMROOTMENU_H */
roblillack/wmaker
033d2d9a6facf44c65848513f723c67f07ea875d
Changed Russian translation
diff --git a/WPrefs.app/po/ru.po b/WPrefs.app/po/ru.po index 99a5592..c5dbd06 100644 --- a/WPrefs.app/po/ru.po +++ b/WPrefs.app/po/ru.po @@ -1,1137 +1,1165 @@ # Igor P. Roboul <[email protected]> # Andrew W. Nosenko <[email protected]> # # Краткий словарь: # options параметры # preferences ??? (не устоялось) # settings установки msgid "" msgstr "" "Project-Id-Version: WPrefs.app 0.45\n" "POT-Creation-Date: 2002-09-12 16:18+0300\n" "PO-Revision-Date: 2002-09-12 17:45+0300\n" "Last-Translator: [email protected]\n" "Language-Team: Russian\n" "MIME-Version: 1.0\n" "Content-Type: text/plain; charset=UTF-8\n" "Content-Transfer-Encoding: 8bit\n" #: ../../WPrefs.app/Appearance.c:1131 msgid "Select File" msgstr "Укажите файл" #: ../../WPrefs.app/Appearance.c:1533 msgid "Focused Window" msgstr "Активное окно" #: ../../WPrefs.app/Appearance.c:1537 msgid "Unfocused Window" msgstr "Неактивное окно" #: ../../WPrefs.app/Appearance.c:1541 msgid "Owner of Focused Window" msgstr "Владелец активного окна" # awn: если перевести, то не помещается в картинку #: ../../WPrefs.app/Appearance.c:1545 ../../WPrefs.app/Appearance.c:1862 msgid "Menu Title" msgstr "" #: ../../WPrefs.app/Appearance.c:1549 ../../WPrefs.app/Appearance.c:1551 msgid "Normal Item" msgstr "Нормальный" #: ../../WPrefs.app/Appearance.c:1555 msgid "Disabled Item" msgstr "Запрещенный" #: ../../WPrefs.app/Appearance.c:1564 msgid "Highlighted" msgstr "Подсвеченный" #: ../../WPrefs.app/Appearance.c:1755 msgid "Texture" msgstr "Текстура" #: ../../WPrefs.app/Appearance.c:1763 msgid "Titlebar of Focused Window" msgstr "Заголовок активного окна" #: ../../WPrefs.app/Appearance.c:1764 msgid "Titlebar of Unfocused Windows" msgstr "Заголовок неактивных окон" #: ../../WPrefs.app/Appearance.c:1765 msgid "Titlebar of Focused Window's Owner" msgstr "Заголовок владельца активного окна" #: ../../WPrefs.app/Appearance.c:1766 msgid "Window Resizebar" msgstr "Рамка изменения размера окна" #: ../../WPrefs.app/Appearance.c:1767 msgid "Titlebar of Menus" msgstr "Заголовок меню" #: ../../WPrefs.app/Appearance.c:1768 msgid "Menu Items" msgstr "Элементы меню" #: ../../WPrefs.app/Appearance.c:1769 msgid "Icon Background" msgstr "Фон иконки" #: ../../WPrefs.app/Appearance.c:1784 msgid "" "Double click in the texture you want to use\n" "for the selected item." msgstr "" "Щелкните дважды на текстуре, которую вы хотите\n" "использовать для выбранного элемента." #: ../../WPrefs.app/Appearance.c:1798 msgid "New" msgstr "Новый" #: ../../WPrefs.app/Appearance.c:1802 msgid "Create a new texture." msgstr "Создать новую текстуру." #: ../../WPrefs.app/Appearance.c:1810 msgid "Extract..." msgstr "Извлечь..." #: ../../WPrefs.app/Appearance.c:1814 msgid "Extract texture(s) from a theme or a style file." msgstr "Извлечь текстуру (текстуры) из темы или файла стиля." #: ../../WPrefs.app/Appearance.c:1824 msgid "Edit" msgstr "Редактировать" #: ../../WPrefs.app/Appearance.c:1827 msgid "Edit the highlighted texture." msgstr "Редактировать выбранную текстуру." #: ../../WPrefs.app/Appearance.c:1835 ../../WPrefs.app/TexturePanel.c:1316 msgid "Delete" msgstr "Стереть" #: ../../WPrefs.app/Appearance.c:1839 msgid "Delete the highlighted texture." msgstr "Удалить выбранную текстуру." #: ../../WPrefs.app/Appearance.c:1852 msgid "Color" msgstr "Цвет" #: ../../WPrefs.app/Appearance.c:1859 msgid "Focused Window Title" msgstr "Заголовок активного окна" #: ../../WPrefs.app/Appearance.c:1860 msgid "Unfocused Window Title" msgstr "Заголовок неактивного окна" #: ../../WPrefs.app/Appearance.c:1861 msgid "Owner of Focused Window Title" msgstr "Владелец активного окна" #: ../../WPrefs.app/Appearance.c:1863 msgid "Menu Item Text" msgstr "Текст элемента меню" #: ../../WPrefs.app/Appearance.c:1864 msgid "Disabled Menu Item Text" msgstr "Текст запрещенного элемента меню" #: ../../WPrefs.app/Appearance.c:1865 msgid "Menu Highlight Color" msgstr "Фон подсвеченного элемента меню" #: ../../WPrefs.app/Appearance.c:1866 msgid "Highlighted Menu Text Color" msgstr "Текст подсвеченного элемента меню" #: ../../WPrefs.app/Appearance.c:1905 msgid "Background" msgstr "Фон" #: ../../WPrefs.app/Appearance.c:1917 ../../WPrefs.app/TexturePanel.c:1503 msgid "Browse..." msgstr "Выбрать" #: ../../WPrefs.app/Appearance.c:1930 msgid "Options" msgstr "Параметры" #: ../../WPrefs.app/Appearance.c:1937 msgid "Menu Style" msgstr "Стиль меню" #: ../../WPrefs.app/Appearance.c:1965 ../../WPrefs.app/Configurations.c:242 #: ../../WPrefs.app/Configurations.c:254 ../../WPrefs.app/Focus.c:288 #: ../../WPrefs.app/Focus.c:299 ../../WPrefs.app/MenuPreferences.c:134 #: ../../WPrefs.app/MenuPreferences.c:145 #: ../../WPrefs.app/MenuPreferences.c:173 #: ../../WPrefs.app/MenuPreferences.c:188 ../../WPrefs.app/MouseSettings.c:560 #: ../../WPrefs.app/MouseSettings.c:571 ../../WPrefs.app/WPrefs.c:558 #: ../../WPrefs.app/WPrefs.c:583 #, c-format msgid "could not load icon file %s" msgstr "не могу загрузить иконку %s" # awn: правильно -- "Выравнивание заголовка", но места нет. #: ../../WPrefs.app/Appearance.c:1979 msgid "Title Alignment" msgstr "Заголовок" #: ../../WPrefs.app/Appearance.c:1986 msgid "Left" msgstr "Влево" #: ../../WPrefs.app/Appearance.c:1989 ../../WPrefs.app/TexturePanel.c:1517 #: ../../WPrefs.app/Workspace.c:270 msgid "Center" msgstr "По центру" #: ../../WPrefs.app/Appearance.c:1992 msgid "Right" msgstr "Вправо" #: ../../WPrefs.app/Appearance.c:2216 msgid "Appearance Preferences" msgstr "Внешний вид" #: ../../WPrefs.app/Appearance.c:2218 msgid "" "Background texture configuration for windows,\n" "menus and icons." msgstr "" "Конфигурация фоновых текстур для окон,\n" "меню и иконок." #: ../../WPrefs.app/Appearance.c:2263 msgid "Extract Texture" msgstr "Извлечь текстуру" #: ../../WPrefs.app/Appearance.c:2283 msgid "Textures" msgstr "Текстуры" #: ../../WPrefs.app/Appearance.c:2294 ../../WPrefs.app/WPrefs.c:302 msgid "Close" msgstr "Закрыть" #: ../../WPrefs.app/Appearance.c:2299 msgid "Extract" msgstr "Извлечь" #: ../../WPrefs.app/Configurations.c:150 ../../WPrefs.app/Configurations.c:156 #: ../../WPrefs.app/MouseSettings.c:490 ../../WPrefs.app/WindowHandling.c:339 #: ../../WPrefs.app/WindowHandling.c:351 ../../WPrefs.app/Workspace.c:90 #: ../../WPrefs.app/Workspace.c:101 #, c-format msgid "could not load icon %s" msgstr "не могу загрузить иконку %s" #: ../../WPrefs.app/Configurations.c:164 ../../WPrefs.app/Workspace.c:109 #, c-format msgid "could not process icon %s: %s" msgstr "не могу обработать иконку %s: %s" #: ../../WPrefs.app/Configurations.c:189 ../../WPrefs.app/Workspace.c:164 #, c-format msgid "could not load image file %s" msgstr "не могу загрузить файл изображения %s" #: ../../WPrefs.app/Configurations.c:203 msgid "Icon Slide Speed" msgstr "Скорость сдвига иконки" #: ../../WPrefs.app/Configurations.c:209 msgid "Shade Animation Speed" msgstr "Скорость сворачивания" # awn: как это нормально перевести, да так, чтобы поместилось? #: ../../WPrefs.app/Configurations.c:271 msgid "Smooth Scaling" msgstr "Гладкое масштабирование" #: ../../WPrefs.app/Configurations.c:272 msgid "" "Smooth scaled background images, neutralizing\n" "the `pixelization' effect. This will slow\n" "down loading of background images considerably." msgstr "" "Сглаживать (нажато) или нет (отпущено) масштабированные\n" "фоновые изображения. С одной стороны, это делает\n" "изображение более \"гладкими\", скрывая отдельные,\n" "увеличившиеся в размерах точки, но с другой стороны,\n" "увеличивает время, необходимое для загрузки фонового\n" "изображения." #: ../../WPrefs.app/Configurations.c:313 msgid "Titlebar Style" msgstr "Стиль заголовка" #: ../../WPrefs.app/Configurations.c:351 msgid "Animations and Sound" msgstr "Анимация и звук" #: ../../WPrefs.app/Configurations.c:357 msgid "Animations" msgstr "Анимация" #: ../../WPrefs.app/Configurations.c:368 msgid "" "Disable/enable animations such as those shown\n" "for window miniaturization, shading etc." msgstr "" "Запрещает/разрешает анимацию при сворачивании\n" "окон в иконку, линейку и т.п." #: ../../WPrefs.app/Configurations.c:376 msgid "Superfluous" msgstr "Излишества" #: ../../WPrefs.app/Configurations.c:387 msgid "" "Disable/enable `superfluous' features and\n" "animations. These include the `ghosting' of the\n" "dock when it's being moved to another side and\n" "the explosion animation when undocking icons." msgstr "" "Запрещает/разрешает различные `излишества'.\n" "Например, анимированный `взрыв' иконки при\n" "удалении ее из Дока." #: ../../WPrefs.app/Configurations.c:397 msgid "Sounds" msgstr "Звуки" #: ../../WPrefs.app/Configurations.c:408 msgid "" "Disable/enable support for sound effects played\n" "for actions like shading and closing a window.\n" "You will need a module distributed separately\n" "for this. You can get it at:\n" "http://shadowmere.student.utwente.nl/" msgstr "" "Запретить/разрешить звуковые эффекты для действий,\n" "наподобие свертки или закрытия окна. Для этого\n" "вам понадобится модуль, поставляемый отдельно.\n" "Вы можете загрузить его с:\n" "http://shadowmere.student.utwente.nl/" #: ../../WPrefs.app/Configurations.c:419 msgid "" "Note: sound requires a module distributed\n" "separately" msgstr "" "Замечание: для звука требуется отдельно\n" "поставляемый модуль" #: ../../WPrefs.app/Configurations.c:429 msgid "Dithering colormap for 8bpp" msgstr "Приведение палитры для 8bpp" #: ../../WPrefs.app/Configurations.c:431 msgid "" "Number of colors to reserve for Window Maker\n" "on displays that support only 8bpp (PseudoColor)." msgstr "" "Количество цветов, которое будет зарезервировано\n" "за Window Maker'ом в режиме 8bpp (PseudoColor)." #: ../../WPrefs.app/Configurations.c:438 msgid "Disable dithering in any visual/depth" msgstr "Запретить приведение палитры вообще" #: ../../WPrefs.app/Configurations.c:459 msgid "" "More colors for\n" "applications" msgstr "" "Больше цветов\n" "для\n" "приложений" #: ../../WPrefs.app/Configurations.c:466 msgid "" "More colors for\n" "Window Maker" msgstr "" "Больше цветов\n" "для\n" "Window Maker'а" #: ../../WPrefs.app/Configurations.c:521 msgid "Other Configurations" msgstr "Другие настройки" #: ../../WPrefs.app/Configurations.c:523 msgid "" "Animation speeds, titlebar styles, various option\n" "toggling and number of colors to reserve for\n" "Window Maker on 8bit displays." msgstr "" "Скорость анимации, стили заголовков, переключение различных\n" "параметров и количества цветов для резервирования за\n" "Window Maker'ом при работе с 8bit'ным цветом (8bpp)." -#: ../../WPrefs.app/Expert.c:75 -msgid "" -"Disable miniwindows (icons for miniaturized windows). For use with KDE/GNOME." -msgstr "" -"Запретить миниокна (иконки для минимизированных окон). Для использования с " -"KDE/GNOME." +#: ../../WPrefs.app/Expert.c:44 +msgid "Disable miniwindows (icons for minimized windows). For use with KDE/GNOME." +msgstr "Запретить миниокна иконки для минимизированных окон. Для использования с KDE/GNOME." + +#: ../../WPrefs.app/Expert.c:47 +msgid "Ignore decoration hints for GTK applications." +msgstr "Игнорировать декорацию окон для GTK приложений." -#: ../../WPrefs.app/Expert.c:76 +#: ../../WPrefs.app/Expert.c:53 msgid "Do not set non-WindowMaker specific parameters (do not use xset)." msgstr "" "Не устанавливать параметры, не относящиеся непосредственно к\n" "Window Maker'у (не использовать xset)." -#: ../../WPrefs.app/Expert.c:77 +#: ../../WPrefs.app/Expert.c:56 msgid "Automatically save session when exiting Window Maker." msgstr "Автоматически сохранять сессию при выходе из Window Maker'а." -#: ../../WPrefs.app/Expert.c:78 +#: ../../WPrefs.app/Expert.c:59 msgid "Use SaveUnder in window frames, icons, menus and other objects." msgstr "Использовать SaveUnder для окон, иконок, меню и других объектов." -#: ../../WPrefs.app/Expert.c:79 -msgid "Use Windoze style cycling." -msgstr "Переключение окон в стиле Windows" - -#: ../../WPrefs.app/Expert.c:80 +#: ../../WPrefs.app/Expert.c:62 msgid "Disable confirmation panel for the Kill command." msgstr "Запретить диалог подтверждения для команды `Убить'." -# awn: FIXME: что это вообще значит? -#: ../../WPrefs.app/Expert.c:81 msgid "Disable selection animation for selected icons." msgstr "Запретить анимацию выбора для выбранных иконок." -#: ../../WPrefs.app/Expert.c:115 +msgid "Show switch panel when cycling windows." +msgstr "Показывать панель переключения окон." + +#: ../../WPrefs.app/Expert.c:68 +msgid "Smooth font edges (needs restart)." +msgstr "Cглаживание шрифтов (требуется перезагрузка)." + +#: ../../WPrefs.app/Expert.c:80 +msgid "Show workspace title on Clip." +msgstr "Показывать имя рабочего места на скрепке." + +#: ../../WPrefs.app/Expert.c:83 +msgid "Highlight the icon of the application when it has the focus." +msgstr "Подсвечивание иконок при нажатии (в фокусе)." + +#: ../../WPrefs.app/Expert.c:91 +msgid "Maximize (snap) a window to edge or corner by dragging." +msgstr "Прилипания окон по краям и углам." + +#: ../../WPrefs.app/Expert.c:100 +msgid "Snapping a window to the top maximizes it to the full screen." +msgstr "Распахнуть окно при перетаскивании к верхнему краю." + + +#: ../../WPrefs.app/Expert.c:118 +msgid "Double click on titlebar maximize a window to full screen." +msgstr "Распахнуть окно двойным щелчком." + +#: ../../WPrefs.app/Expert.c:328 msgid "Expert User Preferences" msgstr "Установки для опытного пользователя" -#: ../../WPrefs.app/Expert.c:117 +#: ../../WPrefs.app/Expert.c:330 msgid "" "Options for people who know what they're doing...\n" "Also have some other misc. options." msgstr "" "Параметры, предназначенные для людей,\n" "которые знают, что делают...\n" "Также содержит некоторые другие,\n" "редко используемые параметры." #: ../../WPrefs.app/Focus.c:80 #, c-format msgid "bad option value %s for option FocusMode. Using default Manual" msgstr "неверное значение %s для FocusMode. Используем Manual" #: ../../WPrefs.app/Focus.c:94 #, c-format msgid "bad option value %s for option ColormapMode. Using default Auto" msgstr "неверное значение %s для ColormapMode. Используем Auto" #: ../../WPrefs.app/Focus.c:214 msgid "Input Focus Mode" msgstr "Режим фокуса ввода" #: ../../WPrefs.app/Focus.c:222 msgid "Manual: Click on the window to set keyboard input focus" msgstr "Вручную: Щелкните на окне, для передачи ему фокуса ввода" #: ../../WPrefs.app/Focus.c:229 msgid "Auto: Set keyboard input focus to the window under the mouse pointer" msgstr "Автоматически: Фокус клавиатурного ввода передается окну, находящемуся под курсором мыши" #: ../../WPrefs.app/Focus.c:243 msgid "Install colormap from the window..." msgstr "Устанавливать палитру окна..." #: ../../WPrefs.app/Focus.c:248 msgid "...that has the input focus" msgstr "...имеющего фокус ввода" #: ../../WPrefs.app/Focus.c:253 msgid "...that's under the mouse pointer" msgstr "...находящегося под курсором мыши" #: ../../WPrefs.app/Focus.c:262 msgid "Automatic Window Raise Delay" msgstr "Всплывать через..." #: ../../WPrefs.app/Focus.c:319 ../../WPrefs.app/MouseSettings.c:601 msgid "ms" msgstr "Мсек" #: ../../WPrefs.app/Focus.c:336 msgid "Do not let applications receive the click used to focus windows" msgstr "Не передавать приложениям щелчок мыши,сделанный для фокусировки" #: ../../WPrefs.app/Focus.c:342 msgid "Automatically focus new windows" msgstr "Автоматически передавать фокус новым окнам" #: ../../WPrefs.app/Focus.c:363 msgid "Window Focus Preferences" msgstr "Параметры для фокусировки окна" #: ../../WPrefs.app/Focus.c:365 msgid "" "Keyboard focus switching policy, colormap switching\n" "policy for 8bpp displays and other related options." msgstr "" "Политика переключения фокуса клавиатуры,\n" "политика переключения цветовой палитры для 8bpp\n" "и тому подобные параметры." #: ../../WPrefs.app/Font.c:276 msgid "Could not locate font information file WPrefs.app/font.data" msgstr "" #: ../../WPrefs.app/Font.c:282 msgid "Could not read font information file WPrefs.app/font.data" msgstr "" #: ../../WPrefs.app/Font.c:293 msgid "" "Invalid data in font information file WPrefs.app/font.data.\n" "Encodings data not found." msgstr "" #: ../../WPrefs.app/Font.c:298 msgid "- Custom -" msgstr "" #: ../../WPrefs.app/Font.c:329 ../../WPrefs.app/Menu.c:1594 #: ../../WPrefs.app/MouseSettings.c:140 ../../WPrefs.app/MouseSettings.c:160 #: ../../WPrefs.app/TexturePanel.c:613 ../../WPrefs.app/TexturePanel.c:693 #: ../../WPrefs.app/Themes.c:96 ../../WPrefs.app/WPrefs.c:758 #: ../../WPrefs.app/WPrefs.c:763 ../../WPrefs.app/WPrefs.c:780 #: ../../WPrefs.app/WPrefs.c:790 ../../WPrefs.app/WPrefs.c:800 #: ../../WPrefs.app/WPrefs.c:838 ../../WPrefs.app/WPrefs.c:843 msgid "Error" msgstr "Ошибка" #: ../../WPrefs.app/Font.c:329 ../../WPrefs.app/Menu.c:1594 #: ../../WPrefs.app/MouseSettings.c:142 ../../WPrefs.app/MouseSettings.c:162 #: ../../WPrefs.app/TexturePanel.c:614 ../../WPrefs.app/TexturePanel.c:695 #: ../../WPrefs.app/TexturePanel.c:1528 ../../WPrefs.app/Themes.c:98 #: ../../WPrefs.app/WPrefs.c:758 ../../WPrefs.app/WPrefs.c:763 #: ../../WPrefs.app/WPrefs.c:782 ../../WPrefs.app/WPrefs.c:794 #: ../../WPrefs.app/WPrefs.c:800 ../../WPrefs.app/WPrefs.c:807 #: ../../WPrefs.app/WPrefs.c:838 ../../WPrefs.app/WPrefs.c:843 #: ../../WPrefs.app/imagebrowser.c:105 msgid "OK" msgstr "OK" #: ../../WPrefs.app/Font.c:376 msgid "Default Font Sets" msgstr "" #: ../../WPrefs.app/Font.c:389 msgid "Font Set" msgstr "" #: ../../WPrefs.app/Font.c:418 msgid "Add..." msgstr "Добавить..." #: ../../WPrefs.app/Font.c:423 ../../WPrefs.app/Font.c:438 msgid "Change..." msgstr "Изменить..." #: ../../WPrefs.app/Font.c:428 ../../WPrefs.app/Paths.c:288 #: ../../WPrefs.app/Paths.c:319 msgid "Remove" msgstr "Удалить" #: ../../WPrefs.app/Font.c:477 msgid "Font Preferences" msgstr "Установки для шрифтов" #: ../../WPrefs.app/Font.c:478 msgid "Font Configurations for Windows, Menus etc" msgstr "Конфигурация Шрифтов для Окон, Меню и т.п." #: ../../WPrefs.app/Icons.c:180 msgid "Icon Positioning" msgstr "Расположение иконок" #: ../../WPrefs.app/Icons.c:227 msgid "Iconification Animation" msgstr "Анимирование сворачивания" #: ../../WPrefs.app/Icons.c:238 msgid "Shrinking/Zooming" msgstr "Сжатие/Распахивание" #: ../../WPrefs.app/Icons.c:239 msgid "Spinning/Twisting" msgstr "Вращение в плоскости" #: ../../WPrefs.app/Icons.c:240 msgid "3D-flipping" msgstr "Трехмерное вращение" #: ../../WPrefs.app/Icons.c:241 ../../WPrefs.app/MouseSettings.c:838 #: ../../WPrefs.app/MouseSettings.c:843 msgid "None" msgstr "Без оного" #: ../../WPrefs.app/Icons.c:254 msgid "Auto-arrange icons" msgstr "Автоматически выравнивать иконки" #: ../../WPrefs.app/Icons.c:256 msgid "Keep icons and miniwindows arranged all the time." msgstr "Поддерживать иконки и миниокна постоянно выровненными." #: ../../WPrefs.app/Icons.c:262 msgid "Omnipresent miniwindows" msgstr "Миниокна присутствуют везде" #: ../../WPrefs.app/Icons.c:264 msgid "Make miniwindows be present in all workspaces." msgstr "" "Сделать миниокна присутствующими сразу на всех\n" "рабочих пространствах." #: ../../WPrefs.app/Icons.c:273 msgid "Icon Size" msgstr "Размер иконок" #: ../../WPrefs.app/Icons.c:275 msgid "The size of the dock/application icon and miniwindows" msgstr "Размер миниокон и иконок приложений/дока" #: ../../WPrefs.app/Icons.c:345 msgid "Icon Preferences" msgstr "Установки для иконок" #: ../../WPrefs.app/Icons.c:347 msgid "" "Icon/Miniwindow handling options. Icon positioning\n" "area, sizes of icons, miniaturization animation style." msgstr "" "Параметры обработки иконок и миниокон. Размещение иконок,\n" "размер иконок, в каком стиле анимировать сворачивание." +#: ../../WPrefs.app/Icons.c:414 +msgid "Single click activation" +msgstr "Одинарный щелчок мыши" + + #: ../../WPrefs.app/imagebrowser.c:95 msgid "View" msgstr "" #: ../../WPrefs.app/KeyboardShortcuts.c:306 ../../WPrefs.app/Menu.c:360 #: ../../WPrefs.app/TexturePanel.c:1534 ../../WPrefs.app/imagebrowser.c:100 msgid "Cancel" msgstr "Отмена" #: ../../WPrefs.app/KeyboardSettings.c:73 msgid "Initial Key Repeat" msgstr "" #: ../../WPrefs.app/KeyboardSettings.c:114 msgid "Key Repeat Rate" msgstr "Скорость повторения клавиши" #: ../../WPrefs.app/KeyboardSettings.c:154 msgid "Type here to test" msgstr "Для теста пишите сюда" #: ../../WPrefs.app/KeyboardSettings.c:173 msgid "Keyboard Preferences" msgstr "Установки для клавиатуры" #: ../../WPrefs.app/KeyboardSettings.c:175 msgid "Not done" msgstr "Не закончено" #: ../../WPrefs.app/KeyboardShortcuts.c:307 msgid "Press the desired shortcut key(s) or click Cancel to stop capturing." msgstr "Нажмите клавишу(ы) или нажмите Отмена для остановки." #: ../../WPrefs.app/KeyboardShortcuts.c:327 #: ../../WPrefs.app/KeyboardShortcuts.c:577 ../../WPrefs.app/Menu.c:371 #: ../../WPrefs.app/Menu.c:830 msgid "Capture" msgstr "Захват" #: ../../WPrefs.app/KeyboardShortcuts.c:328 #: ../../WPrefs.app/KeyboardShortcuts.c:585 msgid "Click Capture to interactively define the shortcut key." msgstr "Нажмите \"Захват\" чтобы определить горячую клавишу(ы)." #: ../../WPrefs.app/KeyboardShortcuts.c:483 msgid "Actions" msgstr "Действия" #: ../../WPrefs.app/KeyboardShortcuts.c:499 msgid "Open applications menu" msgstr "Открыть меню приложений" #: ../../WPrefs.app/KeyboardShortcuts.c:500 msgid "Open window list menu" msgstr "Список окон" #: ../../WPrefs.app/KeyboardShortcuts.c:501 msgid "Open window commands menu" msgstr "Команды для окна" #: ../../WPrefs.app/KeyboardShortcuts.c:502 msgid "Hide active application" msgstr "Скрыть активное приложение" #: ../../WPrefs.app/KeyboardShortcuts.c:503 msgid "Hide other applications" msgstr "Скрыть другие приложения" #: ../../WPrefs.app/KeyboardShortcuts.c:504 msgid "Miniaturize active window" msgstr "Свернуть активное окно" #: ../../WPrefs.app/KeyboardShortcuts.c:505 msgid "Close active window" msgstr "Закрыть активное окно" #: ../../WPrefs.app/KeyboardShortcuts.c:506 msgid "Maximize active window" msgstr "Распахнуть активное окно" #: ../../WPrefs.app/KeyboardShortcuts.c:507 msgid "Maximize active window vertically" msgstr "Распахнуть активное окно по вертикали" #: ../../WPrefs.app/KeyboardShortcuts.c:508 msgid "Maximize active window horizontally" msgstr "Распахнуть активное окно по вертикали" #: ../../WPrefs.app/KeyboardShortcuts.c:509 msgid "Raise active window" msgstr "Активное окно наверх" #: ../../WPrefs.app/KeyboardShortcuts.c:510 msgid "Lower active window" msgstr "Активное окно вниз" #: ../../WPrefs.app/KeyboardShortcuts.c:511 msgid "Raise/Lower window under mouse pointer" msgstr "Вверх/Вниз активное окно" #: ../../WPrefs.app/KeyboardShortcuts.c:512 msgid "Shade active window" msgstr "Втянуть активное окно" #: ../../WPrefs.app/KeyboardShortcuts.c:513 msgid "Move/Resize active window" msgstr "Переместить/изменить размер" #: ../../WPrefs.app/KeyboardShortcuts.c:514 msgid "Select active window" msgstr "Пометить активное окно" #: ../../WPrefs.app/KeyboardShortcuts.c:515 msgid "Focus next window" msgstr "Следующее окно" #: ../../WPrefs.app/KeyboardShortcuts.c:516 msgid "Focus previous window" msgstr "Предыдущее окно" #: ../../WPrefs.app/KeyboardShortcuts.c:517 msgid "Switch to next workspace" msgstr "Следующее рабочее пространство" #: ../../WPrefs.app/KeyboardShortcuts.c:518 msgid "Switch to previous workspace" msgstr "Предыдущее рабочее пространство" #: ../../WPrefs.app/KeyboardShortcuts.c:519 msgid "Switch to next ten workspaces" msgstr "Следующие 10 рабочих пространств" #: ../../WPrefs.app/KeyboardShortcuts.c:520 msgid "Switch to previous ten workspaces" msgstr "Предыдущие 10 рабочих пространств" #: ../../WPrefs.app/KeyboardShortcuts.c:521 msgid "Switch to workspace 1" msgstr "Рабочее пространство 1" #: ../../WPrefs.app/KeyboardShortcuts.c:522 msgid "Switch to workspace 2" msgstr "Рабочее пространство 2" #: ../../WPrefs.app/KeyboardShortcuts.c:523 msgid "Switch to workspace 3" msgstr "Рабочее пространство 3" #: ../../WPrefs.app/KeyboardShortcuts.c:524 msgid "Switch to workspace 4" msgstr "Рабочее пространство 4" #: ../../WPrefs.app/KeyboardShortcuts.c:525 msgid "Switch to workspace 5" msgstr "Рабочее пространство 5" #: ../../WPrefs.app/KeyboardShortcuts.c:526 msgid "Switch to workspace 6" msgstr "Рабочее пространство 6" #: ../../WPrefs.app/KeyboardShortcuts.c:527 msgid "Switch to workspace 7" msgstr "Рабочее пространство 7" #: ../../WPrefs.app/KeyboardShortcuts.c:528 msgid "Switch to workspace 8" msgstr "Рабочее пространство 8" #: ../../WPrefs.app/KeyboardShortcuts.c:529 msgid "Switch to workspace 9" msgstr "Рабочее пространство 9" #: ../../WPrefs.app/KeyboardShortcuts.c:530 msgid "Switch to workspace 10" msgstr "Рабочее пространство 10" #: ../../WPrefs.app/KeyboardShortcuts.c:531 msgid "Shortcut for window 1" msgstr "Горячая клавиша 1" #: ../../WPrefs.app/KeyboardShortcuts.c:532 msgid "Shortcut for window 2" msgstr "Горячая клавиша 2" #: ../../WPrefs.app/KeyboardShortcuts.c:533 msgid "Shortcut for window 3" msgstr "Горячая клавиша 3" #: ../../WPrefs.app/KeyboardShortcuts.c:534 msgid "Shortcut for window 4" msgstr "Горячая клавиша 4" #: ../../WPrefs.app/KeyboardShortcuts.c:535 msgid "Shortcut for window 5" msgstr "Горячая клавиша 5" #: ../../WPrefs.app/KeyboardShortcuts.c:536 msgid "Shortcut for window 6" msgstr "Горячая клавиша 6" #: ../../WPrefs.app/KeyboardShortcuts.c:537 msgid "Shortcut for window 7" msgstr "Горячая клавиша 7" #: ../../WPrefs.app/KeyboardShortcuts.c:538 msgid "Shortcut for window 8" msgstr "Горячая клавиша 8" #: ../../WPrefs.app/KeyboardShortcuts.c:539 msgid "Shortcut for window 9" msgstr "Горячая клавиша 9" #: ../../WPrefs.app/KeyboardShortcuts.c:540 msgid "Shortcut for window 10" msgstr "Горячая клавиша 10" #: ../../WPrefs.app/KeyboardShortcuts.c:541 msgid "Switch to Next Screen/Monitor" msgstr "Следующий экран/монитор" #: ../../WPrefs.app/KeyboardShortcuts.c:542 msgid "Raise Clip" msgstr "Поднять Скрепку" #: ../../WPrefs.app/KeyboardShortcuts.c:543 msgid "Lower Clip" msgstr "Опустить Скрепку" #: ../../WPrefs.app/KeyboardShortcuts.c:544 msgid "Raise/Lower Clip" msgstr "Поднять/Опустить Скрепку" #: ../../WPrefs.app/KeyboardShortcuts.c:546 msgid "Toggle keyboard language" msgstr "Переключить язык клавиатуры" #: ../../WPrefs.app/KeyboardShortcuts.c:560 msgid "Shortcut" msgstr "Горячая клавиша" #: ../../WPrefs.app/KeyboardShortcuts.c:571 ../../WPrefs.app/Menu.c:836 msgid "Clear" msgstr "Очистить" #: ../../WPrefs.app/KeyboardShortcuts.c:633 msgid "Keyboard Shortcut Preferences" msgstr "Горячие клавиши" #: ../../WPrefs.app/KeyboardShortcuts.c:635 msgid "" "Change the keyboard shortcuts for actions such\n" "as changing workspaces and opening menus." msgstr "" "Изменить привязку клавиш для функций наподобие\n" "`переключить рабочее пространство' и `открыть меню'." #: ../../WPrefs.app/main.c:59 #, c-format msgid "usage: %s [options]\n" msgstr "Запуск: %s [параметры]\n" #: ../../WPrefs.app/main.c:60 msgid "options:" msgstr "Параметры:" #: ../../WPrefs.app/main.c:61 msgid " -display <display>\tdisplay to be used" msgstr " -display <дисплей>\tX дисплей для использования" #: ../../WPrefs.app/main.c:62 msgid " --version\t\tprint version number and exit" msgstr " --version\t\tпоказать номер версии и выйти" #: ../../WPrefs.app/main.c:63 msgid " --help\t\tprint this message and exit" msgstr " --help\t\tпоказать это сообщение и выйти" #: ../../WPrefs.app/main.c:122 #, c-format msgid "too few arguments for %s" msgstr "слишком мало аргументов для %s" #: ../../WPrefs.app/main.c:144 msgid "X server does not support locale" msgstr "X сервер не поддерживает locale" #: ../../WPrefs.app/main.c:147 msgid "cannot set locale modifiers" msgstr "не получается установить модификаторы локализации" #: ../../WPrefs.app/main.c:153 #, c-format msgid "could not open display %s" msgstr "не могу открыть дисплей %s" #: ../../WPrefs.app/main.c:161 msgid "could not initialize application" msgstr "не получается инициализировать приложение" #: ../../WPrefs.app/Menu.c:278 msgid "Select Program" msgstr "Выберите программу" #: ../../WPrefs.app/Menu.c:510 msgid "New Items" msgstr "Новые элементы" #: ../../WPrefs.app/Menu.c:511 msgid "Sample Commands" msgstr "Примеры команд" #: ../../WPrefs.app/Menu.c:512 msgid "Sample Submenus" msgstr "Примеры подменю" #: ../../WPrefs.app/Menu.c:526 msgid "Run Program" msgstr "Запуск программы" #: ../../WPrefs.app/Menu.c:527 msgid "Internal Command" msgstr "Внутренняя команда" #: ../../WPrefs.app/Menu.c:528 msgid "Submenu" msgstr "Подменю" #: ../../WPrefs.app/Menu.c:529 msgid "External Submenu" msgstr "Внешнее подменю" #: ../../WPrefs.app/Menu.c:530 msgid "Generated Submenu" msgstr "Сгенерированное подменю" #: ../../WPrefs.app/Menu.c:531 msgid "Directory Contents" msgstr "Содержание каталога" #: ../../WPrefs.app/Menu.c:532 msgid "Workspace Menu" msgstr "Меню рабочих пространств" #: ../../WPrefs.app/Menu.c:533 ../../WPrefs.app/MouseSettings.c:840 msgid "Window List Menu" msgstr "Меню списка окон" #: ../../WPrefs.app/Menu.c:552 msgid "XTerm" msgstr "XTerm" #: ../../WPrefs.app/Menu.c:555 msgid "rxvt" msgstr "rxvt" #: ../../WPrefs.app/Menu.c:558 msgid "ETerm" msgstr "ETerm" #: ../../WPrefs.app/Menu.c:561 msgid "Run..." msgstr "" #: ../../WPrefs.app/Menu.c:562 msgid "%a(Run,Type command to run)" msgstr "" #: ../../WPrefs.app/Menu.c:564 msgid "Netscape" msgstr "Netscape" #: ../../WPrefs.app/Menu.c:567 msgid "gimp" msgstr "gimp" #: ../../WPrefs.app/Menu.c:570 msgid "epic" msgstr "epic" #: ../../WPrefs.app/Menu.c:573 msgid "ee" msgstr "ee" #: ../../WPrefs.app/Menu.c:576 msgid "xv" msgstr "xv" #: ../../WPrefs.app/Menu.c:579 msgid "Acrobat Reader" msgstr "Acrobat Reader" #: ../../WPrefs.app/Menu.c:582 msgid "ghostview" msgstr "ghostview" #: ../../WPrefs.app/Menu.c:585 ../../WPrefs.app/Menu.c:857 msgid "Exit Window Maker" msgstr "Выйти из Window Maker'а" #: ../../WPrefs.app/Menu.c:608 msgid "Debian Menu" msgstr "" #: ../../WPrefs.app/Menu.c:611 msgid "RedHat Menu" msgstr "" #: ../../WPrefs.app/Menu.c:614 msgid "Menu Conectiva" msgstr "" #: ../../WPrefs.app/Menu.c:617 ../../WPrefs.app/Themes.c:250 msgid "Themes" msgstr "Темы" #: ../../WPrefs.app/Menu.c:622 msgid "Bg Images (scale)" msgstr "" #: ../../WPrefs.app/Menu.c:627 msgid "Bg Images (tile)" msgstr "" #: ../../WPrefs.app/Menu.c:632 msgid "Assorted XTerms" msgstr "Различные XTerm'ы" #: ../../WPrefs.app/Menu.c:634 msgid "XTerm Yellow on Blue" msgstr "XTerm (желтое на синем)" #: ../../WPrefs.app/Menu.c:637 msgid "XTerm White on Black" msgstr "XTerm (белое на черном)" #: ../../WPrefs.app/Menu.c:640 msgid "XTerm Black on White" msgstr "XTerm (черное на белом)" #: ../../WPrefs.app/Menu.c:643 msgid "XTerm Black on Beige" msgstr "XTerm (черное на серо-зеленом)" #: ../../WPrefs.app/Menu.c:646 msgid "XTerm White on Green" msgstr "XTerm (белое на зеленом)" #: ../../WPrefs.app/Menu.c:649 msgid "XTerm White on Olive" msgstr "XTerm (белое на темно-оливковом)" #: ../../WPrefs.app/Menu.c:652 msgid "XTerm Blue on Blue" msgstr "XTerm (серо-синее на темно-серо-синем)" #: ../../WPrefs.app/Menu.c:655 msgid "XTerm BIG FONTS" msgstr "XTerm (шрифт 10x20)" #: ../../WPrefs.app/Menu.c:677 msgid "Program to Run" msgstr "Программа" #: ../../WPrefs.app/Menu.c:687 msgid "Browse" msgstr "Выбрать" #: ../../WPrefs.app/Menu.c:698 msgid "Run the program inside a Xterm" msgstr "Запускать в XTerm'е" #: ../../WPrefs.app/Menu.c:708 msgid "Path for Menu" msgstr "Путь к меню" #: ../../WPrefs.app/Menu.c:721 msgid "" "Enter the path for a file containing a menu\n" "or a list of directories with the programs you\n" "want to have listed in the menu. Ex:\n" "~/GNUstep/Library/WindowMaker/menu\n" "or\n" "/usr/bin ~/xbin" msgstr "" "Введите путь к файлу, содержащему меню,\n" "или список с программами, которые вы хотите\n" "видеть перечисленными в меню, Например:\n" " ~/GNUstep/Library/WindowMaker/menu\n" "или\n" " /usr/bin ~/xbin" #: ../../WPrefs.app/Menu.c:736 msgid "Command" msgstr "Команда" #: ../../WPrefs.app/Menu.c:750 msgid "" "Enter a command that outputs a menu\n" "definition to stdout when invoked." msgstr "" "Введите команду, которая, будучи исполненной,\n" "выводит на stdout определение меню." #: ../../WPrefs.app/Menu.c:758 msgid "" "Cache menu contents after opening for\n" "the first time" msgstr "Кэшировать содержимое меню" #: ../../WPrefs.app/Menu.c:769 msgid "Command to Open Files" msgstr "Команда для открытия файлов" @@ -1392,755 +1420,775 @@ msgstr "" #: ../../WPrefs.app/MouseSettings.c:382 msgid "could not retrieve keyboard modifier mapping" msgstr "" #: ../../WPrefs.app/MouseSettings.c:477 msgid "Mouse Speed" msgstr "Скорость мыши" #: ../../WPrefs.app/MouseSettings.c:507 msgid "Accel.:" msgstr "Ускор.:" #: ../../WPrefs.app/MouseSettings.c:520 msgid "Threshold:" msgstr "Чувствит:" #: ../../WPrefs.app/MouseSettings.c:535 msgid "Double-Click Delay" msgstr "Задержка двойного щелчка" #: ../../WPrefs.app/MouseSettings.c:579 msgid "Test" msgstr "Тест" #: ../../WPrefs.app/MouseSettings.c:609 msgid "Workspace Mouse Actions" msgstr "Действия мыши на р/столе" #: ../../WPrefs.app/MouseSettings.c:614 msgid "Disable mouse actions" msgstr "Отключить мышь" #: ../../WPrefs.app/MouseSettings.c:620 msgid "Left Button" msgstr "Левая кнопка" #: ../../WPrefs.app/MouseSettings.c:630 msgid "Middle Button" msgstr "Средняя кнопка" #: ../../WPrefs.app/MouseSettings.c:640 msgid "Right Button" msgstr "Правая кнопка" #: ../../WPrefs.app/MouseSettings.c:650 msgid "Mouse Wheel" msgstr "Колесико мыши" #: ../../WPrefs.app/MouseSettings.c:672 msgid "Mouse Grab Modifier" msgstr "Модификатор захвата мыши" #: ../../WPrefs.app/MouseSettings.c:674 msgid "" "Keyboard modifier to use for actions that\n" "involve dragging windows with the mouse,\n" "clicking inside the window." msgstr "" #: ../../WPrefs.app/MouseSettings.c:708 #, c-format msgid "could not create %s" msgstr "не могу создать %s" #: ../../WPrefs.app/MouseSettings.c:724 #, c-format msgid "could not create temporary file %s" msgstr "не могу создать временный файл %s" #: ../../WPrefs.app/MouseSettings.c:756 #, c-format msgid "could not rename file %s to %s\n" msgstr "не получается переименовать %s в %s\n" #: ../../WPrefs.app/MouseSettings.c:829 msgid "Shift" msgstr "Shift" #: ../../WPrefs.app/MouseSettings.c:830 msgid "Lock" msgstr "" #: ../../WPrefs.app/MouseSettings.c:831 msgid "Control" msgstr "Control" #: ../../WPrefs.app/MouseSettings.c:832 msgid "Mod1" msgstr "Mod1" #: ../../WPrefs.app/MouseSettings.c:833 msgid "Mod2" msgstr "Mod2" #: ../../WPrefs.app/MouseSettings.c:834 msgid "Mod3" msgstr "Mod3" #: ../../WPrefs.app/MouseSettings.c:835 msgid "Mod4" msgstr "Mod4" #: ../../WPrefs.app/MouseSettings.c:836 msgid "Mod5" msgstr "Mod5" #: ../../WPrefs.app/MouseSettings.c:839 msgid "Applications Menu" msgstr "Меню приложений" #: ../../WPrefs.app/MouseSettings.c:841 msgid "Select Windows" msgstr "Выделение окон" # awn: "Переключение рабочих пространств" не помещается #: ../../WPrefs.app/MouseSettings.c:844 msgid "Switch Workspaces" msgstr "" #: ../../WPrefs.app/MouseSettings.c:849 msgid "Mouse Preferences" msgstr "Свойства для мыши" #: ../../WPrefs.app/MouseSettings.c:851 msgid "" "Mouse speed/acceleration, double click delay,\n" "mouse button bindings etc." msgstr "" "Скорость и ускорение мыши, задержка двойного щелчка,\n" "функции, привязанные к кнопкам мыши и т.п." #: ../../WPrefs.app/Paths.c:84 msgid "bad value in option IconPath. Using default path list" msgstr "неправильное значение в IconPath. Используем пути по умолчанию" #: ../../WPrefs.app/Paths.c:101 msgid "bad value in option PixmapPath. Using default path list" msgstr "неправильное значение в PixmapPath. Используем пути по умолчанию" #: ../../WPrefs.app/Paths.c:149 msgid "Select directory" msgstr "Укажите каталог" #: ../../WPrefs.app/Paths.c:270 msgid "Icon Search Paths" msgstr "Пути поиска иконок" #: ../../WPrefs.app/Paths.c:281 ../../WPrefs.app/Paths.c:312 #: ../../WPrefs.app/TexturePanel.c:1310 msgid "Add" msgstr "Добавить" #: ../../WPrefs.app/Paths.c:301 msgid "Pixmap Search Paths" msgstr "Пути поиска Pixmap" #: ../../WPrefs.app/Paths.c:341 msgid "Search Path Configuration" msgstr "Конфигурация путей поиска" #: ../../WPrefs.app/Paths.c:343 msgid "" "Search paths to use when looking for pixmaps\n" "and icons." msgstr "" "Пути, используемые для поиска pixmap'ов\n" "и иконок." #: ../../WPrefs.app/Preferences.c:75 msgid "OFF" msgstr "Выключено" #: ../../WPrefs.app/Preferences.c:77 msgid "1 pixel" msgstr "1 точка" #. 2-4 #: ../../WPrefs.app/Preferences.c:80 #, c-format msgid "%i pixels" msgstr "%i точки" #. >4 #: ../../WPrefs.app/Preferences.c:83 #, c-format msgid "%i pixels " msgstr "%i точек" #: ../../WPrefs.app/Preferences.c:229 msgid "Size Display" msgstr "Отображение размера" #: ../../WPrefs.app/Preferences.c:231 msgid "" "The position or style of the window size\n" "display that's shown when a window is resized." msgstr "" "Где и/или в каком стиле отображать размеры окна\n" "при их изменении." #: ../../WPrefs.app/Preferences.c:238 ../../WPrefs.app/Preferences.c:259 msgid "Corner of screen" msgstr "В углу экрана" #: ../../WPrefs.app/Preferences.c:239 ../../WPrefs.app/Preferences.c:260 msgid "Center of screen" msgstr "В центре экрана" #: ../../WPrefs.app/Preferences.c:240 ../../WPrefs.app/Preferences.c:261 msgid "Center of resized window" msgstr "В центре изменяемого окна" #: ../../WPrefs.app/Preferences.c:241 msgid "Technical drawing-like" msgstr "В чертежном стиле" #: ../../WPrefs.app/Preferences.c:242 ../../WPrefs.app/Preferences.c:262 msgid "Disabled" msgstr "Запрещено" #: ../../WPrefs.app/Preferences.c:250 msgid "Position Display" msgstr "Отображение положения" #: ../../WPrefs.app/Preferences.c:252 msgid "" "The position or style of the window position\n" "display that's shown when a window is moved." msgstr "" "Где и/или в каком стиле отображать положение окна\n" "при его перемещении." #: ../../WPrefs.app/Preferences.c:270 msgid "Show balloon text for..." msgstr "Показывать всплывающую подсказку для..." #: ../../WPrefs.app/Preferences.c:277 msgid "incomplete window titles" msgstr "неполных заголовков окон" #: ../../WPrefs.app/Preferences.c:278 msgid "miniwindow titles" msgstr "заголовков миниокон" #: ../../WPrefs.app/Preferences.c:279 msgid "application/dock icons" msgstr "иконок в доке/скрепке" #: ../../WPrefs.app/Preferences.c:280 msgid "internal help" msgstr "внутренней помощи" #: ../../WPrefs.app/Preferences.c:292 msgid "Raise window when switching focus with keyboard" msgstr "Поднимать окно при переключениифокуса с клавиатуры" #: ../../WPrefs.app/Preferences.c:298 #, fuzzy msgid "" "Enable keyboard language\n" "switch button in window titlebars." msgstr "Сохранять язык клавиатуры для каждого окна" #: ../../WPrefs.app/Preferences.c:307 msgid "Workspace border" msgstr "Границы рабочего пространства" #: ../../WPrefs.app/Preferences.c:323 msgid "Left/Right" msgstr "Слева/Справа" #: ../../WPrefs.app/Preferences.c:328 msgid "Top/Bottom" msgstr "Сверху/Снизу" #: ../../WPrefs.app/Preferences.c:349 msgid "Miscellaneous Ergonomic Preferences" msgstr "Всякие эргономические установки" #: ../../WPrefs.app/Preferences.c:350 msgid "" "Various settings like balloon text, geometry\n" "displays etc." msgstr "" "Различные установки, наподобие\n" "\"когда показывать всплывающие подсказки?\",\n" "\"как отображать изменение геометрии?\" и т.п." #: ../../WPrefs.app/TexturePanel.c:323 msgid "Saturation" msgstr "Насыщенность" #: ../../WPrefs.app/TexturePanel.c:325 msgid "Brightness" msgstr "Яркость" #: ../../WPrefs.app/TexturePanel.c:373 ../../WPrefs.app/TexturePanel.c:380 msgid "Hue" msgstr "Тон" #: ../../WPrefs.app/TexturePanel.c:610 msgid "Could not load the selected file: " msgstr "Не могу загрузить выбранный файл" #: ../../WPrefs.app/TexturePanel.c:664 msgid "Open Image" msgstr "Открыть изображение" #: ../../WPrefs.app/TexturePanel.c:694 msgid "The selected file does not contain a supported image." msgstr "Выбранный файл не содержит изображения в поддерживаемом формате." #: ../../WPrefs.app/TexturePanel.c:945 #, c-format msgid "could not load file '%s': %s" msgstr "не могу загрузить файл '%s': %s" #: ../../WPrefs.app/TexturePanel.c:1064 #, c-format msgid "error creating texture %s" msgstr "ошибка создания текстуры %s" #: ../../WPrefs.app/TexturePanel.c:1254 msgid "Texture Panel" msgstr "Панель текстур" #: ../../WPrefs.app/TexturePanel.c:1262 msgid "Texture Name" msgstr "Название текстуры" #: ../../WPrefs.app/TexturePanel.c:1274 msgid "Solid Color" msgstr "Равномерный цвет" #: ../../WPrefs.app/TexturePanel.c:1275 msgid "Gradient Texture" msgstr "Градиент" #: ../../WPrefs.app/TexturePanel.c:1276 msgid "Simple Gradient Texture" msgstr "Простой градиент" #: ../../WPrefs.app/TexturePanel.c:1277 msgid "Textured Gradient" msgstr "Текстурный градиент" #: ../../WPrefs.app/TexturePanel.c:1278 msgid "Image Texture" msgstr "Текстура изображения" #: ../../WPrefs.app/TexturePanel.c:1286 msgid "Default Color" msgstr "Цвет по умолчанию" #: ../../WPrefs.app/TexturePanel.c:1298 msgid "Gradient Colors" msgstr "Градиентные цвета" #: ../../WPrefs.app/TexturePanel.c:1394 msgid "Direction" msgstr "Направление" #: ../../WPrefs.app/TexturePanel.c:1422 msgid "Gradient" msgstr "Градиент" #: ../../WPrefs.app/TexturePanel.c:1440 msgid "Gradient Opacity" msgstr "Непрозрачность градиента" #: ../../WPrefs.app/TexturePanel.c:1483 msgid "Image" msgstr "Изображение" #: ../../WPrefs.app/TexturePanel.c:1515 msgid "Tile" msgstr "Мозаика" #: ../../WPrefs.app/TexturePanel.c:1516 msgid "Scale" msgstr "Масштабировать" #: ../../WPrefs.app/TexturePanel.c:1518 msgid "Maximize" msgstr "Распахнуть" #: ../../WPrefs.app/Themes.c:71 ../../WPrefs.app/Themes.c:82 msgid "Set" msgstr "Установить" #: ../../WPrefs.app/Themes.c:132 msgid "Stop" msgstr "Стоп" #: ../../WPrefs.app/Themes.c:143 ../../WPrefs.app/Themes.c:203 #: ../../WPrefs.app/Themes.c:223 msgid "Download" msgstr "Загрузить из Internet" #: ../../WPrefs.app/Themes.c:171 msgid "Save Current Theme" msgstr "Сохранить текущую тему" #: ../../WPrefs.app/Themes.c:180 msgid "Load" msgstr "Загрузить" #: ../../WPrefs.app/Themes.c:185 msgid "Install" msgstr "Инсталировать" #: ../../WPrefs.app/Themes.c:193 msgid "Tile of The Day" msgstr "" #: ../../WPrefs.app/Themes.c:213 msgid "Bar of The Day" msgstr "" #: ../../WPrefs.app/WindowHandling.c:141 #, c-format msgid "bad option value %s in WindowPlacement. Using default value" msgstr "" "неверное значение %s в параметре WindowPlacement. Используется значение по " "умолчанию" #: ../../WPrefs.app/WindowHandling.c:163 msgid "invalid data in option WindowPlaceOrigin. Using default (0,0)" msgstr "" "неправильные данные в параметре WindowPlaceOrigin. Используется значение по " "умолчанию (0,0)" #: ../../WPrefs.app/WindowHandling.c:243 msgid "Window Placement" msgstr "Размещение окон" #: ../../WPrefs.app/WindowHandling.c:244 msgid "" "How to place windows when they are first put\n" "on screen." msgstr "" "Как размещать окна, когда они впервые\n" "появляются на экране." #: ../../WPrefs.app/WindowHandling.c:250 msgid "Automatic" msgstr "Автоматическое" #: ../../WPrefs.app/WindowHandling.c:251 msgid "Random" msgstr "Случайное" #: ../../WPrefs.app/WindowHandling.c:252 msgid "Manual" msgstr "Ручное" #: ../../WPrefs.app/WindowHandling.c:253 msgid "Cascade" msgstr "Каскадное" #: ../../WPrefs.app/WindowHandling.c:254 msgid "Smart" msgstr "\"Умное\"" #: ../../WPrefs.app/WindowHandling.c:260 msgid "Placement Origin" msgstr "Исходное положение" #: ../../WPrefs.app/WindowHandling.c:321 msgid "Opaque Move" msgstr "Двигать целиком" #: ../../WPrefs.app/WindowHandling.c:322 msgid "" "Whether the window contents should be moved\n" "when dragging windows aroung or if only a\n" "frame should be displayed.\n" msgstr "" "Во время перемещения окна, должно ли оно\n" "перемещаться целиком, вместе со своим\n" "содержимым (нажато), или только его\n" "каркас (отпущено)\n" #: ../../WPrefs.app/WindowHandling.c:361 msgid "When maximizing..." msgstr "Когда распахивается окно..." #: ../../WPrefs.app/WindowHandling.c:366 msgid "...do not cover icons" msgstr "...не перекрывать иконки" #: ../../WPrefs.app/WindowHandling.c:372 msgid "...do not cover dock" msgstr "...не перекрывать Док" #: ../../WPrefs.app/WindowHandling.c:381 msgid "Edge Resistance" msgstr "Сопротивляемость краев" #: ../../WPrefs.app/WindowHandling.c:383 msgid "" "Edge resistance will make windows `resist'\n" "being moved further for the defined threshold\n" "when moved against other windows or the edges\n" "of the screen." msgstr "" #: ../../WPrefs.app/WindowHandling.c:402 msgid "Resist" msgstr "Упираться" +#: ../../WPrefs.app/WindowHandling.c:406 +msgid "Opaque Move/Resize" +msgstr "Перемещ/Измен.разм." + #: ../../WPrefs.app/WindowHandling.c:407 msgid "Attract" msgstr "Притягиваться" #: ../../WPrefs.app/WindowHandling.c:423 msgid "Open dialogs in same workspace as their owners" msgstr "" "Открывать диалоги в одном рабочем " "пространстве с их родителями" #: ../../WPrefs.app/WindowHandling.c:450 msgid "Window Handling Preferences" msgstr "Параметры окон" #: ../../WPrefs.app/WindowHandling.c:452 msgid "" "Window handling options. Initial placement style\n" "edge resistance, opaque move etc." msgstr "" "Как обращаться с окнами. Начальное расположение окон.\n" "Сопротивляемость границ. Сплошное/каркасное перемещение, и т.п." +#: ../../WPrefs.app/WindowHandling.c:474 +msgid "by keyboard" +msgstr "c помощ.клав." + +#: ../../WPrefs.app/WindowHandling.c:490 +msgid "...do not cover:" +msgstr "не перекрывать:" + +#: ../../WPrefs.app/WindowHandling.c:497 +msgid "Icons" +msgstr "Иконок" + +#: ../../WPrefs.app/WindowHandling.c:502 +msgid "The dock" +msgstr "Дока" + #: ../../WPrefs.app/Workspace.c:176 msgid "Workspace Navigation" msgstr "Навигация по рабочим пространствам" #: ../../WPrefs.app/Workspace.c:183 msgid "Wrap to the first workspace from the last workspace" msgstr "создавать новое рабочее пространство когда переключаемся за последнее" #: ../../WPrefs.app/Workspace.c:205 msgid "Switch workspaces while dragging windows" msgstr "переключать рабочие пространства при перетаскивании окон" #: ../../WPrefs.app/Workspace.c:227 msgid "Automatically create new workspaces" msgstr "автоматически создавать новые рабочие пространства" #: ../../WPrefs.app/Workspace.c:250 msgid "Position of workspace name display" msgstr "Отображение имени рабочего пространства" #: ../../WPrefs.app/Workspace.c:269 msgid "Disable" msgstr "Запретить" #: ../../WPrefs.app/Workspace.c:271 msgid "Top" msgstr "Вверху" #: ../../WPrefs.app/Workspace.c:272 msgid "Bottom" msgstr "Внизу" #: ../../WPrefs.app/Workspace.c:273 msgid "Top/Left" msgstr "Вверху слева" #: ../../WPrefs.app/Workspace.c:274 msgid "Top/Right" msgstr "Вверху справа" #: ../../WPrefs.app/Workspace.c:275 msgid "Bottom/Left" msgstr "Внизу слева" #: ../../WPrefs.app/Workspace.c:276 msgid "Bottom/Right" msgstr "Внизу справа" #: ../../WPrefs.app/Workspace.c:284 msgid "Dock/Clip" msgstr "Док/Скрепка" #: ../../WPrefs.app/Workspace.c:303 msgid "" "Disable/enable the application Dock (the\n" "vertical icon bar in the side of the screen)." msgstr "" "Запретить/разрешить Док приложений (вертикальную\n" "стопку иконок на одной из границ экрана)." #: ../../WPrefs.app/Workspace.c:324 msgid "" "Disable/enable the Clip (that thing with\n" "a paper clip icon)." msgstr "" "Запретить/разрешить Скрепку (вы ее узнаете по иконке\n" "с изображением скрепки для бумаги)." #: ../../WPrefs.app/Workspace.c:364 msgid "Workspace Preferences" msgstr "Установки для рабочего пространства" #: ../../WPrefs.app/Workspace.c:366 msgid "" "Workspace navigation features.\n" "You can also enable/disable the Dock and Clip here." msgstr "" "Особенности навигации по рабочим пространствам.\n" "Здесь вы также можете разрешить/запретить Док и Скрепку." #: ../../WPrefs.app/WPrefs.c:260 msgid "Window Maker Preferences" msgstr "Свойства Window Maker" #: ../../WPrefs.app/WPrefs.c:284 msgid "Revert Page" msgstr "Вернуть страницу" #: ../../WPrefs.app/WPrefs.c:290 msgid "Revert All" msgstr "Вернуть все" #: ../../WPrefs.app/WPrefs.c:296 msgid "Save" msgstr "Сохранить" #: ../../WPrefs.app/WPrefs.c:309 msgid "Balloon Help" msgstr "Всплывающие подсказки" # awn: оставлено без перевода из-за проблемы со шрифтами. #: ../../WPrefs.app/WPrefs.c:334 msgid "Window Maker Preferences Utility" msgstr "" #: ../../WPrefs.app/WPrefs.c:341 #, c-format msgid "Version %s for Window Maker %s or newer" msgstr "Версия %s для Window Maker %s или новее" #: ../../WPrefs.app/WPrefs.c:349 msgid "Starting..." msgstr "Стартую..." #: ../../WPrefs.app/WPrefs.c:355 msgid "" "Programming/Design: Alfredo K. Kojima\n" "Artwork: Marco van Hylckama Vlieg, Largo et al\n" "More Programming: James Thompson et al" msgstr "" "Программирование/Дизайн: Alfredo K. Kojima\n" "Оформление: Marco van Hylckama Vlieg, Largo et al\n" "Программирование: James Thomson et al" #: ../../WPrefs.app/WPrefs.c:455 #, c-format msgid "could not locate image file %s\n" msgstr "не могу найти файл с изображением %s\n" #: ../../WPrefs.app/WPrefs.c:670 #, c-format msgid "could not load image file %s:%s" msgstr "не могу загрузить файл изображения %s:%s" #: ../../WPrefs.app/WPrefs.c:689 msgid "Loading Window Maker configuration files..." msgstr "Загружаю файлы конфигурации Window Maker..." #: ../../WPrefs.app/WPrefs.c:693 msgid "Initializing configuration panels..." msgstr "Инициализирую конфигурационные панели..." #: ../../WPrefs.app/WPrefs.c:727 msgid "" "WPrefs is free software and is distributed WITHOUT ANY\n" "WARRANTY under the terms of the GNU General Public License." msgstr "" "WPrefs является свободным ПО и распространяется БЕЗ КАКИХ-ЛИБО\n" "ГАРАНТИЙ в соответствии с терминами GNU General Public License." #: ../../WPrefs.app/WPrefs.c:757 ../../WPrefs.app/WPrefs.c:837 #, c-format msgid "Window Maker domain (%s) is corrupted!" msgstr "Window Maker домен (%s) поврежден!" #: ../../WPrefs.app/WPrefs.c:761 #, c-format msgid "Could not load Window Maker domain (%s) from defaults database." msgstr "Не могу загрузить домен Window MAker (%s) из базы данных по умолчанию." #: ../../WPrefs.app/WPrefs.c:777 msgid "could not extract version information from Window Maker" msgstr "не могу получить номер версии Window Maker" #: ../../WPrefs.app/WPrefs.c:778 msgid "Make sure wmaker is in your search path." msgstr "Убедитесь что путь к wmaker определен." #: ../../WPrefs.app/WPrefs.c:781 msgid "" "Could not extract version from Window Maker. Make sure it is correctly " "installed and is in your PATH environment variable." msgstr "" "Не могу получить версию Window Maker. Убедитесь что он установлен корректно " "и переменная окружения PATH содержит путь к нему." #: ../../WPrefs.app/WPrefs.c:791 msgid "" "Could not extract version from Window Maker. Make sure it is correctly " "installed and the path where it installed is in the PATH environment " "variable." msgstr "" "Не могу получить версию Window Maker. Убедитесь что он установлен корректно " "и путь к месту где он установлен есть в PATH." #: ../../WPrefs.app/WPrefs.c:798 #, c-format msgid "" "WPrefs only supports Window Maker 0.18.0 or newer.\n" "The version installed is %i.%i.%i\n" msgstr "" "WPrefs работает только с Window Maker 0.18.0 или новее.\n" "Установлена версия %i.%i.%i\n" #: ../../WPrefs.app/WPrefs.c:805 #, c-format msgid "" "Window Maker %i.%i.%i, which is installed in your system, is not fully " "supported by this version of WPrefs." msgstr "" "Window Maker %i.%i.%i, установленный в вашей системе не поддерживается этой " "версией WPrefs полностью." #: ../../WPrefs.app/WPrefs.c:818 #, c-format msgid "could not run \"%s --global_defaults_path\"." msgstr "не могу запустить \"%s --global_defaults_path\"." #: ../../WPrefs.app/WPrefs.c:841 #, c-format msgid "Could not load global Window Maker domain (%s)." msgstr "Не могу загрузить глобальный домен Window Maker (%s)." #: ../../WPrefs.app/WPrefs.c:1090 #, c-format msgid "" "bad speed value for option %s\n" ". Using default Medium" msgstr "" "неправильное значение скорости для %s\n" ". Используем по-умолчанию \"Среднее\""
roblillack/wmaker
6e2075f3dfb7c9f8ca7ac447d47c715b945dd9c0
Double click on titlebar maximize a window to fullscreen
diff --git a/WPrefs.app/Expert.c b/WPrefs.app/Expert.c index f2cbe09..b1a8e9b 100644 --- a/WPrefs.app/Expert.c +++ b/WPrefs.app/Expert.c @@ -1,338 +1,341 @@ /* Expert.c- expert user options * * WPrefs - Window Maker Preferences Program * * Copyright (c) 2014 Window Maker Team * Copyright (c) 1998-2003 Alfredo K. Kojima * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "WPrefs.h" /* This structure containts the list of all the check-buttons to display in the * expert tab of the window with the corresponding information for effect */ static const struct { const char *label; /* Text displayed to user */ int def_state; /* True/False: the default value, if not defined in current config */ enum { OPTION_WMAKER, OPTION_WMAKER_ARRAY, OPTION_USERDEF, OPTION_WMAKER_INT } class; const char *op_name; /* The identifier for the option in the config file */ } expert_options[] = { { N_("Disable miniwindows (icons for minimized windows). For use with KDE/GNOME."), /* default: */ False, OPTION_WMAKER, "DisableMiniwindows" }, { N_("Ignore decoration hints for GTK applications."), /* default: */ False, OPTION_WMAKER, "IgnoreGtkHints" }, { N_("Enable workspace pager."), /* default: */ False, OPTION_WMAKER, "EnableWorkspacePager" }, { N_("Do not set non-WindowMaker specific parameters (do not use xset)."), /* default: */ False, OPTION_USERDEF, "NoXSetStuff" }, { N_("Automatically save session when exiting Window Maker."), /* default: */ False, OPTION_WMAKER, "SaveSessionOnExit" }, { N_("Use SaveUnder in window frames, icons, menus and other objects."), /* default: */ False, OPTION_WMAKER, "UseSaveUnders" }, { N_("Disable confirmation panel for the Kill command."), /* default: */ False, OPTION_WMAKER, "DontConfirmKill" }, { N_("Disable selection animation for selected icons."), /* default: */ False, OPTION_WMAKER, "DisableBlinking" }, { N_("Smooth font edges (needs restart)."), /* default: */ True, OPTION_WMAKER, "AntialiasedText" }, { N_("Cycle windows only on the active head."), /* default: */ False, OPTION_WMAKER, "CycleActiveHeadOnly" }, { N_("Ignore minimized windows when cycling."), /* default: */ False, OPTION_WMAKER, "CycleIgnoreMinimized" }, { N_("Show switch panel when cycling windows."), /* default: */ True, OPTION_WMAKER_ARRAY, "SwitchPanelImages" }, { N_("Show workspace title on Clip."), /* default: */ True, OPTION_WMAKER, "ShowClipTitle" }, { N_("Highlight the icon of the application when it has the focus."), /* default: */ True, OPTION_WMAKER, "HighlightActiveApp" }, #ifdef XKB_MODELOCK { N_("Enable keyboard language switch button in window titlebars."), /* default: */ False, OPTION_WMAKER, "KbdModeLock" }, #endif /* XKB_MODELOCK */ { N_("Maximize (snap) a window to edge or corner by dragging."), /* default: */ False, OPTION_WMAKER, "WindowSnapping" }, { N_("Distance from edge to begin window snap."), /* default: */ 1, OPTION_WMAKER_INT, "SnapEdgeDetect" }, { N_("Distance from corner to begin window snap."), /* default: */ 10, OPTION_WMAKER_INT, "SnapCornerDetect" }, { N_("Snapping a window to the top maximizes it to the full screen."), /* default: */ False, OPTION_WMAKER, "SnapToTopMaximizesFullscreen" }, { N_("Allow move half-maximized windows between multiple screens."), /* default: */ False, OPTION_WMAKER, "MoveHalfMaximizedWindowsBetweenScreens" }, { N_("Alternative transitions between states for half maximized windows."), /* default: */ False, OPTION_WMAKER, "AlternativeHalfMaximized" }, { N_("Move mouse pointer with half maximized windows."), /* default: */ False, OPTION_WMAKER, "PointerWithHalfMaxWindows" }, { N_("Open dialogs in the same workspace as their owners."), /* default: */ False, OPTION_WMAKER, "OpenTransientOnOwnerWorkspace" }, { N_("Wrap dock-attached icons around the screen edges."), - /* default: */ True, OPTION_WMAKER, "WrapAppiconsInDock" } + /* default: */ True, OPTION_WMAKER, "WrapAppiconsInDock" }, + + { N_("Double click on titlebar maximize a window to full screen."), + /* default: */ False, OPTION_WMAKER, "DbClickFullScreen" } }; typedef struct _Panel { WMBox *box; char *sectionName; char *description; CallbackRec callbacks; WMWidget *parent; WMButton *swi[wlengthof_nocheck(expert_options)]; WMTextField *textfield[wlengthof_nocheck(expert_options)]; } _Panel; #define ICON_FILE "expert" static void changeIntTextfield(void *data, int delta) { WMTextField *textfield; char *text; int value; textfield = (WMTextField *)data; text = WMGetTextFieldText(textfield); value = atoi(text); value += delta; sprintf(text, "%d", value); WMSetTextFieldText(textfield, text); } static void downButtonCallback(WMWidget *self, void *data) { (void) self; changeIntTextfield(data, -1); } static void upButtonCallback(WMWidget *self, void *data) { (void) self; changeIntTextfield(data, 1); } static void createPanel(Panel *p) { _Panel *panel = (_Panel *) p; WMScrollView *sv; WMFrame *f; WMUserDefaults *udb; int i, state; panel->box = WMCreateBox(panel->parent); WMSetViewExpandsToParent(WMWidgetView(panel->box), 2, 2, 2, 2); sv = WMCreateScrollView(panel->box); WMResizeWidget(sv, 500, 215); WMMoveWidget(sv, 12, 10); WMSetScrollViewRelief(sv, WRSunken); WMSetScrollViewHasVerticalScroller(sv, True); WMSetScrollViewHasHorizontalScroller(sv, False); f = WMCreateFrame(panel->box); WMResizeWidget(f, 495, wlengthof(expert_options) * 25 + 8); WMSetFrameRelief(f, WRFlat); udb = WMGetStandardUserDefaults(); for (i = 0; i < wlengthof(expert_options); i++) { if (expert_options[i].class != OPTION_WMAKER_INT) { panel->swi[i] = WMCreateSwitchButton(f); WMResizeWidget(panel->swi[i], FRAME_WIDTH - 40, 25); WMMoveWidget(panel->swi[i], 5, 5 + i * 25); WMSetButtonText(panel->swi[i], _(expert_options[i].label)); } switch (expert_options[i].class) { case OPTION_WMAKER: if (GetStringForKey(expert_options[i].op_name)) state = GetBoolForKey(expert_options[i].op_name); else state = expert_options[i].def_state; break; case OPTION_WMAKER_ARRAY: { char *str = GetStringForKey(expert_options[i].op_name); state = expert_options[i].def_state; if (str && strcasecmp(str, "None") == 0) state = False; } break; case OPTION_USERDEF: state = WMGetUDBoolForKey(udb, expert_options[i].op_name); break; case OPTION_WMAKER_INT: { char tmp[10]; WMButton *up, *down; WMLabel *label; panel->textfield[i] = WMCreateTextField(f); WMResizeWidget(panel->textfield[i], 41, 20); WMMoveWidget(panel->textfield[i], 22, 7 + i * 25); down = WMCreateCommandButton(f); WMSetButtonImage(down, WMGetSystemPixmap(WMWidgetScreen(down), WSIArrowDown)); WMSetButtonAltImage(down, WMGetSystemPixmap(WMWidgetScreen(down), WSIHighlightedArrowDown)); WMSetButtonImagePosition(down, WIPImageOnly); WMSetButtonAction(down, downButtonCallback, panel->textfield[i]); WMResizeWidget(down, 16, 16); WMMoveWidget(down, 5, 9 + i * 25); up = WMCreateCommandButton(f); WMSetButtonImage(up, WMGetSystemPixmap(WMWidgetScreen(up), WSIArrowUp)); WMSetButtonAltImage(up, WMGetSystemPixmap(WMWidgetScreen(up), WSIHighlightedArrowUp)); WMSetButtonImagePosition(up, WIPImageOnly); WMSetButtonAction(up, upButtonCallback, panel->textfield[i]); WMResizeWidget(up, 16, 16); WMMoveWidget(up, 64, 9 + i * 25); label = WMCreateLabel(f); WMSetLabelText(label, _(expert_options[i].label)); WMResizeWidget(label, FRAME_WIDTH - 99, 25); WMMoveWidget(label, 85, 5 + i * 25); if (GetStringForKey(expert_options[i].op_name)) state = GetIntegerForKey(expert_options[i].op_name); else state = expert_options[i].def_state; sprintf(tmp, "%d", state); WMSetTextFieldText(panel->textfield[i], tmp); break; } default: #ifdef DEBUG wwarning("export_options[%d].class = %d, this should not happen\n", i, expert_options[i].class); #endif state = expert_options[i].def_state; break; } if (expert_options[i].class != OPTION_WMAKER_INT) WMSetButtonSelected(panel->swi[i], state); } WMMapSubwidgets(panel->box); WMSetScrollViewContentView(sv, WMWidgetView(f)); WMRealizeWidget(panel->box); } static void storeDefaults(_Panel *panel) { WMUserDefaults *udb = WMGetStandardUserDefaults(); int i; for (i = 0; i < wlengthof(expert_options); i++) { switch (expert_options[i].class) { case OPTION_WMAKER: SetBoolForKey(WMGetButtonSelected(panel->swi[i]), expert_options[i].op_name); break; case OPTION_WMAKER_ARRAY: if (WMGetButtonSelected(panel->swi[i])) { /* check if the array was not manually modified */ char *str = GetStringForKey(expert_options[i].op_name); if (str && strcasecmp(str, "None") == 0) RemoveObjectForKey(expert_options[i].op_name); } else SetStringForKey("None", expert_options[i].op_name); break; case OPTION_USERDEF: WMSetUDBoolForKey(udb, WMGetButtonSelected(panel->swi[i]), expert_options[i].op_name); break; case OPTION_WMAKER_INT: { char *text; int value; text = WMGetTextFieldText(panel->textfield[i]); value = atoi(text); SetIntegerForKey(value, expert_options[i].op_name); break; } } } } Panel *InitExpert(WMWidget *parent) { _Panel *panel; panel = wmalloc(sizeof(_Panel)); panel->sectionName = _("Expert User Preferences"); panel->description = _("Options for people who know what they're doing...\n" "Also has some other misc. options."); panel->parent = parent; panel->callbacks.createWidgets = createPanel; panel->callbacks.updateDomain = storeDefaults; AddSection(panel, ICON_FILE); return panel; } diff --git a/src/WindowMaker.h b/src/WindowMaker.h index 4b718ec..b4f3a88 100644 --- a/src/WindowMaker.h +++ b/src/WindowMaker.h @@ -1,660 +1,661 @@ /* * Window Maker window manager * * Copyright (c) 1997-2003 Alfredo K. Kojima * Copyright (c) 2014 Window Maker Team * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef WINDOWMAKER_H_ #define WINDOWMAKER_H_ #include "wconfig.h" #include <assert.h> #include <limits.h> #include <WINGs/WINGs.h> /* class codes */ typedef enum { WCLASS_UNKNOWN = 0, WCLASS_WINDOW = 1, /* managed client windows */ WCLASS_MENU = 2, /* root menus */ WCLASS_APPICON = 3, WCLASS_DUMMYWINDOW = 4, /* window that holds window group leader */ WCLASS_MINIWINDOW = 5, WCLASS_DOCK_ICON = 6, WCLASS_PAGER = 7, WCLASS_TEXT_INPUT = 8, WCLASS_FRAME = 9 } WClassType; /* * generic window levels (a superset of the N*XTSTEP ones) * Applications should use levels between WMDesktopLevel and * WMScreensaverLevel anything boyond that range is allowed, * but discouraged. */ enum { WMBackLevel = INT_MIN+1, /* Very lowest level */ WMDesktopLevel = -1000, /* Lowest level of normal use */ WMSunkenLevel = -1, WMNormalLevel = 0, WMFloatingLevel = 3, WMDockLevel = 5, WMSubmenuLevel = 15, WMMainMenuLevel = 20, WMStatusLevel = 21, WMFullscreenLevel = 50, WMModalLevel = 100, WMPopUpLevel = 101, WMScreensaverLevel = 1000, WMOuterSpaceLevel = INT_MAX }; /* * WObjDescriptor will be used by the event dispatcher to * send events to a particular object through the methods in the * method table. If all objects of the same class share the * same methods, the class method table should be used, otherwise * a new method table must be created for each object. * It is also assigned to find the parent structure of a given * window (like the WWindow or WMenu for a button) */ typedef struct WObjDescriptor { void *self; /* the object that will be called */ /* event handlers */ void (*handle_expose)(struct WObjDescriptor *sender, XEvent *event); void (*handle_mousedown)(struct WObjDescriptor *sender, XEvent *event); void (*handle_enternotify)(struct WObjDescriptor *sender, XEvent *event); void (*handle_leavenotify)(struct WObjDescriptor *sender, XEvent *event); WClassType parent_type; /* type code of the parent */ void *parent; /* parent object (WWindow or WMenu) */ } WObjDescriptor; /* internal buttons */ #define WBUT_CLOSE 0 #define WBUT_BROKENCLOSE 1 #define WBUT_ICONIFY 2 #define WBUT_KILL 3 #ifdef XKB_BUTTON_HINT #define WBUT_XKBGROUP1 4 #define WBUT_XKBGROUP2 5 #define WBUT_XKBGROUP3 6 #define WBUT_XKBGROUP4 7 #define PRED_BPIXMAPS 8 /* reserved for 4 groups */ #else #define PRED_BPIXMAPS 4 /* count of WBUT icons */ #endif /* XKB_BUTTON_HINT */ /* Mouse cursors */ typedef enum { WCUR_NORMAL, WCUR_MOVE, WCUR_RESIZE, WCUR_TOPLEFTRESIZE, WCUR_TOPRIGHTRESIZE, WCUR_BOTTOMLEFTRESIZE, WCUR_BOTTOMRIGHTRESIZE, WCUR_VERTICALRESIZE, WCUR_HORIZONRESIZE, WCUR_WAIT, WCUR_ARROW, WCUR_QUESTION, WCUR_TEXT, WCUR_SELECT, WCUR_ROOT, WCUR_EMPTY, /* Count of the number of cursors defined */ WCUR_LAST } w_cursor; /* geometry displays */ #define WDIS_NEW 0 /* new style */ #define WDIS_CENTER 1 /* center of screen */ #define WDIS_TOPLEFT 2 /* top left corner of screen */ #define WDIS_FRAME_CENTER 3 /* center of the frame */ #define WDIS_NONE 4 /* keyboard input focus mode */ #define WKF_CLICK 0 #define WKF_SLOPPY 2 /* colormap change mode */ #define WCM_CLICK 0 #define WCM_POINTER 1 /* window placement mode */ #define WPM_MANUAL 0 #define WPM_CASCADE 1 #define WPM_SMART 2 #define WPM_RANDOM 3 #define WPM_AUTO 4 #define WPM_CENTER 5 /* text justification */ #define WTJ_CENTER 0 #define WTJ_LEFT 1 #define WTJ_RIGHT 2 /* iconification styles */ #define WIS_ZOOM 0 #define WIS_TWIST 1 #define WIS_FLIP 2 #define WIS_NONE 3 #define WIS_RANDOM 4 /* secret */ /* switchmenu actions */ #define ACTION_ADD 0 #define ACTION_REMOVE 1 #define ACTION_CHANGE 2 #define ACTION_CHANGE_WORKSPACE 3 #define ACTION_CHANGE_STATE 4 /* speeds */ #define SPEED_ULTRAFAST 0 #define SPEED_FAST 1 #define SPEED_MEDIUM 2 #define SPEED_SLOW 3 #define SPEED_ULTRASLOW 4 /* window states */ #define WS_FOCUSED 0 #define WS_UNFOCUSED 1 #define WS_PFOCUSED 2 /* clip title colors */ #define CLIP_NORMAL 0 #define CLIP_COLLAPSED 1 /* icon yard position */ #define IY_VERT 1 #define IY_HORIZ 0 #define IY_TOP 2 #define IY_BOTTOM 0 #define IY_RIGHT 4 #define IY_LEFT 0 /* menu styles */ #define MS_NORMAL 0 #define MS_SINGLE_TEXTURE 1 #define MS_FLAT 2 /* workspace actions */ #define WA_NONE 0 #define WA_SELECT_WINDOWS 1 #define WA_OPEN_APPMENU 2 #define WA_OPEN_WINLISTMENU 3 #define WA_SWITCH_WORKSPACES 4 #define WA_MOVE_PREVWORKSPACE 5 #define WA_MOVE_NEXTWORKSPACE 6 #define WA_SWITCH_WINDOWS 7 #define WA_MOVE_PREVWINDOW 8 #define WA_MOVE_NEXTWINDOW 9 /* workspace display position */ #define WD_NONE 0 #define WD_CENTER 1 #define WD_TOP 2 #define WD_BOTTOM 3 #define WD_TOPLEFT 4 #define WD_TOPRIGHT 5 #define WD_BOTTOMLEFT 6 #define WD_BOTTOMRIGHT 7 /* titlebar style */ #define TS_NEW 0 #define TS_OLD 1 #define TS_NEXT 2 /* workspace border position */ #define WB_NONE 0 #define WB_LEFTRIGHT 1 #define WB_TOPBOTTOM 2 #define WB_ALLDIRS (WB_LEFTRIGHT|WB_TOPBOTTOM) /* drag maximized window behaviors */ enum { DRAGMAX_MOVE, DRAGMAX_RESTORE, DRAGMAX_UNMAXIMIZE, DRAGMAX_NOMOVE }; /* program states */ typedef enum { WSTATE_NORMAL = 0, WSTATE_NEED_EXIT = 1, WSTATE_NEED_RESTART = 2, WSTATE_EXITING = 3, WSTATE_RESTARTING = 4, WSTATE_MODAL = 5, WSTATE_NEED_REREAD = 6 } wprog_state; #define WCHECK_STATE(chk_state) (w_global.program.state == (chk_state)) #define WCHANGE_STATE(nstate) {\ if (w_global.program.state == WSTATE_NORMAL \ || (nstate) != WSTATE_MODAL) \ w_global.program.state = (nstate); \ if (w_global.program.signal_state != 0) \ w_global.program.state = w_global.program.signal_state; \ } /* only call inside signal handlers, with signals blocked */ #define SIG_WCHANGE_STATE(nstate) {\ w_global.program.signal_state = (nstate); \ w_global.program.state = (nstate); \ } /* Flags for the Window Maker state when restarting/crash situations */ #define WFLAGS_NONE (0) #define WFLAGS_CRASHED (1<<0) /* notifications */ #ifdef MAINFILE #define NOTIFICATION(n) const char WN##n [] = #n #else #define NOTIFICATION(n) extern const char WN##n [] #endif NOTIFICATION(WindowAppearanceSettingsChanged); NOTIFICATION(IconAppearanceSettingsChanged); NOTIFICATION(IconTileSettingsChanged); NOTIFICATION(MenuAppearanceSettingsChanged); NOTIFICATION(MenuTitleAppearanceSettingsChanged); /* appearance settings clientdata flags */ enum { WFontSettings = 1 << 0, WTextureSettings = 1 << 1, WColorSettings = 1 << 2 }; typedef struct { int x1, y1; int x2, y2; } WArea; typedef struct WCoord { int x, y; } WCoord; extern struct WPreferences { char *pixmap_path; /* : separated list of paths to find pixmaps */ char *icon_path; /* : separated list of paths to find icons */ WMArray *fallbackWMs; /* fallback window manager list */ char *logger_shell; /* shell to log child stdi/o */ RImage *button_images; /* titlebar button images */ char smooth_workspace_back; signed char size_display; /* display type for resize geometry */ signed char move_display; /* display type for move geometry */ signed char window_placement; /* window placement mode */ signed char colormap_mode; /* colormap focus mode */ signed char focus_mode; /* window focusing mode */ char opaque_move; /* update window position during move */ char opaque_resize; /* update window position during resize */ char opaque_move_resize_keyboard; /* update window position during move,resize with keyboard */ char wrap_menus; /* wrap menus at edge of screen */ char scrollable_menus; /* let them be scrolled */ char vi_key_menus; /* use h/j/k/l to select */ char align_menus; /* align menu with their parents */ char use_saveunders; /* turn on SaveUnders for menus, icons etc. */ char no_window_over_dock; char no_window_over_icons; WCoord window_place_origin; /* Offset for windows placed on screen */ char constrain_window_size; /* don't let windows get bigger than screen */ char windows_cycling; /* windoze cycling */ char circ_raise; /* raise window after Alt-tabbing */ char ignore_focus_click; char open_transients_with_parent; /* open transient window in same workspace as parent */ signed char title_justification; /* titlebar text alignment */ int window_title_clearance; int window_title_min_height; int window_title_max_height; int menu_title_clearance; int menu_title_min_height; int menu_title_max_height; int menu_text_clearance; char multi_byte_text; #ifdef KEEP_XKB_LOCK_STATUS char modelock; #endif char no_dithering; /* use dithering or not */ char no_animations; /* enable/disable animations */ char no_autowrap; /* wrap workspace when window is moved to the edge */ char window_snapping; /* enable window snapping */ int snap_edge_detect; /* how far from edge to begin snap */ int snap_corner_detect; /* how far from corner to begin snap */ char snap_to_top_maximizes_fullscreen; char drag_maximized_window; /* behavior when a maximized window is dragged */ char move_half_max_between_heads; /* move half maximized window between available heads */ char alt_half_maximize; /* alternative half-maximize feature behavior */ char pointer_with_half_max_windows; char highlight_active_app; /* show the focused app by highlighting its icon */ char auto_arrange_icons; /* automagically arrange icons */ char icon_box_position; /* position to place icons */ signed char iconification_style; /* position to place icons */ char disable_root_mouse; /* disable button events in root window */ char auto_focus; /* focus window when it's mapped */ char *icon_back_file; /* background image for icons */ char enforce_icon_margin; /* auto-shrink icon images */ WCoord *root_menu_pos; /* initial position of the root menu*/ WCoord *app_menu_pos; WCoord *win_menu_pos; signed char icon_yard; /* aka iconbox */ int raise_delay; /* delay for autoraise. 0 is disabled */ int cmap_size; /* size of dithering colormap in colors per channel */ int icon_size; /* size of the icon */ signed char menu_style; /* menu decoration style */ signed char workspace_name_display_position; unsigned int modifier_mask; /* mask to use as kbd modifier */ char *modifier_labels[7]; /* Names of the modifiers */ unsigned int supports_tiff; /* Use tiff files */ char ws_advance; /* Create new workspace and advance */ char ws_cycle; /* Cycle existing workspaces */ char save_session_on_exit; /* automatically save session on exit */ char sticky_icons; /* If miniwindows will be onmipresent */ char dont_confirm_kill; /* do not confirm Kill application */ char disable_miniwindows; char enable_workspace_pager; char ignore_gtk_decoration_hints; char dont_blink; /* do not blink icon selection */ /* Appearance options */ char new_style; /* Use newstyle buttons */ char superfluous; /* Use superfluous things */ /* root window mouse bindings */ signed char mouse_button1; /* action for left mouse button */ signed char mouse_button2; /* action for middle mouse button */ signed char mouse_button3; /* action for right mouse button */ signed char mouse_button8; /* action for 4th button aka backward mouse button */ signed char mouse_button9; /* action for 5th button aka forward mouse button */ signed char mouse_wheel_scroll; /* action for mouse wheel scroll */ signed char mouse_wheel_tilt; /* action for mouse wheel tilt */ /* balloon text */ char window_balloon; char miniwin_title_balloon; char miniwin_preview_balloon; char appicon_balloon; char help_balloon; /* some constants */ int dblclick_time; /* double click delay time in ms */ /* animate menus */ signed char menu_scroll_speed; /* how fast menus are scrolled */ /* animate icon sliding */ signed char icon_slide_speed; /* icon slide animation speed */ /* shading animation */ signed char shade_speed; /* bouncing animation */ char bounce_appicons_when_urgent; char raise_appicons_when_bouncing; char do_not_make_appicons_bounce; int edge_resistance; int resize_increment; char attract; unsigned int workspace_border_size; /* Size in pixels of the workspace border */ char workspace_border_position; /* Where to leave a workspace border */ char single_click; /* single click to lauch applications */ int history_lines; /* history of "Run..." dialog */ char cycle_active_head_only; /* Cycle only windows on the active head */ char cycle_ignore_minimized; /* Ignore minimized windows when cycling */ + char double_click_fullscreen; /* Double click on titlebar maximize a window to full screen*/ char strict_windoze_cycle; /* don't close switch panel when shift is released */ char panel_only_open; /* Only open the switch panel; don't switch */ int minipreview_size; /* Size of Mini-Previews in pixels */ /* All delays here are in ms. 0 means instant auto-action. */ int clip_auto_raise_delay; /* Delay after which the clip will be raised when entered */ int clip_auto_lower_delay; /* Delay after which the clip will be lowered when leaved */ int clip_auto_expand_delay; /* Delay after which the clip will expand when entered */ int clip_auto_collapse_delay; /* Delay after which the clip will collapse when leaved */ RImage *swtileImage; RImage *swbackImage[9]; union WTexture *wsmbackTexture; char show_clip_title; struct { #ifdef USE_ICCCM_WMREPLACE unsigned int replace:1; /* replace existing window manager */ #endif unsigned int nodock:1; /* don't display the dock */ unsigned int noclip:1; /* don't display the clip */ unsigned int clip_merged_in_dock:1; /* disable clip, switch workspaces with dock */ unsigned int nodrawer:1; /* don't use drawers */ unsigned int wrap_appicons_in_dock:1; /* Whether to wrap appicons when Dock is moved up and down */ unsigned int noupdates:1; /* don't require ~/GNUstep (-static) */ unsigned int noautolaunch:1; /* don't autolaunch apps */ unsigned int norestore:1; /* don't restore session */ unsigned int restarting:2; } flags; /* internal flags */ /* Map table between w_cursor and actual X id */ Cursor cursor[WCUR_LAST]; int switch_panel_icon_size; /* icon size in switch panel */ } wPreferences; /****** Global Variables ******/ extern Display *dpy; extern struct wmaker_global_variables { /* Tracking of the state of the program */ struct { wprog_state state; wprog_state signal_state; } program; /* locale to use. NULL==POSIX or C */ const char *locale; /* Tracking of X events timestamps */ struct { /* ts of the last event we received */ Time last_event; /* ts on the last time we did XSetInputFocus() */ Time focus_change; } timestamp; /* Global Domains, for storing dictionaries */ struct { /* Note: you must #include <defaults.h> if you want to use them */ struct WDDomain *wmaker; struct WDDomain *window_attr; struct WDDomain *root_menu; } domain; /* Screens related */ int screen_count; /* * Ignore Workspace Change: * this variable is used to prevent workspace switch while certain * operations are ongoing. */ Bool ignore_workspace_change; /* * Process WorkspaceMap Event: * this variable is set when the Workspace Map window is being displayed, * it is mainly used to avoid re-opening another one at the same time */ Bool process_workspacemap_event; #ifdef HAVE_INOTIFY struct { int fd_event_queue; /* Inotify's queue file descriptor */ int wd_defaults; /* Watch Descriptor for the 'Defaults' configuration file */ } inotify; #endif /* definition for X Atoms */ struct { /* Window-Manager related */ struct { Atom state; Atom change_state; Atom protocols; Atom take_focus; Atom delete_window; Atom save_yourself; Atom client_leader; Atom colormap_windows; Atom colormap_notify; Atom ignore_focus_events; } wm; /* GNUStep related */ struct { Atom wm_attr; Atom wm_miniaturize_window; Atom wm_resizebar; Atom titlebar_state; } gnustep; /* Destkop-environment related */ struct { Atom gtk_object_path; } desktop; /* WindowMaker specific */ struct { Atom menu; Atom wm_protocols; Atom state; Atom wm_function; Atom noticeboard; Atom command; Atom icon_size; Atom icon_tile; } wmaker; } atom; /* X Contexts */ struct { XContext client_win; XContext app_win; XContext stack; } context; /* X Extensions */ struct { #ifdef USE_XSHAPE struct { Bool supported; int event_base; } shape; #endif #ifdef KEEP_XKB_LOCK_STATUS struct { Bool supported; int event_base; } xkb; #endif #ifdef USE_RANDR struct { Bool supported; int event_base; } randr; #endif /* * If no extension were activated, we would end up with an empty * structure, which old compilers may not appreciate, so let's * work around this with a simple: */ int dummy; } xext; /* Keyboard and shortcuts */ struct { /* * Bit-mask to hide special key modifiers which we don't want to * impact the shortcuts (typically: CapsLock, NumLock, ScrollLock) */ unsigned int modifiers_mask; } shortcut; } w_global; /****** Notifications ******/ extern const char WMNManaged[]; extern const char WMNUnmanaged[]; extern const char WMNChangedWorkspace[]; extern const char WMNChangedState[]; extern const char WMNChangedFocus[]; extern const char WMNChangedStacking[]; extern const char WMNChangedName[]; extern const char WMNWorkspaceCreated[]; extern const char WMNWorkspaceDestroyed[]; extern const char WMNWorkspaceChanged[]; extern const char WMNWorkspaceNameChanged[]; extern const char WMNResetStacking[]; #endif diff --git a/src/defaults.c b/src/defaults.c index 3caa504..11c438f 100644 --- a/src/defaults.c +++ b/src/defaults.c @@ -316,1025 +316,1027 @@ static WOptionEnumeration seDragMaximizedWindow[] = { * ALL entries in the tables below NEED to have a default value * defined, and this value needs to be correct. * * Also add the default key/value pair to WindowMaker/Defaults/WindowMaker.in */ /* these options will only affect the window manager on startup * * static defaults can't access the screen data, because it is * created after these defaults are read */ WDefaultEntry staticOptionList[] = { {"ColormapSize", "4", NULL, &wPreferences.cmap_size, getInt, NULL, NULL, NULL}, {"DisableDithering", "NO", NULL, &wPreferences.no_dithering, getBool, NULL, NULL, NULL}, {"IconSize", "64", NULL, &wPreferences.icon_size, getInt, NULL, NULL, NULL}, {"ModifierKey", "Mod1", NULL, &wPreferences.modifier_mask, getModMask, NULL, NULL, NULL}, {"FocusMode", "manual", seFocusModes, /* have a problem when switching from */ &wPreferences.focus_mode, getEnum, NULL, NULL, NULL}, /* manual to sloppy without restart */ {"NewStyle", "new", seTitlebarModes, &wPreferences.new_style, getEnum, NULL, NULL, NULL}, {"DisableDock", "NO", (void *)WM_DOCK, NULL, getBool, setIfDockPresent, NULL, NULL}, {"DisableClip", "NO", (void *)WM_CLIP, NULL, getBool, setIfDockPresent, NULL, NULL}, {"DisableDrawers", "NO", (void *)WM_DRAWER, NULL, getBool, setIfDockPresent, NULL, NULL}, {"ClipMergedInDock", "NO", NULL, NULL, getBool, setClipMergedInDock, NULL, NULL}, {"DisableMiniwindows", "NO", NULL, &wPreferences.disable_miniwindows, getBool, NULL, NULL, NULL}, {"EnableWorkspacePager", "NO", NULL, &wPreferences.enable_workspace_pager, getBool, NULL, NULL, NULL}, {"SwitchPanelIconSize", "64", NULL, &wPreferences.switch_panel_icon_size, getInt, NULL, NULL, NULL}, }; #define NUM2STRING_(x) #x #define NUM2STRING(x) NUM2STRING_(x) WDefaultEntry optionList[] = { /* dynamic options */ {"IconPosition", "blh", seIconPositions, &wPreferences.icon_yard, getEnum, setIconPosition, NULL, NULL}, {"IconificationStyle", "Zoom", seIconificationStyles, &wPreferences.iconification_style, getEnum, NULL, NULL, NULL}, {"EnforceIconMargin", "NO", NULL, &wPreferences.enforce_icon_margin, getBool, NULL, NULL, NULL}, {"DisableWSMouseActions", "NO", NULL, &wPreferences.disable_root_mouse, getBool, NULL, NULL, NULL}, {"MouseLeftButtonAction", "SelectWindows", seMouseButtonActions, &wPreferences.mouse_button1, getEnum, NULL, NULL, NULL}, {"MouseMiddleButtonAction", "OpenWindowListMenu", seMouseButtonActions, &wPreferences.mouse_button2, getEnum, NULL, NULL, NULL}, {"MouseRightButtonAction", "OpenApplicationsMenu", seMouseButtonActions, &wPreferences.mouse_button3, getEnum, NULL, NULL, NULL}, {"MouseBackwardButtonAction", "None", seMouseButtonActions, &wPreferences.mouse_button8, getEnum, NULL, NULL, NULL}, {"MouseForwardButtonAction", "None", seMouseButtonActions, &wPreferences.mouse_button9, getEnum, NULL, NULL, NULL}, {"MouseWheelAction", "None", seMouseWheelActions, &wPreferences.mouse_wheel_scroll, getEnum, NULL, NULL, NULL}, {"MouseWheelTiltAction", "None", seMouseWheelActions, &wPreferences.mouse_wheel_tilt, getEnum, NULL, NULL, NULL}, {"PixmapPath", DEF_PIXMAP_PATHS, NULL, &wPreferences.pixmap_path, getPathList, NULL, NULL, NULL}, {"IconPath", DEF_ICON_PATHS, NULL, &wPreferences.icon_path, getPathList, NULL, NULL, NULL}, {"ColormapMode", "auto", seColormapModes, &wPreferences.colormap_mode, getEnum, NULL, NULL, NULL}, {"AutoFocus", "YES", NULL, &wPreferences.auto_focus, getBool, NULL, NULL, NULL}, {"RaiseDelay", "0", NULL, &wPreferences.raise_delay, getInt, NULL, NULL, NULL}, {"CirculateRaise", "NO", NULL, &wPreferences.circ_raise, getBool, NULL, NULL, NULL}, {"Superfluous", "YES", NULL, &wPreferences.superfluous, getBool, NULL, NULL, NULL}, {"AdvanceToNewWorkspace", "NO", NULL, &wPreferences.ws_advance, getBool, NULL, NULL, NULL}, {"CycleWorkspaces", "NO", NULL, &wPreferences.ws_cycle, getBool, NULL, NULL, NULL}, {"WorkspaceNameDisplayPosition", "center", seDisplayPositions, &wPreferences.workspace_name_display_position, getEnum, NULL, NULL, NULL}, {"WorkspaceBorder", "None", seWorkspaceBorder, &wPreferences.workspace_border_position, getEnum, updateUsableArea, NULL, NULL}, {"WorkspaceBorderSize", "0", NULL, &wPreferences.workspace_border_size, getInt, updateUsableArea, NULL, NULL}, {"StickyIcons", "NO", NULL, &wPreferences.sticky_icons, getBool, setStickyIcons, NULL, NULL}, {"SaveSessionOnExit", "NO", NULL, &wPreferences.save_session_on_exit, getBool, NULL, NULL, NULL}, {"WrapMenus", "NO", NULL, &wPreferences.wrap_menus, getBool, NULL, NULL, NULL}, {"ScrollableMenus", "YES", NULL, &wPreferences.scrollable_menus, getBool, NULL, NULL, NULL}, {"MenuScrollSpeed", "fast", seSpeeds, &wPreferences.menu_scroll_speed, getEnum, NULL, NULL, NULL}, {"IconSlideSpeed", "fast", seSpeeds, &wPreferences.icon_slide_speed, getEnum, NULL, NULL, NULL}, {"ShadeSpeed", "fast", seSpeeds, &wPreferences.shade_speed, getEnum, NULL, NULL, NULL}, {"BounceAppIconsWhenUrgent", "YES", NULL, &wPreferences.bounce_appicons_when_urgent, getBool, NULL, NULL, NULL}, {"RaiseAppIconsWhenBouncing", "NO", NULL, &wPreferences.raise_appicons_when_bouncing, getBool, NULL, NULL, NULL}, {"DoNotMakeAppIconsBounce", "NO", NULL, &wPreferences.do_not_make_appicons_bounce, getBool, NULL, NULL, NULL}, {"DoubleClickTime", "250", (void *)&wPreferences.dblclick_time, &wPreferences.dblclick_time, getInt, setDoubleClick, NULL, NULL}, {"ClipAutoraiseDelay", "600", NULL, &wPreferences.clip_auto_raise_delay, getInt, NULL, NULL, NULL}, {"ClipAutolowerDelay", "1000", NULL, &wPreferences.clip_auto_lower_delay, getInt, NULL, NULL, NULL}, {"ClipAutoexpandDelay", "600", NULL, &wPreferences.clip_auto_expand_delay, getInt, NULL, NULL, NULL}, {"ClipAutocollapseDelay", "1000", NULL, &wPreferences.clip_auto_collapse_delay, getInt, NULL, NULL, NULL}, {"WrapAppiconsInDock", "YES", NULL, NULL, getBool, setWrapAppiconsInDock, NULL, NULL}, {"AlignSubmenus", "NO", NULL, &wPreferences.align_menus, getBool, NULL, NULL, NULL}, {"ViKeyMenus", "NO", NULL, &wPreferences.vi_key_menus, getBool, NULL, NULL, NULL}, {"OpenTransientOnOwnerWorkspace", "NO", NULL, &wPreferences.open_transients_with_parent, getBool, NULL, NULL, NULL}, {"WindowPlacement", "auto", sePlacements, &wPreferences.window_placement, getEnum, NULL, NULL, NULL}, {"IgnoreFocusClick", "NO", NULL, &wPreferences.ignore_focus_click, getBool, NULL, NULL, NULL}, {"UseSaveUnders", "NO", NULL, &wPreferences.use_saveunders, getBool, NULL, NULL, NULL}, {"OpaqueMove", "YES", NULL, &wPreferences.opaque_move, getBool, NULL, NULL, NULL}, {"OpaqueResize", "NO", NULL, &wPreferences.opaque_resize, getBool, NULL, NULL, NULL}, {"OpaqueMoveResizeKeyboard", "NO", NULL, &wPreferences.opaque_move_resize_keyboard, getBool, NULL, NULL, NULL}, {"DisableAnimations", "NO", NULL, &wPreferences.no_animations, getBool, NULL, NULL, NULL}, {"DontLinkWorkspaces", "YES", NULL, &wPreferences.no_autowrap, getBool, NULL, NULL, NULL}, {"WindowSnapping", "NO", NULL, &wPreferences.window_snapping, getBool, NULL, NULL, NULL}, {"SnapEdgeDetect", "1", NULL, &wPreferences.snap_edge_detect, getInt, NULL, NULL, NULL}, {"SnapCornerDetect", "10", NULL, &wPreferences.snap_corner_detect, getInt, NULL, NULL, NULL}, {"SnapToTopMaximizesFullscreen", "NO", NULL, &wPreferences.snap_to_top_maximizes_fullscreen, getBool, NULL, NULL, NULL}, {"DragMaximizedWindow", "Move", seDragMaximizedWindow, &wPreferences.drag_maximized_window, getEnum, NULL, NULL, NULL}, {"MoveHalfMaximizedWindowsBetweenScreens", "NO", NULL, &wPreferences.move_half_max_between_heads, getBool, NULL, NULL, NULL}, {"AlternativeHalfMaximized", "NO", NULL, &wPreferences.alt_half_maximize, getBool, NULL, NULL, NULL}, {"PointerWithHalfMaxWindows", "NO", NULL, &wPreferences.pointer_with_half_max_windows, getBool, NULL, NULL, NULL}, {"HighlightActiveApp", "YES", NULL, &wPreferences.highlight_active_app, getBool, NULL, NULL, NULL}, {"AutoArrangeIcons", "NO", NULL, &wPreferences.auto_arrange_icons, getBool, NULL, NULL, NULL}, {"NoWindowOverDock", "NO", NULL, &wPreferences.no_window_over_dock, getBool, updateUsableArea, NULL, NULL}, {"NoWindowOverIcons", "NO", NULL, &wPreferences.no_window_over_icons, getBool, updateUsableArea, NULL, NULL}, {"WindowPlaceOrigin", "(64, 0)", NULL, &wPreferences.window_place_origin, getCoord, NULL, NULL, NULL}, {"ResizeDisplay", "center", seGeomDisplays, &wPreferences.size_display, getEnum, NULL, NULL, NULL}, {"MoveDisplay", "floating", seGeomDisplays, &wPreferences.move_display, getEnum, NULL, NULL, NULL}, {"DontConfirmKill", "NO", NULL, &wPreferences.dont_confirm_kill, getBool, NULL, NULL, NULL}, {"WindowTitleBalloons", "YES", NULL, &wPreferences.window_balloon, getBool, NULL, NULL, NULL}, {"MiniwindowTitleBalloons", "NO", NULL, &wPreferences.miniwin_title_balloon, getBool, NULL, NULL, NULL}, {"MiniwindowPreviewBalloons", "NO", NULL, &wPreferences.miniwin_preview_balloon, getBool, NULL, NULL, NULL}, {"AppIconBalloons", "NO", NULL, &wPreferences.appicon_balloon, getBool, NULL, NULL, NULL}, {"HelpBalloons", "NO", NULL, &wPreferences.help_balloon, getBool, NULL, NULL, NULL}, {"EdgeResistance", "30", NULL, &wPreferences.edge_resistance, getInt, NULL, NULL, NULL}, {"ResizeIncrement", "0", NULL, &wPreferences.resize_increment, getInt, NULL, NULL, NULL}, {"Attraction", "NO", NULL, &wPreferences.attract, getBool, NULL, NULL, NULL}, {"DisableBlinking", "NO", NULL, &wPreferences.dont_blink, getBool, NULL, NULL, NULL}, {"SingleClickLaunch", "NO", NULL, &wPreferences.single_click, getBool, NULL, NULL, NULL}, {"StrictWindozeCycle", "YES", NULL, &wPreferences.strict_windoze_cycle, getBool, NULL, NULL, NULL}, {"SwitchPanelOnlyOpen", "NO", NULL, &wPreferences.panel_only_open, getBool, NULL, NULL, NULL}, {"MiniPreviewSize", "128", NULL, &wPreferences.minipreview_size, getInt, NULL, NULL, NULL}, {"IgnoreGtkHints", "NO", NULL, &wPreferences.ignore_gtk_decoration_hints, getBool, NULL, NULL, NULL}, /* style options */ {"MenuStyle", "normal", seMenuStyles, &wPreferences.menu_style, getEnum, setMenuStyle, NULL, NULL}, {"WidgetColor", "(solid, gray)", NULL, NULL, getTexture, setWidgetColor, NULL, NULL}, {"WorkspaceSpecificBack", "()", NULL, NULL, getWSSpecificBackground, setWorkspaceSpecificBack, NULL, NULL}, /* WorkspaceBack must come after WorkspaceSpecificBack or * WorkspaceBack won't know WorkspaceSpecificBack was also * specified and 2 copies of wmsetbg will be launched */ {"WorkspaceBack", "(solid, \"rgb:50/50/75\")", NULL, NULL, getWSBackground, setWorkspaceBack, NULL, NULL}, {"SmoothWorkspaceBack", "NO", NULL, NULL, getBool, NULL, NULL, NULL}, {"IconBack", "(dgradient, \"rgb:a6/a6/b6\", \"rgb:51/55/61\")", NULL, NULL, getTexture, setIconTile, NULL, NULL}, {"TitleJustify", "center", seJustifications, &wPreferences.title_justification, getEnum, setJustify, NULL, NULL}, {"WindowTitleFont", DEF_TITLE_FONT, NULL, NULL, getFont, setWinTitleFont, NULL, NULL}, {"WindowTitleExtendSpace", DEF_WINDOW_TITLE_EXTEND_SPACE, NULL, &wPreferences.window_title_clearance, getInt, setClearance, NULL, NULL}, {"WindowTitleMinHeight", "0", NULL, &wPreferences.window_title_min_height, getInt, setClearance, NULL, NULL}, {"WindowTitleMaxHeight", NUM2STRING(INT_MAX), NULL, &wPreferences.window_title_max_height, getInt, setClearance, NULL, NULL}, {"MenuTitleExtendSpace", DEF_MENU_TITLE_EXTEND_SPACE, NULL, &wPreferences.menu_title_clearance, getInt, setClearance, NULL, NULL}, {"MenuTitleMinHeight", "0", NULL, &wPreferences.menu_title_min_height, getInt, setClearance, NULL, NULL}, {"MenuTitleMaxHeight", NUM2STRING(INT_MAX), NULL, &wPreferences.menu_title_max_height, getInt, setClearance, NULL, NULL}, {"MenuTextExtendSpace", DEF_MENU_TEXT_EXTEND_SPACE, NULL, &wPreferences.menu_text_clearance, getInt, setClearance, NULL, NULL}, {"MenuTitleFont", DEF_MENU_TITLE_FONT, NULL, NULL, getFont, setMenuTitleFont, NULL, NULL}, {"MenuTextFont", DEF_MENU_ENTRY_FONT, NULL, NULL, getFont, setMenuTextFont, NULL, NULL}, {"IconTitleFont", DEF_ICON_TITLE_FONT, NULL, NULL, getFont, setIconTitleFont, NULL, NULL}, {"ClipTitleFont", DEF_CLIP_TITLE_FONT, NULL, NULL, getFont, setClipTitleFont, NULL, NULL}, {"ShowClipTitle", "YES", NULL, &wPreferences.show_clip_title, getBool, NULL, NULL, NULL}, {"LargeDisplayFont", DEF_WORKSPACE_NAME_FONT, NULL, NULL, getFont, setLargeDisplayFont, NULL, NULL}, {"HighlightColor", "white", NULL, NULL, getColor, setHightlight, NULL, NULL}, {"HighlightTextColor", "black", NULL, NULL, getColor, setHightlightText, NULL, NULL}, {"ClipTitleColor", "black", (void *)CLIP_NORMAL, NULL, getColor, setClipTitleColor, NULL, NULL}, {"CClipTitleColor", "\"rgb:61/61/61\"", (void *)CLIP_COLLAPSED, NULL, getColor, setClipTitleColor, NULL, NULL}, {"FTitleColor", "white", (void *)WS_FOCUSED, NULL, getColor, setWTitleColor, NULL, NULL}, {"PTitleColor", "white", (void *)WS_PFOCUSED, NULL, getColor, setWTitleColor, NULL, NULL}, {"UTitleColor", "black", (void *)WS_UNFOCUSED, NULL, getColor, setWTitleColor, NULL, NULL}, {"FTitleBack", "(solid, black)", NULL, NULL, getTexture, setFTitleBack, NULL, NULL}, {"PTitleBack", "(solid, gray40)", NULL, NULL, getTexture, setPTitleBack, NULL, NULL}, {"UTitleBack", "(solid, \"rgb:aa/aa/aa\")", NULL, NULL, getTexture, setUTitleBack, NULL, NULL}, {"ResizebarBack", "(solid, \"rgb:aa/aa/aa\")", NULL, NULL, getTexture, setResizebarBack, NULL, NULL}, {"MenuTitleColor", "white", NULL, NULL, getColor, setMenuTitleColor, NULL, NULL}, {"MenuTextColor", "black", NULL, NULL, getColor, setMenuTextColor, NULL, NULL}, {"MenuDisabledColor", "gray50", NULL, NULL, getColor, setMenuDisabledColor, NULL, NULL}, {"MenuTitleBack", "(solid, black)", NULL, NULL, getTexture, setMenuTitleBack, NULL, NULL}, {"MenuTextBack", "(solid, \"rgb:aa/aa/aa\")", NULL, NULL, getTexture, setMenuTextBack, NULL, NULL}, {"IconTitleColor", "white", NULL, NULL, getColor, setIconTitleColor, NULL, NULL}, {"IconTitleBack", "black", NULL, NULL, getColor, setIconTitleBack, NULL, NULL}, {"SwitchPanelImages", "(swtile.png, swback.png, 30, 40)", &wPreferences, NULL, getPropList, setSwPOptions, NULL, NULL}, {"ModifierKeyLabels", "(\"Shift+\", \"Control+\", \"Mod1+\", \"Mod2+\", \"Mod3+\", \"Mod4+\", \"Mod5+\")", &wPreferences, NULL, getPropList, setModifierKeyLabels, NULL, NULL}, {"FrameBorderWidth", "1", NULL, NULL, getInt, setFrameBorderWidth, NULL, NULL}, {"FrameBorderColor", "black", NULL, NULL, getColor, setFrameBorderColor, NULL, NULL}, {"FrameFocusedBorderColor", "black", NULL, NULL, getColor, setFrameFocusedBorderColor, NULL, NULL}, {"FrameSelectedBorderColor", "white", NULL, NULL, getColor, setFrameSelectedBorderColor, NULL, NULL}, {"WorkspaceMapBack", "(solid, black)", NULL, NULL, getTexture, setWorkspaceMapBackground, NULL, NULL}, /* keybindings */ {"RootMenuKey", "F12", (void *)WKBD_ROOTMENU, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowListKey", "F11", (void *)WKBD_WINDOWLIST, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowMenuKey", "Control+Escape", (void *)WKBD_WINDOWMENU, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"DockRaiseLowerKey", "None", (void*)WKBD_DOCKRAISELOWER, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"ClipRaiseLowerKey", "None", (void *)WKBD_CLIPRAISELOWER, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MiniaturizeKey", "Mod1+M", (void *)WKBD_MINIATURIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MinimizeAllKey", "None", (void *)WKBD_MINIMIZEALL, NULL, getKeybind, setKeyGrab, NULL, NULL }, {"HideKey", "Mod1+H", (void *)WKBD_HIDE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"HideOthersKey", "None", (void *)WKBD_HIDE_OTHERS, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveResizeKey", "None", (void *)WKBD_MOVERESIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"CloseKey", "None", (void *)WKBD_CLOSE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MaximizeKey", "None", (void *)WKBD_MAXIMIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"VMaximizeKey", "None", (void *)WKBD_VMAXIMIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"HMaximizeKey", "None", (void *)WKBD_HMAXIMIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"LHMaximizeKey", "None", (void*)WKBD_LHMAXIMIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"RHMaximizeKey", "None", (void*)WKBD_RHMAXIMIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"THMaximizeKey", "None", (void*)WKBD_THMAXIMIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"BHMaximizeKey", "None", (void*)WKBD_BHMAXIMIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"LTCMaximizeKey", "None", (void*)WKBD_LTCMAXIMIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"RTCMaximizeKey", "None", (void*)WKBD_RTCMAXIMIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"LBCMaximizeKey", "None", (void*)WKBD_LBCMAXIMIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"RBCMaximizeKey", "None", (void*)WKBD_RBCMAXIMIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MaximusKey", "None", (void*)WKBD_MAXIMUS, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"KeepOnTopKey", "None", (void *)WKBD_KEEP_ON_TOP, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"KeepAtBottomKey", "None", (void *)WKBD_KEEP_AT_BOTTOM, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"OmnipresentKey", "None", (void *)WKBD_OMNIPRESENT, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"RaiseKey", "Mod1+Up", (void *)WKBD_RAISE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"LowerKey", "Mod1+Down", (void *)WKBD_LOWER, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"RaiseLowerKey", "None", (void *)WKBD_RAISELOWER, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"ShadeKey", "None", (void *)WKBD_SHADE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"SelectKey", "None", (void *)WKBD_SELECT, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WorkspaceMapKey", "None", (void *)WKBD_WORKSPACEMAP, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"FocusNextKey", "Mod1+Tab", (void *)WKBD_FOCUSNEXT, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"FocusPrevKey", "Mod1+Shift+Tab", (void *)WKBD_FOCUSPREV, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"GroupNextKey", "None", (void *)WKBD_GROUPNEXT, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"GroupPrevKey", "None", (void *)WKBD_GROUPPREV, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"NextWorkspaceKey", "Mod1+Control+Right", (void *)WKBD_NEXTWORKSPACE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"PrevWorkspaceKey", "Mod1+Control+Left", (void *)WKBD_PREVWORKSPACE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"LastWorkspaceKey", "None", (void *)WKBD_LASTWORKSPACE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"NextWorkspaceLayerKey", "None", (void *)WKBD_NEXTWSLAYER, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"PrevWorkspaceLayerKey", "None", (void *)WKBD_PREVWSLAYER, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"Workspace1Key", "Mod1+1", (void *)WKBD_WORKSPACE1, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"Workspace2Key", "Mod1+2", (void *)WKBD_WORKSPACE2, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"Workspace3Key", "Mod1+3", (void *)WKBD_WORKSPACE3, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"Workspace4Key", "Mod1+4", (void *)WKBD_WORKSPACE4, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"Workspace5Key", "Mod1+5", (void *)WKBD_WORKSPACE5, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"Workspace6Key", "Mod1+6", (void *)WKBD_WORKSPACE6, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"Workspace7Key", "Mod1+7", (void *)WKBD_WORKSPACE7, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"Workspace8Key", "Mod1+8", (void *)WKBD_WORKSPACE8, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"Workspace9Key", "Mod1+9", (void *)WKBD_WORKSPACE9, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"Workspace10Key", "Mod1+0", (void *)WKBD_WORKSPACE10, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToWorkspace1Key", "None", (void *)WKBD_MOVE_WORKSPACE1, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToWorkspace2Key", "None", (void *)WKBD_MOVE_WORKSPACE2, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToWorkspace3Key", "None", (void *)WKBD_MOVE_WORKSPACE3, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToWorkspace4Key", "None", (void *)WKBD_MOVE_WORKSPACE4, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToWorkspace5Key", "None", (void *)WKBD_MOVE_WORKSPACE5, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToWorkspace6Key", "None", (void *)WKBD_MOVE_WORKSPACE6, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToWorkspace7Key", "None", (void *)WKBD_MOVE_WORKSPACE7, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToWorkspace8Key", "None", (void *)WKBD_MOVE_WORKSPACE8, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToWorkspace9Key", "None", (void *)WKBD_MOVE_WORKSPACE9, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToWorkspace10Key", "None", (void *)WKBD_MOVE_WORKSPACE10, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToNextWorkspaceKey", "None", (void *)WKBD_MOVE_NEXTWORKSPACE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToPrevWorkspaceKey", "None", (void *)WKBD_MOVE_PREVWORKSPACE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToLastWorkspaceKey", "None", (void *)WKBD_MOVE_LASTWORKSPACE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToNextWorkspaceLayerKey", "None", (void *)WKBD_MOVE_NEXTWSLAYER, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToPrevWorkspaceLayerKey", "None", (void *)WKBD_MOVE_PREVWSLAYER, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowShortcut1Key", "None", (void *)WKBD_WINDOW1, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowShortcut2Key", "None", (void *)WKBD_WINDOW2, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowShortcut3Key", "None", (void *)WKBD_WINDOW3, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowShortcut4Key", "None", (void *)WKBD_WINDOW4, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowShortcut5Key", "None", (void *)WKBD_WINDOW5, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowShortcut6Key", "None", (void *)WKBD_WINDOW6, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowShortcut7Key", "None", (void *)WKBD_WINDOW7, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowShortcut8Key", "None", (void *)WKBD_WINDOW8, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowShortcut9Key", "None", (void *)WKBD_WINDOW9, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowShortcut10Key", "None", (void *)WKBD_WINDOW10, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveTo12to6Head", "None", (void *)WKBD_MOVE_12_TO_6_HEAD, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveTo6to12Head", "None", (void *)WKBD_MOVE_6_TO_12_HEAD, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowRelaunchKey", "None", (void *)WKBD_RELAUNCH, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"ScreenSwitchKey", "None", (void *)WKBD_SWITCH_SCREEN, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"RunKey", "None", (void *)WKBD_RUN, NULL, getKeybind, setKeyGrab, NULL, NULL}, #ifdef KEEP_XKB_LOCK_STATUS {"ToggleKbdModeKey", "None", (void *)WKBD_TOGGLE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"KbdModeLock", "NO", NULL, &wPreferences.modelock, getBool, NULL, NULL, NULL}, #endif /* KEEP_XKB_LOCK_STATUS */ {"NormalCursor", "(builtin, left_ptr)", (void *)WCUR_ROOT, NULL, getCursor, setCursor, NULL, NULL}, {"ArrowCursor", "(builtin, top_left_arrow)", (void *)WCUR_ARROW, NULL, getCursor, setCursor, NULL, NULL}, {"MoveCursor", "(builtin, fleur)", (void *)WCUR_MOVE, NULL, getCursor, setCursor, NULL, NULL}, {"ResizeCursor", "(builtin, sizing)", (void *)WCUR_RESIZE, NULL, getCursor, setCursor, NULL, NULL}, {"TopLeftResizeCursor", "(builtin, top_left_corner)", (void *)WCUR_TOPLEFTRESIZE, NULL, getCursor, setCursor, NULL, NULL}, {"TopRightResizeCursor", "(builtin, top_right_corner)", (void *)WCUR_TOPRIGHTRESIZE, NULL, getCursor, setCursor, NULL, NULL}, {"BottomLeftResizeCursor", "(builtin, bottom_left_corner)", (void *)WCUR_BOTTOMLEFTRESIZE, NULL, getCursor, setCursor, NULL, NULL}, {"BottomRightResizeCursor", "(builtin, bottom_right_corner)", (void *)WCUR_BOTTOMRIGHTRESIZE, NULL, getCursor, setCursor, NULL, NULL}, {"VerticalResizeCursor", "(builtin, sb_v_double_arrow)", (void *)WCUR_VERTICALRESIZE, NULL, getCursor, setCursor, NULL, NULL}, {"HorizontalResizeCursor", "(builtin, sb_h_double_arrow)", (void *)WCUR_HORIZONRESIZE, NULL, getCursor, setCursor, NULL, NULL}, {"WaitCursor", "(builtin, watch)", (void *)WCUR_WAIT, NULL, getCursor, setCursor, NULL, NULL}, {"QuestionCursor", "(builtin, question_arrow)", (void *)WCUR_QUESTION, NULL, getCursor, setCursor, NULL, NULL}, {"TextCursor", "(builtin, xterm)", (void *)WCUR_TEXT, NULL, getCursor, setCursor, NULL, NULL}, {"SelectCursor", "(builtin, cross)", (void *)WCUR_SELECT, NULL, getCursor, setCursor, NULL, NULL}, {"DialogHistoryLines", "500", NULL, &wPreferences.history_lines, getInt, NULL, NULL, NULL}, {"CycleActiveHeadOnly", "NO", NULL, &wPreferences.cycle_active_head_only, getBool, NULL, NULL, NULL}, {"CycleIgnoreMinimized", "NO", NULL, - &wPreferences.cycle_ignore_minimized, getBool, NULL, NULL, NULL} + &wPreferences.cycle_ignore_minimized, getBool, NULL, NULL, NULL}, + {"DbClickFullScreen", "NO", NULL, + &wPreferences.double_click_fullscreen, getBool, NULL, NULL, NULL} }; static void initDefaults(void) { unsigned int i; WDefaultEntry *entry; WMPLSetCaseSensitive(False); for (i = 0; i < wlengthof(optionList); i++) { entry = &optionList[i]; entry->plkey = WMCreatePLString(entry->key); if (entry->default_value) entry->plvalue = WMCreatePropListFromDescription(entry->default_value); else entry->plvalue = NULL; } for (i = 0; i < wlengthof(staticOptionList); i++) { entry = &staticOptionList[i]; entry->plkey = WMCreatePLString(entry->key); if (entry->default_value) entry->plvalue = WMCreatePropListFromDescription(entry->default_value); else entry->plvalue = NULL; } } static WMPropList *readGlobalDomain(const char *domainName, Bool requireDictionary) { WMPropList *globalDict = NULL; char path[PATH_MAX]; struct stat stbuf; snprintf(path, sizeof(path), "%s/%s", DEFSDATADIR, domainName); if (stat(path, &stbuf) >= 0) { globalDict = WMReadPropListFromFile(path); if (globalDict && requireDictionary && !WMIsPLDictionary(globalDict)) { wwarning(_("Domain %s (%s) of global defaults database is corrupted!"), domainName, path); WMReleasePropList(globalDict); globalDict = NULL; } else if (!globalDict) { wwarning(_("could not load domain %s from global defaults database"), domainName); } } return globalDict; } #if defined(GLOBAL_PREAMBLE_MENU_FILE) || defined(GLOBAL_EPILOGUE_MENU_FILE) static void prependMenu(WMPropList * destarr, WMPropList * array) { WMPropList *item; int i; for (i = 0; i < WMGetPropListItemCount(array); i++) { item = WMGetFromPLArray(array, i); if (item) WMInsertInPLArray(destarr, i + 1, item); } } static void appendMenu(WMPropList * destarr, WMPropList * array) { WMPropList *item; int i; for (i = 0; i < WMGetPropListItemCount(array); i++) { item = WMGetFromPLArray(array, i); if (item) WMAddToPLArray(destarr, item); } } #endif void wDefaultsMergeGlobalMenus(WDDomain * menuDomain) { WMPropList *menu = menuDomain->dictionary; WMPropList *submenu; if (!menu || !WMIsPLArray(menu)) return; #ifdef GLOBAL_PREAMBLE_MENU_FILE submenu = WMReadPropListFromFile(DEFSDATADIR "/" GLOBAL_PREAMBLE_MENU_FILE); if (submenu && !WMIsPLArray(submenu)) { wwarning(_("invalid global menu file %s"), GLOBAL_PREAMBLE_MENU_FILE); WMReleasePropList(submenu); submenu = NULL; } if (submenu) { prependMenu(menu, submenu); WMReleasePropList(submenu); } #endif #ifdef GLOBAL_EPILOGUE_MENU_FILE submenu = WMReadPropListFromFile(DEFSDATADIR "/" GLOBAL_EPILOGUE_MENU_FILE); if (submenu && !WMIsPLArray(submenu)) { wwarning(_("invalid global menu file %s"), GLOBAL_EPILOGUE_MENU_FILE); WMReleasePropList(submenu); submenu = NULL; } if (submenu) { appendMenu(menu, submenu); WMReleasePropList(submenu); } #endif menuDomain->dictionary = menu; } WDDomain *wDefaultsInitDomain(const char *domain, Bool requireDictionary) { WDDomain *db; struct stat stbuf; static int inited = 0; WMPropList *shared_dict = NULL; if (!inited) { inited = 1; initDefaults(); } db = wmalloc(sizeof(WDDomain)); db->domain_name = domain; db->path = wdefaultspathfordomain(domain); if (stat(db->path, &stbuf) >= 0) { db->dictionary = WMReadPropListFromFile(db->path); if (db->dictionary) { if (requireDictionary && !WMIsPLDictionary(db->dictionary)) { WMReleasePropList(db->dictionary); db->dictionary = NULL; wwarning(_("Domain %s (%s) of defaults database is corrupted!"), domain, db->path); } db->timestamp = stbuf.st_mtime; } else { wwarning(_("could not load domain %s from user defaults database"), domain); } } /* global system dictionary */ shared_dict = readGlobalDomain(domain, requireDictionary); if (shared_dict && db->dictionary && WMIsPLDictionary(shared_dict) && WMIsPLDictionary(db->dictionary)) { WMMergePLDictionaries(shared_dict, db->dictionary, True); WMReleasePropList(db->dictionary); db->dictionary = shared_dict; if (stbuf.st_mtime > db->timestamp) db->timestamp = stbuf.st_mtime; } else if (!db->dictionary) { db->dictionary = shared_dict; if (stbuf.st_mtime > db->timestamp) db->timestamp = stbuf.st_mtime; } return db; } void wReadStaticDefaults(WMPropList * dict) { WMPropList *plvalue; WDefaultEntry *entry; unsigned int i; void *tdata; for (i = 0; i < wlengthof(staticOptionList); i++) { entry = &staticOptionList[i]; if (dict) plvalue = WMGetFromPLDictionary(dict, entry->plkey); else plvalue = NULL; /* no default in the DB. Use builtin default */ if (!plvalue) plvalue = entry->plvalue; if (plvalue) { /* convert data */ (*entry->convert) (NULL, entry, plvalue, entry->addr, &tdata); if (entry->update) (*entry->update) (NULL, entry, tdata, entry->extra_data); } } } void wDefaultsCheckDomains(void* arg) { WScreen *scr; struct stat stbuf; WMPropList *shared_dict = NULL; WMPropList *dict; int i; /* Parameter not used, but tell the compiler that it is ok */ (void) arg; if (stat(w_global.domain.wmaker->path, &stbuf) >= 0 && w_global.domain.wmaker->timestamp < stbuf.st_mtime) { w_global.domain.wmaker->timestamp = stbuf.st_mtime; /* Global dictionary */ shared_dict = readGlobalDomain("WindowMaker", True); /* User dictionary */ dict = WMReadPropListFromFile(w_global.domain.wmaker->path); if (dict) { if (!WMIsPLDictionary(dict)) { WMReleasePropList(dict); dict = NULL; wwarning(_("Domain %s (%s) of defaults database is corrupted!"), "WindowMaker", w_global.domain.wmaker->path); } else { if (shared_dict) { WMMergePLDictionaries(shared_dict, dict, True); WMReleasePropList(dict); dict = shared_dict; shared_dict = NULL; } for (i = 0; i < w_global.screen_count; i++) { scr = wScreenWithNumber(i); if (scr) wReadDefaults(scr, dict); } if (w_global.domain.wmaker->dictionary) WMReleasePropList(w_global.domain.wmaker->dictionary); w_global.domain.wmaker->dictionary = dict; } } else { wwarning(_("could not load domain %s from user defaults database"), "WindowMaker"); } if (shared_dict) WMReleasePropList(shared_dict); } if (stat(w_global.domain.window_attr->path, &stbuf) >= 0 && w_global.domain.window_attr->timestamp < stbuf.st_mtime) { /* global dictionary */ shared_dict = readGlobalDomain("WMWindowAttributes", True); /* user dictionary */ dict = WMReadPropListFromFile(w_global.domain.window_attr->path); if (dict) { if (!WMIsPLDictionary(dict)) { WMReleasePropList(dict); dict = NULL; wwarning(_("Domain %s (%s) of defaults database is corrupted!"), "WMWindowAttributes", w_global.domain.window_attr->path); } else { if (shared_dict) { WMMergePLDictionaries(shared_dict, dict, True); WMReleasePropList(dict); dict = shared_dict; shared_dict = NULL; } if (w_global.domain.window_attr->dictionary) WMReleasePropList(w_global.domain.window_attr->dictionary); w_global.domain.window_attr->dictionary = dict; for (i = 0; i < w_global.screen_count; i++) { scr = wScreenWithNumber(i); if (scr) { wDefaultUpdateIcons(scr); /* Update the panel image if changed */ /* Don't worry. If the image is the same these * functions will have no performance impact. */ create_logo_image(scr); } } } } else { wwarning(_("could not load domain %s from user defaults database"), "WMWindowAttributes"); } w_global.domain.window_attr->timestamp = stbuf.st_mtime; if (shared_dict) WMReleasePropList(shared_dict); } if (stat(w_global.domain.root_menu->path, &stbuf) >= 0 && w_global.domain.root_menu->timestamp < stbuf.st_mtime) { dict = WMReadPropListFromFile(w_global.domain.root_menu->path); if (dict) { if (!WMIsPLArray(dict) && !WMIsPLString(dict)) { WMReleasePropList(dict); dict = NULL; wwarning(_("Domain %s (%s) of defaults database is corrupted!"), "WMRootMenu", w_global.domain.root_menu->path); } else { if (w_global.domain.root_menu->dictionary) WMReleasePropList(w_global.domain.root_menu->dictionary); w_global.domain.root_menu->dictionary = dict; wDefaultsMergeGlobalMenus(w_global.domain.root_menu); } } else { wwarning(_("could not load domain %s from user defaults database"), "WMRootMenu"); } w_global.domain.root_menu->timestamp = stbuf.st_mtime; } #ifndef HAVE_INOTIFY if (!arg) WMAddTimerHandler(DEFAULTS_CHECK_INTERVAL, wDefaultsCheckDomains, arg); #endif } void wReadDefaults(WScreen * scr, WMPropList * new_dict) { WMPropList *plvalue, *old_value; WDefaultEntry *entry; unsigned int i; int update_workspace_back = 0; /* kluge :/ */ unsigned int needs_refresh; void *tdata; WMPropList *old_dict = (w_global.domain.wmaker->dictionary != new_dict ? w_global.domain.wmaker->dictionary : NULL); needs_refresh = 0; for (i = 0; i < wlengthof(optionList); i++) { entry = &optionList[i]; if (new_dict) plvalue = WMGetFromPLDictionary(new_dict, entry->plkey); else plvalue = NULL; if (!old_dict) old_value = NULL; else old_value = WMGetFromPLDictionary(old_dict, entry->plkey); if (!plvalue && !old_value) { /* no default in the DB. Use builtin default */ plvalue = entry->plvalue; if (plvalue && new_dict) WMPutInPLDictionary(new_dict, entry->plkey, plvalue); } else if (!plvalue) { /* value was deleted from DB. Keep current value */ continue; } else if (!old_value) { /* set value for the 1st time */ } else if (!WMIsPropListEqualTo(plvalue, old_value)) { /* value has changed */ } else { if (strcmp(entry->key, "WorkspaceBack") == 0 && update_workspace_back && scr->flags.backimage_helper_launched) { } else { /* value was not changed since last time */ continue; } } if (plvalue) { /* convert data */ if ((*entry->convert) (scr, entry, plvalue, entry->addr, &tdata)) { /* * If the WorkspaceSpecificBack data has been changed * so that the helper will be launched now, we must be * sure to send the default background texture config * to the helper. */ if (strcmp(entry->key, "WorkspaceSpecificBack") == 0 && !scr->flags.backimage_helper_launched) update_workspace_back = 1; if (entry->update) needs_refresh |= (*entry->update) (scr, entry, tdata, entry->extra_data); } } } if (needs_refresh != 0 && !scr->flags.startup) { int foo; foo = 0; if (needs_refresh & REFRESH_MENU_TITLE_TEXTURE) foo |= WTextureSettings; if (needs_refresh & REFRESH_MENU_TITLE_FONT) foo |= WFontSettings; if (needs_refresh & REFRESH_MENU_TITLE_COLOR) foo |= WColorSettings; if (foo) WMPostNotificationName(WNMenuTitleAppearanceSettingsChanged, NULL, (void *)(uintptr_t) foo); foo = 0; if (needs_refresh & REFRESH_MENU_TEXTURE) foo |= WTextureSettings; if (needs_refresh & REFRESH_MENU_FONT) foo |= WFontSettings; if (needs_refresh & REFRESH_MENU_COLOR) foo |= WColorSettings; if (foo) WMPostNotificationName(WNMenuAppearanceSettingsChanged, NULL, (void *)(uintptr_t) foo); foo = 0; if (needs_refresh & REFRESH_WINDOW_FONT) foo |= WFontSettings; if (needs_refresh & REFRESH_WINDOW_TEXTURES) foo |= WTextureSettings; if (needs_refresh & REFRESH_WINDOW_TITLE_COLOR) foo |= WColorSettings; if (foo) WMPostNotificationName(WNWindowAppearanceSettingsChanged, NULL, (void *)(uintptr_t) foo); if (!(needs_refresh & REFRESH_ICON_TILE)) { foo = 0; if (needs_refresh & REFRESH_ICON_FONT) foo |= WFontSettings; if (needs_refresh & REFRESH_ICON_TITLE_COLOR) foo |= WTextureSettings; if (needs_refresh & REFRESH_ICON_TITLE_BACK) foo |= WTextureSettings; if (foo) WMPostNotificationName(WNIconAppearanceSettingsChanged, NULL, (void *)(uintptr_t) foo); } if (needs_refresh & REFRESH_ICON_TILE) WMPostNotificationName(WNIconTileSettingsChanged, NULL, NULL); if (needs_refresh & REFRESH_WORKSPACE_MENU) { if (scr->workspace_menu) wWorkspaceMenuUpdate(scr, scr->workspace_menu); if (scr->clip_ws_menu) wWorkspaceMenuUpdate(scr, scr->clip_ws_menu); if (scr->workspace_submenu) scr->workspace_submenu->flags.realized = 0; if (scr->clip_submenu) scr->clip_submenu->flags.realized = 0; } } } void wDefaultUpdateIcons(WScreen *scr) { WAppIcon *aicon = scr->app_icon_list; WDrawerChain *dc; WWindow *wwin = scr->focused_window; while (aicon) { /* Get the application icon, default included */ wIconChangeImageFile(aicon->icon, NULL); wAppIconPaint(aicon); aicon = aicon->next; } if (!wPreferences.flags.noclip || wPreferences.flags.clip_merged_in_dock) wClipIconPaint(scr->clip_icon); for (dc = scr->drawers; dc != NULL; dc = dc->next) wDrawerIconPaint(dc->adrawer->icon_array[0]); while (wwin) { if (wwin->icon && wwin->flags.miniaturized) wIconChangeImageFile(wwin->icon, NULL); wwin = wwin->prev; } } /* --------------------------- Local ----------------------- */ #define GET_STRING_OR_DEFAULT(x, var) if (!WMIsPLString(value)) { \ wwarning(_("Wrong option format for key \"%s\". Should be %s."), \ entry->key, x); \ wwarning(_("using default \"%s\" instead"), entry->default_value); \ var = entry->default_value;\ } else var = WMGetFromPLString(value)\ static int string2index(WMPropList *key, WMPropList *val, const char *def, WOptionEnumeration * values) { char *str; WOptionEnumeration *v; char buffer[TOTAL_VALUES_LENGTH]; if (WMIsPLString(val) && (str = WMGetFromPLString(val))) { for (v = values; v->string != NULL; v++) { if (strcasecmp(v->string, str) == 0) return v->value; } } buffer[0] = 0; for (v = values; v->string != NULL; v++) { if (!v->is_alias) { if (buffer[0] != 0) strcat(buffer, ", "); snprintf(buffer+strlen(buffer), sizeof(buffer)-strlen(buffer)-1, "\"%s\"", v->string); } } wwarning(_("wrong option value for key \"%s\"; got \"%s\", should be one of %s."), WMGetFromPLString(key), WMIsPLString(val) ? WMGetFromPLString(val) : "(unknown)", buffer); if (def) { return string2index(key, val, NULL, values); } diff --git a/src/window.c b/src/window.c index a276f48..bf6e6e3 100644 --- a/src/window.c +++ b/src/window.c @@ -2340,788 +2340,802 @@ void wWindowConfigureBorders(WWindow *wwin) && wwin->frame->flags.hide_left_button) flags |= WFF_LEFT_BUTTON; #ifdef XKB_BUTTON_HINT if (!WFLAGP(wwin, no_language_button) && wwin->frame->flags.hide_language_button) flags |= WFF_LANGUAGE_BUTTON; #endif if (!WFLAGP(wwin, no_close_button) && wwin->frame->flags.hide_right_button) flags |= WFF_RIGHT_BUTTON; if (flags != 0) { wWindowUpdateButtonImages(wwin); wFrameWindowShowButton(wwin->frame, flags); } flags = 0; if (WFLAGP(wwin, no_miniaturize_button) && !wwin->frame->flags.hide_left_button) flags |= WFF_LEFT_BUTTON; #ifdef XKB_BUTTON_HINT if (WFLAGP(wwin, no_language_button) && !wwin->frame->flags.hide_language_button) flags |= WFF_LANGUAGE_BUTTON; #endif if (WFLAGP(wwin, no_close_button) && !wwin->frame->flags.hide_right_button) flags |= WFF_RIGHT_BUTTON; if (flags != 0) wFrameWindowHideButton(wwin->frame, flags); #ifdef USE_XSHAPE if (w_global.xext.shape.supported && wwin->flags.shaped) wWindowSetShape(wwin); #endif } } void wWindowSaveState(WWindow *wwin) { long data[10]; int i; memset(data, 0, sizeof(long) * 10); data[0] = wwin->frame->workspace; data[1] = wwin->flags.miniaturized; data[2] = wwin->flags.shaded; data[3] = wwin->flags.hidden; data[4] = wwin->flags.maximized; if (wwin->flags.maximized == 0) { data[5] = wwin->frame_x; data[6] = wwin->frame_y; data[7] = wwin->frame->core->width; data[8] = wwin->frame->core->height; } else { data[5] = wwin->old_geometry.x; data[6] = wwin->old_geometry.y; data[7] = wwin->old_geometry.width; data[8] = wwin->old_geometry.height; } for (i = 0; i < MAX_WINDOW_SHORTCUTS; i++) { if (wwin->screen_ptr->shortcutWindows[i] && WMCountInArray(wwin->screen_ptr->shortcutWindows[i], wwin)) data[9] |= 1 << i; } XChangeProperty(dpy, wwin->client_win, w_global.atom.wmaker.state, w_global.atom.wmaker.state, 32, PropModeReplace, (unsigned char *)data, 10); } static int getSavedState(Window window, WSavedState ** state) { Atom type_ret; int fmt_ret; unsigned long nitems_ret; unsigned long bytes_after_ret; long *data; if (XGetWindowProperty(dpy, window, w_global.atom.wmaker.state, 0, 10, True, w_global.atom.wmaker.state, &type_ret, &fmt_ret, &nitems_ret, &bytes_after_ret, (unsigned char **)&data) != Success || !data || nitems_ret < 10) return 0; if (type_ret != w_global.atom.wmaker.state) { XFree(data); return 0; } *state = wmalloc(sizeof(WSavedState)); (*state)->workspace = data[0]; (*state)->miniaturized = data[1]; (*state)->shaded = data[2]; (*state)->hidden = data[3]; (*state)->maximized = data[4]; (*state)->x = data[5]; (*state)->y = data[6]; (*state)->w = data[7]; (*state)->h = data[8]; (*state)->window_shortcuts = data[9]; XFree(data); return 1; } #ifdef USE_XSHAPE void wWindowClearShape(WWindow * wwin) { XShapeCombineMask(dpy, wwin->frame->core->window, ShapeBounding, 0, wwin->frame->top_width, None, ShapeSet); XFlush(dpy); } void wWindowSetShape(WWindow * wwin) { XRectangle rect[2]; int count; #ifdef OPTIMIZE_SHAPE XRectangle *rects; XRectangle *urec; int ordering; /* only shape is the client's */ if (!HAS_TITLEBAR(wwin) && !HAS_RESIZEBAR(wwin)) goto alt_code; /* Get array of rectangles describing the shape mask */ rects = XShapeGetRectangles(dpy, wwin->client_win, ShapeBounding, &count, &ordering); if (!rects) goto alt_code; urec = malloc(sizeof(XRectangle) * (count + 2)); if (!urec) { XFree(rects); goto alt_code; } /* insert our decoration rectangles in the rect list */ memcpy(urec, rects, sizeof(XRectangle) * count); XFree(rects); if (HAS_TITLEBAR(wwin)) { urec[count].x = -1; urec[count].y = -1 - wwin->frame->top_width; urec[count].width = wwin->frame->core->width + 2; urec[count].height = wwin->frame->top_width + 1; count++; } if (HAS_RESIZEBAR(wwin)) { urec[count].x = -1; urec[count].y = wwin->frame->core->height - wwin->frame->bottom_width - wwin->frame->top_width; urec[count].width = wwin->frame->core->width + 2; urec[count].height = wwin->frame->bottom_width + 1; count++; } /* shape our frame window */ XShapeCombineRectangles(dpy, wwin->frame->core->window, ShapeBounding, 0, wwin->frame->top_width, urec, count, ShapeSet, Unsorted); XFlush(dpy); wfree(urec); return; alt_code: #endif /* OPTIMIZE_SHAPE */ count = 0; if (HAS_TITLEBAR(wwin)) { rect[count].x = -1; rect[count].y = -1; rect[count].width = wwin->frame->core->width + 2; rect[count].height = wwin->frame->top_width + 1; count++; } if (HAS_RESIZEBAR(wwin)) { rect[count].x = -1; rect[count].y = wwin->frame->core->height - wwin->frame->bottom_width; rect[count].width = wwin->frame->core->width + 2; rect[count].height = wwin->frame->bottom_width + 1; count++; } if (count > 0) { XShapeCombineRectangles(dpy, wwin->frame->core->window, ShapeBounding, 0, 0, rect, count, ShapeSet, Unsorted); } XShapeCombineShape(dpy, wwin->frame->core->window, ShapeBounding, 0, wwin->frame->top_width, wwin->client_win, ShapeBounding, (count > 0 ? ShapeUnion : ShapeSet)); XFlush(dpy); } #endif /* USE_XSHAPE */ /* ====================================================================== */ static FocusMode getFocusMode(WWindow * wwin) { FocusMode mode; if ((wwin->wm_hints) && (wwin->wm_hints->flags & InputHint)) { if (wwin->wm_hints->input == True) { if (wwin->protocols.TAKE_FOCUS) mode = WFM_LOCALLY_ACTIVE; else mode = WFM_PASSIVE; } else { if (wwin->protocols.TAKE_FOCUS) mode = WFM_GLOBALLY_ACTIVE; else mode = WFM_NO_INPUT; } } else { mode = WFM_PASSIVE; } return mode; } void wWindowSetKeyGrabs(WWindow * wwin) { int i; WShortKey *key; for (i = 0; i < WKBD_LAST; i++) { key = &wKeyBindings[i]; if (key->keycode == 0) continue; if (key->modifier != AnyModifier) { XGrabKey(dpy, key->keycode, key->modifier | LockMask, wwin->frame->core->window, True, GrabModeAsync, GrabModeAsync); #ifdef NUMLOCK_HACK /* Also grab all modifier combinations possible that include, * LockMask, ScrollLockMask and NumLockMask, so that keygrabs * work even if the NumLock/ScrollLock key is on. */ wHackedGrabKey(key->keycode, key->modifier, wwin->frame->core->window, True, GrabModeAsync, GrabModeAsync); #endif } XGrabKey(dpy, key->keycode, key->modifier, wwin->frame->core->window, True, GrabModeAsync, GrabModeAsync); } wRootMenuBindShortcuts(wwin->frame->core->window); } void wWindowResetMouseGrabs(WWindow * wwin) { /* Mouse grabs can't be done on the client window because of * ICCCM and because clients that try to do the same will crash. * * But there is a problem which makes tbar buttons of unfocused * windows not usable as the click goes to the frame window instead * of the button itself. Must figure a way to fix that. */ XUngrabButton(dpy, AnyButton, AnyModifier, wwin->client_win); if (!WFLAGP(wwin, no_bind_mouse)) { /* grabs for Meta+drag */ wHackedGrabButton(AnyButton, MOD_MASK, wwin->client_win, True, ButtonPressMask | ButtonReleaseMask, GrabModeSync, GrabModeAsync, None, None); /* for CTRL+Wheel to Scroll Horiz, we have to grab CTRL as well * but we only grab it for Button4 and Button 5 since a lot of apps * use CTRL+Button1-3 for app related functionality */ if (wPreferences.resize_increment > 0) { wHackedGrabButton(Button4, ControlMask, wwin->client_win, True, ButtonPressMask | ButtonReleaseMask, GrabModeSync, GrabModeAsync, None, None); wHackedGrabButton(Button5, ControlMask, wwin->client_win, True, ButtonPressMask | ButtonReleaseMask, GrabModeSync, GrabModeAsync, None, None); wHackedGrabButton(Button4, MOD_MASK | ControlMask, wwin->client_win, True, ButtonPressMask | ButtonReleaseMask, GrabModeSync, GrabModeAsync, None, None); wHackedGrabButton(Button5, MOD_MASK | ControlMask, wwin->client_win, True, ButtonPressMask | ButtonReleaseMask, GrabModeSync, GrabModeAsync, None, None); } } if (!wwin->flags.focused && !WFLAGP(wwin, no_focusable) && !wwin->flags.is_gnustep) { /* the passive grabs to focus the window */ /* if (wPreferences.focus_mode == WKF_CLICK) */ XGrabButton(dpy, AnyButton, AnyModifier, wwin->client_win, True, ButtonPressMask | ButtonReleaseMask, GrabModeSync, GrabModeAsync, None, None); } XFlush(dpy); } void wWindowUpdateGNUstepAttr(WWindow * wwin, GNUstepWMAttributes * attr) { if (attr->flags & GSExtraFlagsAttr) { if (MGFLAGP(wwin, broken_close) != (attr->extra_flags & GSDocumentEditedFlag)) { wwin->client_flags.broken_close = !MGFLAGP(wwin, broken_close); wWindowUpdateButtonImages(wwin); } } } WMagicNumber wWindowAddSavedState(const char *instance, const char *class, const char *command, pid_t pid, WSavedState * state) { WWindowState *wstate; wstate = malloc(sizeof(WWindowState)); if (!wstate) return NULL; memset(wstate, 0, sizeof(WWindowState)); wstate->pid = pid; if (instance) wstate->instance = wstrdup(instance); if (class) wstate->class = wstrdup(class); if (command) wstate->command = wstrdup(command); wstate->state = state; wstate->next = windowState; windowState = wstate; return wstate; } static inline int is_same(const char *x, const char *y) { if ((x == NULL) && (y == NULL)) return 1; if ((x == NULL) || (y == NULL)) return 0; if (strcmp(x, y) == 0) return 1; else return 0; } WMagicNumber wWindowGetSavedState(Window win) { char *instance, *class, *command = NULL; WWindowState *wstate = windowState; if (!wstate) return NULL; command = GetCommandForWindow(win); if (!command) return NULL; if (PropGetWMClass(win, &class, &instance)) { while (wstate) { if (is_same(instance, wstate->instance) && is_same(class, wstate->class) && is_same(command, wstate->command)) { break; } wstate = wstate->next; } } else { wstate = NULL; } if (command) wfree(command); if (instance) free(instance); if (class) free(class); return wstate; } void wWindowDeleteSavedState(WMagicNumber id) { WWindowState *tmp, *wstate = (WWindowState *) id; if (!wstate || !windowState) return; tmp = windowState; if (tmp == wstate) { windowState = wstate->next; release_wwindowstate(wstate); } else { while (tmp->next) { if (tmp->next == wstate) { tmp->next = wstate->next; release_wwindowstate(wstate); break; } tmp = tmp->next; } } } void wWindowDeleteSavedStatesForPID(pid_t pid) { WWindowState *tmp, *wstate; if (!windowState) return; tmp = windowState; if (tmp->pid == pid) { wstate = windowState; windowState = tmp->next; release_wwindowstate(wstate); } else { while (tmp->next) { if (tmp->next->pid == pid) { wstate = tmp->next; tmp->next = wstate->next; release_wwindowstate(wstate); break; } tmp = tmp->next; } } } static void release_wwindowstate(WWindowState *wstate) { if (wstate->instance) wfree(wstate->instance); if (wstate->class) wfree(wstate->class); if (wstate->command) wfree(wstate->command); wfree(wstate->state); wfree(wstate); } void wWindowSetOmnipresent(WWindow *wwin, Bool flag) { if (wwin->flags.omnipresent == flag) return; wwin->flags.omnipresent = flag; WMPostNotificationName(WMNChangedState, wwin, "omnipresent"); } static void resizebarMouseDown(WCoreWindow *sender, void *data, XEvent *event) { WWindow *wwin = data; /* Parameter not used, but tell the compiler that it is ok */ (void) sender; #ifndef NUMLOCK_HACK if ((event->xbutton.state & ValidModMask) != (event->xbutton.state & ~LockMask)) { wwarning(_("The NumLock, ScrollLock or similar key seems to be turned on. " "Turn it off or some mouse actions and keyboard shortcuts will not work.")); } #endif event->xbutton.state &= w_global.shortcut.modifiers_mask; CloseWindowMenu(wwin->screen_ptr); if (wPreferences.focus_mode == WKF_CLICK && !(event->xbutton.state & ControlMask) && !WFLAGP(wwin, no_focusable)) { wSetFocusTo(wwin->screen_ptr, wwin); } if (event->xbutton.button == Button1) wRaiseFrame(wwin->frame->core); if (event->xbutton.window != wwin->frame->resizebar->window) { if (XGrabPointer(dpy, wwin->frame->resizebar->window, True, ButtonMotionMask | ButtonReleaseMask | ButtonPressMask, GrabModeAsync, GrabModeAsync, None, None, CurrentTime) != GrabSuccess) { return; } } if (event->xbutton.state & MOD_MASK) { /* move the window */ wMouseMoveWindow(wwin, event); XUngrabPointer(dpy, CurrentTime); } else { wMouseResizeWindow(wwin, event); XUngrabPointer(dpy, CurrentTime); } } static void titlebarDblClick(WCoreWindow *sender, void *data, XEvent *event) { WWindow *wwin = data; /* Parameter not used, but tell the compiler that it is ok */ (void) sender; event->xbutton.state &= w_global.shortcut.modifiers_mask; - if (event->xbutton.button == Button1) { - if (event->xbutton.state == 0) { - if (!WFLAGP(wwin, no_shadeable)) { + if (event->xbutton.button == Button1 ) { + if (event->xbutton.state == 0 ) { + if (!WFLAGP(wwin, no_shadeable) & !wPreferences.double_click_fullscreen) { /* shade window */ if (wwin->flags.shaded) wUnshadeWindow(wwin); else wShadeWindow(wwin); - } + } + } + + if (wPreferences.double_click_fullscreen){ + int dir = 0; + if (event->xbutton.state == 0) { + /* maximize window full screen*/ + dir |= (MAX_VERTICAL|MAX_HORIZONTAL); + int ndir = dir ^ wwin->flags.maximized; + wMaximizeWindow(wwin, ndir, wGetHeadForWindow(wwin)); + + } + + } else { int dir = 0; if (event->xbutton.state & ControlMask) dir |= MAX_VERTICAL; if (event->xbutton.state & ShiftMask) { dir |= MAX_HORIZONTAL; if (!(event->xbutton.state & ControlMask)) wSelectWindow(wwin, !wwin->flags.selected); } /* maximize window */ + if (dir != 0 && IS_RESIZABLE(wwin)) { int ndir = dir ^ wwin->flags.maximized; if (ndir != 0) wMaximizeWindow(wwin, ndir, wGetHeadForWindow(wwin)); else wUnmaximizeWindow(wwin); } } } else if (event->xbutton.button == Button3) { if (event->xbutton.state & MOD_MASK) wHideOtherApplications(wwin); } else if (event->xbutton.button == Button2) { wSelectWindow(wwin, !wwin->flags.selected); } else if (event->xbutton.button == W_getconf_mouseWheelUp()) { wShadeWindow(wwin); } else if (event->xbutton.button == W_getconf_mouseWheelDown()) { wUnshadeWindow(wwin); } } static void frameMouseDown(WObjDescriptor *desc, XEvent *event) { WWindow *wwin = desc->parent; unsigned int new_width, w_scale; unsigned int new_height, h_scale; unsigned int resize_width_increment = 0; unsigned int resize_height_increment = 0; if (wwin->normal_hints) { w_scale = (wPreferences.resize_increment + wwin->normal_hints->width_inc - 1) / wwin->normal_hints->width_inc; h_scale = (wPreferences.resize_increment + wwin->normal_hints->height_inc - 1) / wwin->normal_hints->height_inc; resize_width_increment = wwin->normal_hints->width_inc * w_scale; resize_height_increment = wwin->normal_hints->height_inc * h_scale; } if (resize_width_increment <= 1 && resize_height_increment <= 1) { resize_width_increment = wPreferences.resize_increment; resize_height_increment = wPreferences.resize_increment; } event->xbutton.state &= w_global.shortcut.modifiers_mask; CloseWindowMenu(wwin->screen_ptr); if (!(event->xbutton.state & ControlMask) && !WFLAGP(wwin, no_focusable)) wSetFocusTo(wwin->screen_ptr, wwin); if (event->xbutton.button == Button1) wRaiseFrame(wwin->frame->core); if (event->xbutton.state & ControlMask) { if (event->xbutton.button == Button4) { new_width = wwin->client.width - resize_width_increment; wWindowConstrainSize(wwin, &new_width, &wwin->client.height); wWindowConfigure(wwin, wwin->frame_x, wwin->frame_y, new_width, wwin->client.height); } if (event->xbutton.button == Button5) { new_width = wwin->client.width + resize_width_increment; wWindowConstrainSize(wwin, &new_width, &wwin->client.height); wWindowConfigure(wwin, wwin->frame_x, wwin->frame_y, new_width, wwin->client.height); } } if (event->xbutton.state & MOD_MASK) { /* move the window */ if (XGrabPointer(dpy, wwin->client_win, False, ButtonMotionMask | ButtonReleaseMask | ButtonPressMask, GrabModeAsync, GrabModeAsync, None, None, CurrentTime) != GrabSuccess) { return; } if (event->xbutton.button == Button3) { wMouseResizeWindow(wwin, event); } else if (event->xbutton.button == Button4) { new_height = wwin->client.height - resize_height_increment; wWindowConstrainSize(wwin, &wwin->client.width, &new_height); wWindowConfigure(wwin, wwin->frame_x, wwin->frame_y, wwin->client.width, new_height); } else if (event->xbutton.button == Button5) { new_height = wwin->client.height + resize_height_increment; wWindowConstrainSize(wwin, &wwin->client.width, &new_height); wWindowConfigure(wwin, wwin->frame_x, wwin->frame_y, wwin->client.width, new_height); } else if (event->xbutton.button == Button1 || event->xbutton.button == Button2) { wMouseMoveWindow(wwin, event); } XUngrabPointer(dpy, CurrentTime); } } static void titlebarMouseDown(WCoreWindow *sender, void *data, XEvent *event) { WWindow *wwin = (WWindow *) data; /* Parameter not used, but tell the compiler that it is ok */ (void) sender; #ifndef NUMLOCK_HACK if ((event->xbutton.state & ValidModMask) != (event->xbutton.state & ~LockMask)) wwarning(_("The NumLock, ScrollLock or similar key seems to be turned on. " "Turn it off or some mouse actions and keyboard shortcuts will not work.")); #endif event->xbutton.state &= w_global.shortcut.modifiers_mask; CloseWindowMenu(wwin->screen_ptr); if (wPreferences.focus_mode == WKF_CLICK && !(event->xbutton.state & ControlMask) && !WFLAGP(wwin, no_focusable)) wSetFocusTo(wwin->screen_ptr, wwin); if (event->xbutton.button == Button1 || event->xbutton.button == Button2) { if (event->xbutton.button == Button1) { if (event->xbutton.state & MOD_MASK) wLowerFrame(wwin->frame->core); else wRaiseFrame(wwin->frame->core); } if ((event->xbutton.state & ShiftMask) && !(event->xbutton.state & ControlMask)) { wSelectWindow(wwin, !wwin->flags.selected); return; } if (event->xbutton.window != wwin->frame->titlebar->window && XGrabPointer(dpy, wwin->frame->titlebar->window, False, ButtonMotionMask | ButtonReleaseMask | ButtonPressMask, GrabModeAsync, GrabModeAsync, None, None, CurrentTime) != GrabSuccess) { return; } /* move the window */ wMouseMoveWindow(wwin, event); XUngrabPointer(dpy, CurrentTime); } else if (event->xbutton.button == Button3 && event->xbutton.state == 0 && !wwin->flags.internal_window && !WCHECK_STATE(WSTATE_MODAL)) { WObjDescriptor *desc; if (event->xbutton.window != wwin->frame->titlebar->window && XGrabPointer(dpy, wwin->frame->titlebar->window, False, ButtonMotionMask | ButtonReleaseMask | ButtonPressMask, GrabModeAsync, GrabModeAsync, None, None, CurrentTime) != GrabSuccess) { return; } OpenWindowMenu(wwin, event->xbutton.x_root, wwin->frame_y + wwin->frame->top_width, False); /* allow drag select */ desc = &wwin->screen_ptr->window_menu->menu->descriptor; event->xany.send_event = True; (*desc->handle_mousedown) (desc, event); XUngrabPointer(dpy, CurrentTime); } } static void windowCloseClick(WCoreWindow *sender, void *data, XEvent *event) { WWindow *wwin = data; /* Parameter not used, but tell the compiler that it is ok */ (void) sender; event->xbutton.state &= w_global.shortcut.modifiers_mask; CloseWindowMenu(wwin->screen_ptr); if (event->xbutton.button < Button1 || event->xbutton.button > Button3) return; /* if control-click, kill the client */ if (event->xbutton.state & ControlMask) { wClientKill(wwin); } else { if (wwin->protocols.DELETE_WINDOW && event->xbutton.state == 0) { /* send delete message */ wClientSendProtocol(wwin, w_global.atom.wm.delete_window, w_global.timestamp.last_event); } } } static void windowCloseDblClick(WCoreWindow *sender, void *data, XEvent *event) { WWindow *wwin = data; /* Parameter not used, but tell the compiler that it is ok */ (void) sender; CloseWindowMenu(wwin->screen_ptr); if (event->xbutton.button < Button1 || event->xbutton.button > Button3) return; /* send delete message */ if (wwin->protocols.DELETE_WINDOW) wClientSendProtocol(wwin, w_global.atom.wm.delete_window, w_global.timestamp.last_event); else wClientKill(wwin); } #ifdef XKB_BUTTON_HINT static void windowLanguageClick(WCoreWindow *sender, void *data, XEvent *event) { WWindow *wwin = data; WFrameWindow *fwin = wwin->frame; WScreen *scr = fwin->screen_ptr; int tl; /* Parameter not used, but tell the compiler that it is ok */ (void) sender; if (event->xbutton.button != Button1 && event->xbutton.button != Button3) return; tl = wwin->frame->languagemode; wwin->frame->languagemode = wwin->frame->last_languagemode; wwin->frame->last_languagemode = tl; wSetFocusTo(scr, wwin); wwin->frame->languagebutton_image = wwin->frame->screen_ptr->b_pixmaps[WBUT_XKBGROUP1 + wwin->frame->languagemode]; wFrameWindowUpdateLanguageButton(wwin->frame); if (event->xbutton.button == Button3) return; wRaiseFrame(fwin->core); } #endif static void windowIconifyClick(WCoreWindow *sender, void *data, XEvent *event) { WWindow *wwin = data; /* Parameter not used, but tell the compiler that it is ok */ (void) sender; event->xbutton.state &= w_global.shortcut.modifiers_mask; CloseWindowMenu(wwin->screen_ptr); if (event->xbutton.button < Button1 || event->xbutton.button > Button3) return; if (wwin->protocols.MINIATURIZE_WINDOW && event->xbutton.state == 0) { wClientSendProtocol(wwin, w_global.atom.gnustep.wm_miniaturize_window, w_global.timestamp.last_event); } else { WApplication *wapp; if ((event->xbutton.state & ControlMask) || (event->xbutton.button == Button3)) { wapp = wApplicationOf(wwin->main_window); if (wapp && !WFLAGP(wwin, no_appicon)) wHideApplication(wapp); } else if (event->xbutton.state == 0) { wIconifyWindow(wwin); } } }
roblillack/wmaker
5d2fd7bf7eb652498943279a1c05193f4d203f7a
WPrefs: Create Turkish translation
diff --git a/WPrefs.app/po/Makefile.am b/WPrefs.app/po/Makefile.am index c2363e9..860c605 100644 --- a/WPrefs.app/po/Makefile.am +++ b/WPrefs.app/po/Makefile.am @@ -1,91 +1,91 @@ DOMAIN = WPrefs CATALOGS = @WPREFSMOFILES@ CLEANFILES = $(DOMAIN).pot $(CATALOGS) EXTRA_DIST = bg.po ca.po cs.po de.po es.po et.po fi.po fr.po fy.po hr.po hu.po \ - it.po ja.po ko.po nl.po pt.po ru.po sk.po uk.po zh_CN.po zh_TW.po + it.po ja.po ko.po nl.po pt.po ru.po sk.po tr.po uk.po zh_CN.po zh_TW.po POTFILES = \ $(top_srcdir)/WPrefs.app/Appearance.c \ $(top_srcdir)/WPrefs.app/Configurations.c \ $(top_srcdir)/WPrefs.app/Docks.c \ $(top_srcdir)/WPrefs.app/Expert.c \ $(top_srcdir)/WPrefs.app/Focus.c \ $(top_srcdir)/WPrefs.app/FontSimple.c \ $(top_srcdir)/WPrefs.app/Icons.c \ $(top_srcdir)/WPrefs.app/KeyboardShortcuts.c \ $(top_srcdir)/WPrefs.app/Menu.c \ $(top_srcdir)/WPrefs.app/MenuPreferences.c \ $(top_srcdir)/WPrefs.app/MouseSettings.c \ $(top_srcdir)/WPrefs.app/Paths.c \ $(top_srcdir)/WPrefs.app/Preferences.c \ $(top_srcdir)/WPrefs.app/TexturePanel.c \ $(top_srcdir)/WPrefs.app/WPrefs.c \ $(top_srcdir)/WPrefs.app/WindowHandling.c \ $(top_srcdir)/WPrefs.app/Workspace.c \ $(top_srcdir)/WPrefs.app/double.c \ $(top_srcdir)/WPrefs.app/editmenu.c \ $(top_srcdir)/WPrefs.app/main.c \ $(top_srcdir)/WPrefs.app/xmodifier.c # not_yet_fully_implemented # $(top_srcdir)/WPrefs.app/KeyboardSettings.c \ # $(top_srcdir)/WPrefs.app/Themes.c \ # SUFFIXES = .po .mo .po.mo: $(AM_V_GEN)$(MSGFMT) -c -o $@ $< all-local: $(CATALOGS) .PHONY: update-lang if HAVE_XGETTEXT update-lang: $(DOMAIN).pot $(AM_V_GEN)$(top_srcdir)/script/generate-po-from-template.sh \ -n "$(PACKAGE_NAME)" -v "$(PACKAGE_VERSION)" -b "$(PACKAGE_BUGREPORT)" \ -t "$(DOMAIN).pot" "$(srcdir)/$(PO).po" $(DOMAIN).pot: $(POTFILES) $(AM_V_GEN)$(XGETTEXT) --default-domain=$(DOMAIN) \ --add-comments --keyword=_ --keyword=N_ $(POTFILES) @if cmp -s $(DOMAIN).po $(DOMAIN).pot; then \ rm -f $(DOMAIN).po; \ else \ mv -f $(DOMAIN).po $(DOMAIN).pot; \ fi endif install-data-local: $(CATALOGS) $(mkinstalldirs) $(DESTDIR)$(localedir) for n in $(CATALOGS) __DuMmY ; do \ if test "$$n" -a "$$n" != "__DuMmY" ; then \ l=`basename $$n .mo`; \ $(mkinstalldirs) $(DESTDIR)$(localedir)/$$l/LC_MESSAGES; \ $(INSTALL_DATA) -m 644 $$n $(DESTDIR)$(localedir)/$$l/LC_MESSAGES/$(DOMAIN).mo; \ fi; \ done uninstall-local: for n in $(CATALOGS) ; do \ l=`basename $$n .mo`; \ rm -f $(DESTDIR)$(localedir)/$$l/LC_MESSAGES/$(DOMAIN).mo; \ done # Create a 'silent rule' for our make check the same way automake does AM_V_CHKTRANS = $(am__v_CHKTRANS_$(V)) am__v_CHKTRANS_ = $(am__v_CHKTRANS_$(AM_DEFAULT_VERBOSITY)) am__v_CHKTRANS_0 = @echo " CHK translations" ; am__v_CHKTRANS_1 = # 'make check' will make sure the tranlation sources are in line with the compiled source check-local: $(AM_V_CHKTRANS)$(top_srcdir)/script/check-translation-sources.sh \ "$(srcdir)" -s "$(top_srcdir)/WPrefs.app/Makefile.am" diff --git a/WPrefs.app/po/tr.po b/WPrefs.app/po/tr.po new file mode 100644 index 0000000..88b6c6e --- /dev/null +++ b/WPrefs.app/po/tr.po @@ -0,0 +1,2627 @@ +# Copyright (C) 2020 The Window Maker Team +# This file is distributed under the same license as the Window Maker package. +# +msgid "" +msgstr "" +"Project-Id-Version: WindowMaker 0.95.9\n" +"Report-Msgid-Bugs-To: [email protected]\n" +"POT-Creation-Date: 2020-06-20 13:50+0200\n" +"PO-Revision-Date: 2020-06-28 07:47+0000\n" +"Last-Translator: XOR <[email protected]>\n" +"Language-Team: Turkish\n" +"Language: tr\n" +"MIME-Version: 1.0\n" +"Content-Type: text/plain; charset=UTF-8\n" +"Content-Transfer-Encoding: 8bit\n" + +#. Related to Window titles +#: ../../WPrefs.app/Appearance.c:44 +msgid "Focused Window Title" +msgstr "Odaklanmış Pencere Başlığı" + +#: ../../WPrefs.app/Appearance.c:46 +msgid "Unfocused Window Title" +msgstr "Odaklanmamış Pencere Başlığı" + +#: ../../WPrefs.app/Appearance.c:48 +msgid "Owner of Focused Window Title" +msgstr "Odaklanmış Pencere Başlığının Sahibi" + +#. Related to Menus +#: ../../WPrefs.app/Appearance.c:52 ../../WPrefs.app/Appearance.c:1504 +#: ../../WPrefs.app/FontSimple.c:100 +msgid "Menu Title" +msgstr "Menü Başlığı" + +#: ../../WPrefs.app/Appearance.c:54 +msgid "Menu Item Text" +msgstr "Menü Öğesi Metni" + +#: ../../WPrefs.app/Appearance.c:56 +msgid "Disabled Menu Item Text" +msgstr "Devre Dışı Menü Öğesi Metni" + +#: ../../WPrefs.app/Appearance.c:58 +msgid "Menu Highlight Color" +msgstr "Menü Vurgu Rengi" + +#: ../../WPrefs.app/Appearance.c:60 +msgid "Highlighted Menu Text Color" +msgstr "Vurgulanan Menü Metin Rengi" + +#. +#. * yuck kluge: the coordinate for HighlightTextColor are actually those of the last "Normal item" +#. * at the bottom when user clicks it, the "yuck kluge" in the function 'previewClick' will swap it +#. * for the MenuTextColor selection as user would expect +#. * +#. * Note that the entries are reffered by their index for performance +#. +#. Related to Window's border +#: ../../WPrefs.app/Appearance.c:71 +msgid "Focused Window Border Color" +msgstr "Odaklanmış Pencere Kenarlığı Rengi" + +#: ../../WPrefs.app/Appearance.c:73 +msgid "Window Border Color" +msgstr "Pencere Kenarlığı Rengi" + +#: ../../WPrefs.app/Appearance.c:75 +msgid "Selected Window Border Color" +msgstr "Seçili Pencere Kenarlığı Rengi" + +#. Related to Icons and Clip +#: ../../WPrefs.app/Appearance.c:79 +msgid "Miniwindow Title" +msgstr "Miniwindow Başlığı" + +#: ../../WPrefs.app/Appearance.c:81 +msgid "Miniwindow Title Back" +msgstr "Miniwindow Başlığı Geri" + +#: ../../WPrefs.app/Appearance.c:83 ../../WPrefs.app/FontSimple.c:103 +msgid "Clip Title" +msgstr "Klip Başlığı" + +#: ../../WPrefs.app/Appearance.c:85 +msgid "Collapsed Clip Title" +msgstr "Daraltılmış Klip Başlığı" + +#: ../../WPrefs.app/Appearance.c:110 +msgid "Left" +msgstr "Sol" + +#: ../../WPrefs.app/Appearance.c:111 ../../WPrefs.app/TexturePanel.c:1407 +#: ../../WPrefs.app/WindowHandling.c:93 ../../WPrefs.app/Workspace.c:189 +msgid "Center" +msgstr "Merkez" + +#: ../../WPrefs.app/Appearance.c:112 +msgid "Right" +msgstr "Sağ" + +#: ../../WPrefs.app/Appearance.c:382 +msgid "[Focused]" +msgstr "[Odaklanmış]" + +#: ../../WPrefs.app/Appearance.c:383 +msgid "Titlebar of Focused Window" +msgstr "Odaklanmış Pencerenin Başlık Çubuğu" + +#: ../../WPrefs.app/Appearance.c:386 +msgid "[Unfocused]" +msgstr "[Odaklanmamış]" + +#: ../../WPrefs.app/Appearance.c:387 +msgid "Titlebar of Unfocused Windows" +msgstr "Odaklanmamış Windows'un Başlık Çubuğu" + +#: ../../WPrefs.app/Appearance.c:390 +msgid "[Owner of Focused]" +msgstr "[Odaklanmışın Sahibi]" + +#: ../../WPrefs.app/Appearance.c:391 +msgid "Titlebar of Focused Window's Owner" +msgstr "Odaklanmış Pencerenin Sahibinin Başlık Çubuğu" + +#: ../../WPrefs.app/Appearance.c:394 +msgid "[Resizebar]" +msgstr "[Resizebar]" + +#: ../../WPrefs.app/Appearance.c:395 +msgid "Window Resizebar" +msgstr "Pencere Resizebar" + +#: ../../WPrefs.app/Appearance.c:398 +msgid "[Menu Title]" +msgstr "[Menü Başlığı]" + +#: ../../WPrefs.app/Appearance.c:399 +msgid "Titlebar of Menus" +msgstr "Menülerin Başlık Çubuğu" + +#: ../../WPrefs.app/Appearance.c:402 +msgid "[Menu Item]" +msgstr "[Menü Öğesi]" + +#: ../../WPrefs.app/Appearance.c:403 +msgid "Menu Items" +msgstr "Menü Öğeleri" + +#: ../../WPrefs.app/Appearance.c:406 +msgid "[Icon]" +msgstr "[Simge]" + +#: ../../WPrefs.app/Appearance.c:407 +msgid "Icon Background" +msgstr "Simge Arkaplan" + +#: ../../WPrefs.app/Appearance.c:410 +msgid "[Background]" +msgstr "[Arka plan]" + +#: ../../WPrefs.app/Appearance.c:411 +msgid "Workspace Background" +msgstr "Çalışma Alanı Arkaplanı" + +#: ../../WPrefs.app/Appearance.c:562 ../../WPrefs.app/TexturePanel.c:880 +#, c-format +msgid "could not load file '%s': %s" +msgstr "'%s' dosyası yüklenemedi: %s" + +#: ../../WPrefs.app/Appearance.c:565 +#, c-format +msgid "could not find file '%s' for texture type %s" +msgstr "%s doku tipi için '%s' dosyası bulunamadı" + +#: ../../WPrefs.app/Appearance.c:613 ../../WPrefs.app/Appearance.c:640 +#: ../../WPrefs.app/Appearance.c:675 +#, c-format +msgid "unknown direction in '%s', falling back to diagonal" +msgstr "'%s' de bilinmeyen yön, diyagonal geri düşüyor" + +#: ../../WPrefs.app/Appearance.c:723 +#, c-format +msgid "type '%s' is not a supported type for a texture" +msgstr "'%s' türü bir doku için desteklenen bir tür değil" + +#: ../../WPrefs.app/Appearance.c:1091 +#, c-format +msgid "could not remove file %s" +msgstr "%s dosyası silinemedi" + +#: ../../WPrefs.app/Appearance.c:1113 +msgid "Select File" +msgstr "Dosya Seç" + +#: ../../WPrefs.app/Appearance.c:1316 +#, c-format +msgid "could not read size of image from '%s', ignoring" +msgstr "'%s' öğesinden resim boyutu okunamadı, yok sayılıyor" + +#: ../../WPrefs.app/Appearance.c:1321 +#, c-format +msgid "image \"%s\" has an invalid depth of %d, ignoring" +msgstr "image \"%s\" geçersiz bir %d derinliğe sahip, yoksayılıyor" + +#: ../../WPrefs.app/Appearance.c:1327 +#, c-format +msgid "could not create RImage for \"%s\": %s" +msgstr "\"%s\" için RImage oluşturulamadı: %s" + +#: ../../WPrefs.app/Appearance.c:1484 +msgid "Focused Window" +msgstr "Odaklanmış Pencere" + +#: ../../WPrefs.app/Appearance.c:1491 +msgid "Unfocused Window" +msgstr "Odaklanmamış Pencere" + +#: ../../WPrefs.app/Appearance.c:1498 +msgid "Owner of Focused Window" +msgstr "Odaklanmış Pencerenin Sahibi" + +#: ../../WPrefs.app/Appearance.c:1510 ../../WPrefs.app/Appearance.c:1514 +msgid "Normal Item" +msgstr "Normal Öğe" + +#: ../../WPrefs.app/Appearance.c:1520 +msgid "Disabled Item" +msgstr "Devre dışı bırakılmış öğe" + +#: ../../WPrefs.app/Appearance.c:1535 +msgid "Highlighted" +msgstr "Vurgulanan" + +#: ../../WPrefs.app/Appearance.c:1628 +msgid "Icon Text" +msgstr "Simge Metni" + +#: ../../WPrefs.app/Appearance.c:1712 ../../WPrefs.app/Appearance.c:1719 +msgid "Clip" +msgstr "Klip" + +#: ../../WPrefs.app/Appearance.c:1716 +msgid "Coll." +msgstr "" + +#: ../../WPrefs.app/Appearance.c:1880 +msgid "Texture" +msgstr "Doku" + +#: ../../WPrefs.app/Appearance.c:1903 +msgid "" +"Double click in the texture you want to use\n" +"for the selected item." +msgstr "Seçilen öğe için kullanmak istediğiniz dokuya çift tıklayın." + +#: ../../WPrefs.app/Appearance.c:1915 +msgid "New" +msgstr "Yeni" + +#: ../../WPrefs.app/Appearance.c:1919 +msgid "Create a new texture." +msgstr "Yeni bir doku oluştur." + +#: ../../WPrefs.app/Appearance.c:1926 +msgid "Extract..." +msgstr "Ayıkla ..." + +#: ../../WPrefs.app/Appearance.c:1930 +msgid "Extract texture(s) from a theme or a style file." +msgstr "Bir tema veya stil dosyasından doku (ları) ayıklayın." + +#: ../../WPrefs.app/Appearance.c:1939 +msgid "Edit" +msgstr "Düzenle" + +#: ../../WPrefs.app/Appearance.c:1942 +msgid "Edit the highlighted texture." +msgstr "Vurgulanan dokuyu düzenleyin." + +#: ../../WPrefs.app/Appearance.c:1949 ../../WPrefs.app/TexturePanel.c:1218 +msgid "Delete" +msgstr "Sil" + +#: ../../WPrefs.app/Appearance.c:1953 +msgid "Delete the highlighted texture." +msgstr "Vurgulanan dokuyu sil." + +#: ../../WPrefs.app/Appearance.c:1965 +msgid "Color" +msgstr "Renk" + +#: ../../WPrefs.app/Appearance.c:2021 +msgid "Options" +msgstr "Seçenekler" + +#: ../../WPrefs.app/Appearance.c:2028 +msgid "Menu Style" +msgstr "Menü Stili" + +#: ../../WPrefs.app/Appearance.c:2046 ../../WPrefs.app/Configurations.c:179 +#: ../../WPrefs.app/Configurations.c:191 ../../WPrefs.app/Docks.c:212 +#: ../../WPrefs.app/Docks.c:220 ../../WPrefs.app/Focus.c:279 +#: ../../WPrefs.app/Focus.c:290 ../../WPrefs.app/MenuPreferences.c:127 +#: ../../WPrefs.app/MenuPreferences.c:138 +#: ../../WPrefs.app/MenuPreferences.c:166 +#: ../../WPrefs.app/MenuPreferences.c:181 ../../WPrefs.app/MouseSettings.c:554 +#: ../../WPrefs.app/MouseSettings.c:565 ../../WPrefs.app/WPrefs.c:459 +#: ../../WPrefs.app/WPrefs.c:473 +#, c-format +msgid "could not load icon file %s" +msgstr "%s simge dosyası yüklenemedi" + +#: ../../WPrefs.app/Appearance.c:2059 +msgid "Title Alignment" +msgstr "Başlık Hizalama" + +#: ../../WPrefs.app/Appearance.c:2257 +msgid "Appearance Preferences" +msgstr "Görünüm Tercihleri" + +#: ../../WPrefs.app/Appearance.c:2259 +msgid "" +"Background texture configuration for windows,\n" +"menus and icons." +msgstr "" +"Windows, menüler ve simgeler için arka plan doku yapılandırması." + +#: ../../WPrefs.app/Appearance.c:2295 +msgid "Extract Texture" +msgstr "Doku Çıkar" + +#: ../../WPrefs.app/Appearance.c:2315 +msgid "Textures" +msgstr "Dokular" + +#: ../../WPrefs.app/Appearance.c:2324 ../../WPrefs.app/WPrefs.c:253 +msgid "Close" +msgstr "Kapat" + +#: ../../WPrefs.app/Appearance.c:2329 +msgid "Extract" +msgstr "Ayıkla" + +#: ../../WPrefs.app/Configurations.c:130 ../../WPrefs.app/Docks.c:170 +#: ../../WPrefs.app/Workspace.c:106 +#, c-format +msgid "could not load image file %s" +msgstr "%s resim dosyası yüklenemedi" + +#: ../../WPrefs.app/Configurations.c:141 +msgid "Icon Slide Speed" +msgstr "Simge Slayt Hızı" + +#: ../../WPrefs.app/Configurations.c:147 +msgid "Shade Animation Speed" +msgstr "Gölge Animasyon Hızı" + +#: ../../WPrefs.app/Configurations.c:206 +msgid "Smooth Scaling" +msgstr "Düzgün Ölçekleme" + +#: ../../WPrefs.app/Configurations.c:237 +msgid "" +"Smooth scaled background images, neutralizing\n" +"the `pixelization' effect. This will slow\n" +"down loading of background images considerably." +msgstr "" +"Pikselleştirme efektini nötralize eden pürüzsüz ölçekli arka plan resimleri.\n" +"Bu, arka plan görüntülerinin yüklenmesini önemli ölçüde yavaşlatır." + +#: ../../WPrefs.app/Configurations.c:247 +msgid "Titlebar Style" +msgstr "Başlık Çubuğu Stili" + +#: ../../WPrefs.app/Configurations.c:300 ../../WPrefs.app/Configurations.c:306 +msgid "Animations" +msgstr "Animasyonlar" + +#: ../../WPrefs.app/Configurations.c:317 +msgid "" +"Disable/enable animations such as those shown\n" +"for window miniaturization, shading etc." +msgstr "" +"Pencere minyatürleştirme, gölgeleme vb. Gibi animasyonları devre dışı " +"bırakın / etkinleştirin." + +#: ../../WPrefs.app/Configurations.c:324 +msgid "Superfluous" +msgstr "Gereksiz" + +#: ../../WPrefs.app/Configurations.c:335 +msgid "" +"Disable/enable `superfluous' features and\n" +"animations. These include the `ghosting' of the\n" +"dock when it's being moved to another side and\n" +"the explosion animation when undocking icons." +msgstr "" +"`` Gereksiz '' özellikleri ve animasyonları devre dışı bırakın / " +"etkinleştirin. Bunlar, başka bir tarafa taşınırken rıhtımın `` " +"gölgelenmesini '' ve simgeleri geri alırken patlama animasyonunu içerir." + +#: ../../WPrefs.app/Configurations.c:348 +msgid "Dithering colormap for 8bpp" +msgstr "8bpp için renk taklidi renk taklidi" + +#: ../../WPrefs.app/Configurations.c:350 +msgid "" +"Number of colors to reserve for Window Maker\n" +"on displays that support only 8bpp (PseudoColor)." +msgstr "" +"Yalnızca 8bpp (PseudoColor) destekleyen ekranlarda Window Maker için " +"ayrılacak renk sayısı." + +#: ../../WPrefs.app/Configurations.c:357 +msgid "Disable dithering in any visual/depth" +msgstr "Herhangi bir görsel / derinlikte titremeyi devre dışı bırak" + +#: ../../WPrefs.app/Configurations.c:378 +msgid "" +"More colors for\n" +"applications" +msgstr "Uygulamalar için daha fazla renk" + +#: ../../WPrefs.app/Configurations.c:385 +msgid "" +"More colors for\n" +"Window Maker" +msgstr "Window Maker için daha fazla renk" + +#: ../../WPrefs.app/Configurations.c:434 +msgid "Other Configurations" +msgstr "Diğer Konfigürasyonlar" + +#: ../../WPrefs.app/Configurations.c:435 +msgid "" +"Animation speeds, titlebar styles, various option\n" +"toggling and number of colors to reserve for\n" +"Window Maker on 8bit displays." +msgstr "" +"Animasyon hızları, başlık çubuğu stilleri, çeşitli seçenek geçişleri ve 8 " +"bitlik ekranlarda Window Maker için ayrılacak renk sayısı." + +#: ../../WPrefs.app/Docks.c:26 +msgid "Clip autocollapsing delays" +msgstr "Klip otomatik çakıştırma gecikmeleri" + +#: ../../WPrefs.app/Docks.c:27 +msgid "Clip autoraising delays" +msgstr "Klip otomatikleştirme gecikmeleri" + +#: ../../WPrefs.app/Docks.c:34 +msgid "Before auto-expansion" +msgstr "Otomatik genişletmeden önce" + +#: ../../WPrefs.app/Docks.c:35 +msgid "Before auto-collapsing" +msgstr "Otomatik daralmadan önce" + +#: ../../WPrefs.app/Docks.c:36 +msgid "Before auto-raising" +msgstr "Otomatik kaldırmadan önce" + +#: ../../WPrefs.app/Docks.c:37 +msgid "Before auto-lowering" +msgstr "Otomatik indirme öncesi" + +#: ../../WPrefs.app/Docks.c:48 +msgid "" +"Disable/enable the application Dock (the\n" +"vertical icon bar in the side of the screen)." +msgstr "" +"Uygulama Yuvasını devre dışı bırakın / etkinleştirin (ekranın yan " +"tarafındaki dikey simge çubuğu)." + +#: ../../WPrefs.app/Docks.c:50 +msgid "" +"Disable/enable the Clip (that thing with\n" +"a paper clip icon)." +msgstr "Klibi devre dışı bırakma / etkinleştirme (ataş simgesiyle bu şey)." + +#: ../../WPrefs.app/Docks.c:52 +msgid "" +"Disable/enable Drawers (a dock that stores\n" +"application icons horizontally). The dock is required." +msgstr "" +"Çekmeceleri devre dışı bırakma / etkinleştirme (uygulama simgelerini yatay " +"olarak saklayan bir yuva). Yuva gereklidir." + +#: ../../WPrefs.app/Docks.c:234 ../../WPrefs.app/Focus.c:309 +#: ../../WPrefs.app/MouseSettings.c:595 +msgid "ms" +msgstr "" + +#: ../../WPrefs.app/Docks.c:250 +msgid "Dock/Clip/Drawer" +msgstr "Dock/Klip/Çekmece (Dock/Clip/Drawer)" + +#: ../../WPrefs.app/Docks.c:322 +msgid "Dock Preferences" +msgstr "Dock Tercihleri" + +#: ../../WPrefs.app/Docks.c:324 +msgid "" +"Dock and clip features.\n" +"Enable/disable the Dock and Clip, and tune some delays." +msgstr "" +"Yuva ve klips özellikleri. Dock ve Clip'i etkinleştirin / devre dışı bırakın " +"ve bazı gecikmeleri ayarlayın." + +#: ../../WPrefs.app/Expert.c:44 +msgid "" +"Disable miniwindows (icons for minimized windows). For use with KDE/GNOME." +msgstr "" +"Mini pencereleri devre dışı bırakın (simge durumuna küçültülmüş pencereler " +"için simgeler). KDE / GNOME ile kullanım için." + +#. default: +#: ../../WPrefs.app/Expert.c:47 +msgid "Ignore decoration hints for GTK applications." +msgstr "GTK uygulamaları için dekorasyon ipuçlarını yoksay." + +#. default: +#: ../../WPrefs.app/Expert.c:50 +msgid "Enable workspace pager." +msgstr "Çalışma alanı çağrı cihazını etkinleştir." + +#. default: +#: ../../WPrefs.app/Expert.c:53 +msgid "Do not set non-WindowMaker specific parameters (do not use xset)." +msgstr "" +"WindowMaker'a özgü olmayan parametreler ayarlamayın (xset kullanmayın)." + +#. default: +#: ../../WPrefs.app/Expert.c:56 +msgid "Automatically save session when exiting Window Maker." +msgstr "Window Maker'dan çıkarken oturumu otomatik olarak kaydet." + +#. default: +#: ../../WPrefs.app/Expert.c:59 +msgid "Use SaveUnder in window frames, icons, menus and other objects." +msgstr "" +"SaveUnder'i pencere çerçeveleri, simgeler, menüler ve diğer nesnelerde " +"kullanın." + +#. default: +#: ../../WPrefs.app/Expert.c:62 +msgid "Disable confirmation panel for the Kill command." +msgstr "Kill (sonlandırma) komutu için onay panelini devre dışı bırak." + +#. default: +#: ../../WPrefs.app/Expert.c:65 +msgid "Disable selection animation for selected icons." +msgstr "Seçili simgeler için seçim animasyonunu devre dışı bırak." + +#. default: +#: ../../WPrefs.app/Expert.c:68 +msgid "Smooth font edges (needs restart)." +msgstr "Pürüzsüz yazı tipi kenarları (yeniden başlatılması gerekiyor)." + +#. default: +#: ../../WPrefs.app/Expert.c:71 +msgid "Cycle windows only on the active head." +msgstr "Pencereleri sadece aktif kafada dolaş." + +#. default: +#: ../../WPrefs.app/Expert.c:74 +msgid "Ignore minimized windows when cycling." +msgstr "Bisiklet sürerken simge durumuna küçültülmüş pencereleri yoksay." + +#. default: +#: ../../WPrefs.app/Expert.c:77 +msgid "Show switch panel when cycling windows." +msgstr "Pencereleri çevirirken anahtar panelini göster." + +#. default: +#: ../../WPrefs.app/Expert.c:80 +msgid "Show workspace title on Clip." +msgstr "Klipte çalışma alanı başlığını göster." + +#. default: +#: ../../WPrefs.app/Expert.c:83 +msgid "Highlight the icon of the application when it has the focus." +msgstr "Odak olduğunda uygulamanın simgesini vurgula." + +#: ../../WPrefs.app/Expert.c:87 +msgid "Enable keyboard language switch button in window titlebars." +msgstr "Pencere başlık çubuklarında klavye dili geçiş düğmesini etkinleştir." + +#: ../../WPrefs.app/Expert.c:91 +msgid "Maximize (snap) a window to edge or corner by dragging." +msgstr "" +"Bir pencereyi sürükleyerek kenarına veya köşesine büyütme (yapıştırma)." + +#. default: +#: ../../WPrefs.app/Expert.c:94 +msgid "Distance from edge to begin window snap." +msgstr "Pencere kenetlemeye başlamak için kenardan uzaklık." + +#. default: +#: ../../WPrefs.app/Expert.c:97 +msgid "Distance from corner to begin window snap." +msgstr "Pencere yapışmasına başlamak için köşeden uzaklık." + +#. default: +#: ../../WPrefs.app/Expert.c:100 +msgid "Snapping a window to the top maximizes it to the full screen." +msgstr "Bir pencereyi en üste yapıştırmak onu tam ekrana büyütür." + +#. default: +#: ../../WPrefs.app/Expert.c:103 +msgid "Allow move half-maximized windows between multiple screens." +msgstr "" +"Birden çok ekran arasında yarı büyütülmüş pencerelerin taşınmasına izin ver." + +#. default: +#: ../../WPrefs.app/Expert.c:106 +msgid "Alternative transitions between states for half maximized windows." +msgstr "Yarı büyütülmüş pencereler için durumlar arasında alternatif geçişler." + +#. default: +#: ../../WPrefs.app/Expert.c:109 +msgid "Move mouse pointer with half maximized windows." +msgstr "Fare işaretçisini yarı büyütülmüş pencerelerle taşı." + +#. default: +#: ../../WPrefs.app/Expert.c:112 +msgid "Open dialogs in the same workspace as their owners." +msgstr "Diyalogları sahipleriyle aynı çalışma alanında aç." + +#. default: +#: ../../WPrefs.app/Expert.c:115 +msgid "Wrap dock-attached icons around the screen edges." +msgstr "Dock-ekli simgeleri ekran kenarlarına sarın." + +#: ../../WPrefs.app/Expert.c:325 +msgid "Expert User Preferences" +msgstr "Uzman Kullanıcı Tercihleri" + +#: ../../WPrefs.app/Expert.c:327 +msgid "" +"Options for people who know what they're doing...\n" +"Also has some other misc. options." +msgstr "" +"Ne yaptıklarını bilenler için seçenekler ... Ayrıca başka çeşitli var. " +"seçenekler." + +#: ../../WPrefs.app/Focus.c:75 +#, c-format +msgid "bad option value %s for option FocusMode. Using default Manual" +msgstr "" +"FocusMode seçeneği için %s hatalı seçenek değeri. Varsayılan Manuel'i " +"kullanma" + +#: ../../WPrefs.app/Focus.c:87 +#, c-format +msgid "bad option value %s for option ColormapMode. Using default Auto" +msgstr "" +"ColormapMode seçeneği için %s hatalı seçenek değeri. Varsayılan Otomatik " +"kullanımı" + +#: ../../WPrefs.app/Focus.c:154 ../../WPrefs.app/Icons.c:161 +#: ../../WPrefs.app/Icons.c:369 ../../WPrefs.app/Preferences.c:120 +#: ../../WPrefs.app/WindowHandling.c:140 ../../WPrefs.app/WindowHandling.c:159 +#, c-format +msgid "OFF" +msgstr "KAPALI" + +#: ../../WPrefs.app/Focus.c:199 +msgid "Input Focus Mode" +msgstr "Giriş Odak Modu" + +#: ../../WPrefs.app/Focus.c:207 +msgid "Manual: Click on the window to set keyboard input focus" +msgstr "Manuel: Klavye giriş odağını ayarlamak için pencereye tıklayın" + +#: ../../WPrefs.app/Focus.c:213 +msgid "Auto: Set keyboard input focus to the window under the mouse pointer" +msgstr "" +"Otomatik: Klavye giriş odağını fare işaretçisinin altındaki pencereye ayarla" + +#: ../../WPrefs.app/Focus.c:226 +msgid "Install colormap from the window..." +msgstr "Renk haritasını pencereden yükle ..." + +#: ../../WPrefs.app/Focus.c:228 +msgid "" +"This option is for screens that can display only a limited number\n" +"of colors at a time, so they use an indexed table of colors (called\n" +"a ColorMap) that each application customizes for its needs, and\n" +"WindowMaker will set the global ColorMap dynamically from the\n" +"active application.\n" +"You can know the capability of your screen in WindowMaker's info\n" +"panel as the 'visual'." +msgstr "" +"Bu seçenek bir seferde yalnızca sınırlı sayıda renk görüntüleyebilen " +"ekranlar içindir, bu nedenle her uygulamanın ihtiyaçları için özelleştirdiği " +"dizine alınmış bir renk tablosu (ColorMap olarak adlandırılır) kullanırlar " +"ve WindowMaker genel ColorMap'i etkin olarak dinamik olarak ayarlar uygulama." +" WindowMaker'ın bilgi panelinde ekranınızın yeteneğini 'görsel' olarak " +"bilebilirsiniz." + +#: ../../WPrefs.app/Focus.c:240 +msgid "...that has the input focus" +msgstr "... giriş odağı olan" + +#: ../../WPrefs.app/Focus.c:245 +msgid "...that's under the mouse pointer" +msgstr "... bu fare imlecinin altında" + +#: ../../WPrefs.app/Focus.c:254 +msgid "Automatic Window Raise Delay" +msgstr "Otomatik Pencere Yükseltme Gecikmesi" + +#: ../../WPrefs.app/Focus.c:326 +msgid "Do not let applications receive the click used to focus windows" +msgstr "" +"Uygulamaların pencereleri odaklamak için kullanılan tıklamayı almasına izin " +"verme" + +#: ../../WPrefs.app/Focus.c:331 +msgid "Automatically focus new windows" +msgstr "Yeni pencereleri otomatik olarak odakla" + +#: ../../WPrefs.app/Focus.c:336 +msgid "Raise window when switching focus with keyboard" +msgstr "Odağı klavyeyle değiştirirken pencereyi kaldır" + +#: ../../WPrefs.app/Focus.c:352 +msgid "Window Focus Preferences" +msgstr "Pencere Odaklama Tercihleri" + +#: ../../WPrefs.app/Focus.c:353 +msgid "Keyboard focus switching policy and related options." +msgstr "Klavye odak değiştirme politikası ve ilgili seçenekler." + +#: ../../WPrefs.app/FontSimple.c:99 +msgid "Window Title" +msgstr "Pencere Başlığı" + +#: ../../WPrefs.app/FontSimple.c:101 +msgid "Menu Text" +msgstr "Menü Metni" + +#: ../../WPrefs.app/FontSimple.c:102 +msgid "Icon Title" +msgstr "Simge Başlığı" + +#: ../../WPrefs.app/FontSimple.c:104 +msgid "Desktop Caption" +msgstr "Masaüstü Altyazısı" + +#: ../../WPrefs.app/FontSimple.c:105 +msgid "System Font" +msgstr "Sistem Yazı Tipi" + +#: ../../WPrefs.app/FontSimple.c:106 +msgid "Bold System Font" +msgstr "Kalın Sistem Yazı Tipi" + +#: ../../WPrefs.app/FontSimple.c:661 +msgid "Sample Text" +msgstr "Örnek Metin" + +#: ../../WPrefs.app/FontSimple.c:678 +msgid "Family" +msgstr "Aile" + +#: ../../WPrefs.app/FontSimple.c:704 +msgid "Style" +msgstr "Stil" + +#: ../../WPrefs.app/FontSimple.c:707 +msgid "Size" +msgstr "Boyut" + +#: ../../WPrefs.app/FontSimple.c:739 +msgid "Font Configuration" +msgstr "Yazı Tipi Yapılandırması" + +#: ../../WPrefs.app/FontSimple.c:741 +msgid "Configure fonts for Window Maker titlebars, menus etc." +msgstr "" +"Window Maker başlık çubukları, menüler vb. için yazı tiplerini yapılandırma." + +#: ../../WPrefs.app/Icons.c:29 +msgid "Shrinking/Zooming" +msgstr "Küçülme / Yakınlaştırma" + +#: ../../WPrefs.app/Icons.c:30 +msgid "Spinning/Twisting" +msgstr "Eğirme / Büküm" + +#: ../../WPrefs.app/Icons.c:31 +msgid "3D-flipping" +msgstr "3B çevirme" + +#: ../../WPrefs.app/Icons.c:32 ../../WPrefs.app/MouseSettings.c:56 +#: ../../WPrefs.app/MouseSettings.c:70 +msgid "None" +msgstr "Yok" + +#: ../../WPrefs.app/Icons.c:186 ../../WPrefs.app/Preferences.c:145 +#: ../../WPrefs.app/Preferences.c:159 +#, c-format +msgid "bad value \"%s\" for option %s, using default \"%s\"" +msgstr "%s seçeneği için varsayılan \"%s\" kullanılarak \"%s\" hatalı değeri" + +#: ../../WPrefs.app/Icons.c:228 +#, c-format +msgid "animation style \"%s\" is unknown, resetting to \"%s\"" +msgstr "animasyon stili \"%s\" bilinmiyor, \"%s\" olarak sıfırlanıyor" + +#: ../../WPrefs.app/Icons.c:255 +msgid "Icon Positioning" +msgstr "Simge Konumlandırma" + +#: ../../WPrefs.app/Icons.c:334 +msgid "Icon Size" +msgstr "Simge Boyutu" + +#: ../../WPrefs.app/Icons.c:336 +msgid "The size of the dock/application icon and miniwindows" +msgstr "Dock / uygulama simgesinin ve mini pencerelerin boyutu" + +#: ../../WPrefs.app/Icons.c:353 +msgid "Mini-Previews for Icons" +msgstr "Simgeler için Mini Önizlemeler" + +#: ../../WPrefs.app/Icons.c:355 +msgid "" +"The Mini-Preview provides a small view of the content of the\n" +"window when the mouse is placed over the icon." +msgstr "" +"Mini Önizleme, fare simgenin üzerine getirildiğinde pencerenin içeriğinin " +"küçük bir görünümünü sağlar." + +#: ../../WPrefs.app/Icons.c:377 +msgid "Iconification Animation" +msgstr "İkonlaştırma Animasyonu" + +#: ../../WPrefs.app/Icons.c:398 +msgid "Auto-arrange icons" +msgstr "Simgeleri otomatik düzenle" + +#: ../../WPrefs.app/Icons.c:400 +msgid "Keep icons and miniwindows arranged all the time." +msgstr "Simgeleri ve mini pencereleri her zaman düzenli tutun." + +#: ../../WPrefs.app/Icons.c:406 +msgid "Omnipresent miniwindows" +msgstr "Omnipresent mini pencereler" + +#: ../../WPrefs.app/Icons.c:408 +msgid "Make miniwindows be present in all workspaces." +msgstr "Mini pencerelerin tüm çalışma alanlarında bulunmasını sağla." + +#: ../../WPrefs.app/Icons.c:414 +msgid "Single click activation" +msgstr "Tek tıkla etkinleştirme" + +#: ../../WPrefs.app/Icons.c:416 +msgid "Launch applications and restore windows with a single click." +msgstr "" +"Uygulamaları başlatın ve tek bir tıklama ile pencereleri geri yükleyin." + +#: ../../WPrefs.app/Icons.c:422 +msgid "Enforce icon margin" +msgstr "Simge kenar boşluğunu zorunlu kıl" + +#: ../../WPrefs.app/Icons.c:424 +msgid "Make sure that the icon image does not protrude into the icon frame." +msgstr "Simge görüntüsünün simge çerçevesine çıkmadığından emin olun." + +#: ../../WPrefs.app/Icons.c:472 +msgid "Icon Preferences" +msgstr "Simge Tercihleri" + +#: ../../WPrefs.app/Icons.c:474 +msgid "" +"Icon/Miniwindow handling options. Icon positioning\n" +"area, sizes of icons, miniaturization animation style." +msgstr "" +"Simge / Miniwindow kullanım seçenekleri. Simge konumlandırma alanı, simge " +"boyutları, minyatür animasyon stili." + +#: ../../WPrefs.app/KeyboardShortcuts.c:72 +msgid "Open applications menu" +msgstr "Uygulamalar menüsünü aç" + +#: ../../WPrefs.app/KeyboardShortcuts.c:73 +msgid "Open window list menu" +msgstr "Pencere listesi menüsünü aç" + +#: ../../WPrefs.app/KeyboardShortcuts.c:74 +msgid "Open window commands menu" +msgstr "Pencere komutları menüsünü aç" + +#: ../../WPrefs.app/KeyboardShortcuts.c:75 +msgid "Hide active application" +msgstr "Etkin uygulamayı gizle" + +#: ../../WPrefs.app/KeyboardShortcuts.c:76 +msgid "Hide other applications" +msgstr "Diğer uygulamaları gizle" + +#: ../../WPrefs.app/KeyboardShortcuts.c:77 +msgid "Miniaturize active window" +msgstr "Aktif pencereyi küçült" + +#: ../../WPrefs.app/KeyboardShortcuts.c:78 +msgid "Miniaturize all windows" +msgstr "Tüm pencereleri küçült" + +#: ../../WPrefs.app/KeyboardShortcuts.c:79 +msgid "Close active window" +msgstr "Etkin pencereyi kapat" + +#: ../../WPrefs.app/KeyboardShortcuts.c:80 +msgid "Maximize active window" +msgstr "Etkin pencereyi büyüt" + +#: ../../WPrefs.app/KeyboardShortcuts.c:81 +msgid "Maximize active window vertically" +msgstr "Aktif pencereyi dikey olarak büyüt" + +#: ../../WPrefs.app/KeyboardShortcuts.c:82 +msgid "Maximize active window horizontally" +msgstr "Aktif pencereyi yatay olarak büyüt" + +#: ../../WPrefs.app/KeyboardShortcuts.c:83 +msgid "Maximize active window left half" +msgstr "Aktif pencerenin sol yarısını büyüt" + +#: ../../WPrefs.app/KeyboardShortcuts.c:84 +msgid "Maximize active window right half" +msgstr "Aktif pencerenin sağ yarısını büyüt" + +#: ../../WPrefs.app/KeyboardShortcuts.c:85 +msgid "Maximize active window top half" +msgstr "Aktif pencerenin üst yarısını büyüt" + +#: ../../WPrefs.app/KeyboardShortcuts.c:86 +msgid "Maximize active window bottom half" +msgstr "Aktif pencerenin alt yarısını büyüt" + +#: ../../WPrefs.app/KeyboardShortcuts.c:87 +msgid "Maximize active window left top corner" +msgstr "Aktif pencereyi sol üst köşeye büyüt" + +#: ../../WPrefs.app/KeyboardShortcuts.c:88 +msgid "Maximize active window right top corner" +msgstr "Aktif pencereyi sağ üst köşeye büyüt" + +#: ../../WPrefs.app/KeyboardShortcuts.c:89 +msgid "Maximize active window left bottom corner" +msgstr "Aktif pencereyi sol alt köşeye büyüt" + +#: ../../WPrefs.app/KeyboardShortcuts.c:90 +msgid "Maximize active window right bottom corner" +msgstr "Aktif pencereyi sağ alt köşeye büyüt" + +#: ../../WPrefs.app/KeyboardShortcuts.c:91 +msgid "Maximus: Tiled maximization " +msgstr "Maximus: Döşenmiş maksimizasyon" + +#: ../../WPrefs.app/KeyboardShortcuts.c:92 +msgid "Toggle window on top status" +msgstr "Pencereyi üst durumda aç / kapat" + +#: ../../WPrefs.app/KeyboardShortcuts.c:93 +msgid "Toggle window at bottom status" +msgstr "Pencereyi en alt konumda aç / kapat" + +#: ../../WPrefs.app/KeyboardShortcuts.c:94 +msgid "Toggle window omnipresent status" +msgstr "Pencere her zaman mevcut durumunu aç / kapat" + +#: ../../WPrefs.app/KeyboardShortcuts.c:95 +msgid "Raise active window" +msgstr "Aktif pencereyi kaldır" + +#: ../../WPrefs.app/KeyboardShortcuts.c:96 +msgid "Lower active window" +msgstr "Alt aktif pencere" + +#: ../../WPrefs.app/KeyboardShortcuts.c:97 +msgid "Raise/Lower window under mouse pointer" +msgstr "Fare işaretçisinin altındaki pencereyi kaldır / indir" + +#: ../../WPrefs.app/KeyboardShortcuts.c:98 +msgid "Shade active window" +msgstr "Gölge aktif pencere" + +#: ../../WPrefs.app/KeyboardShortcuts.c:99 +msgid "Move/Resize active window" +msgstr "Etkin pencereyi taşı / yeniden boyutlandır" + +#: ../../WPrefs.app/KeyboardShortcuts.c:100 +msgid "Select active window" +msgstr "Aktif pencereyi seç" + +#: ../../WPrefs.app/KeyboardShortcuts.c:101 +msgid "Focus next window" +msgstr "Bir sonraki pencereye odaklan" + +#: ../../WPrefs.app/KeyboardShortcuts.c:102 +msgid "Focus previous window" +msgstr "Önceki pencereye odaklan" + +#: ../../WPrefs.app/KeyboardShortcuts.c:103 +msgid "Focus next group window" +msgstr "Sonraki grup penceresine odaklan" + +#: ../../WPrefs.app/KeyboardShortcuts.c:104 +msgid "Focus previous group window" +msgstr "Önceki grup penceresine odaklan" + +#. Workspace Related +#: ../../WPrefs.app/KeyboardShortcuts.c:107 +msgid "Open workspace pager" +msgstr "Çalışma alanı çağrı cihazını aç" + +#: ../../WPrefs.app/KeyboardShortcuts.c:108 +msgid "Switch to next workspace" +msgstr "Sonraki çalışma alanına geç" + +#: ../../WPrefs.app/KeyboardShortcuts.c:109 +msgid "Switch to previous workspace" +msgstr "Önceki çalışma alanına geç" + +#: ../../WPrefs.app/KeyboardShortcuts.c:110 +msgid "Switch to last used workspace" +msgstr "Son kullanılan çalışma alanına geç" + +#: ../../WPrefs.app/KeyboardShortcuts.c:111 +msgid "Switch to next ten workspaces" +msgstr "Sonraki on çalışma alanına geç" + +#: ../../WPrefs.app/KeyboardShortcuts.c:112 +msgid "Switch to previous ten workspaces" +msgstr "Önceki on çalışma alanına geç" + +#: ../../WPrefs.app/KeyboardShortcuts.c:113 +msgid "Switch to workspace 1" +msgstr "Çalışma alanı 1'e geç" + +#: ../../WPrefs.app/KeyboardShortcuts.c:114 +msgid "Switch to workspace 2" +msgstr "Çalışma alanı 2'ye geç" + +#: ../../WPrefs.app/KeyboardShortcuts.c:115 +msgid "Switch to workspace 3" +msgstr "Çalışma alanı 3'e geç" + +#: ../../WPrefs.app/KeyboardShortcuts.c:116 +msgid "Switch to workspace 4" +msgstr "Çalışma alanı 4'e geç" + +#: ../../WPrefs.app/KeyboardShortcuts.c:117 +msgid "Switch to workspace 5" +msgstr "Çalışma alanına 5 geç" + +#: ../../WPrefs.app/KeyboardShortcuts.c:118 +msgid "Switch to workspace 6" +msgstr "Çalışma alanına 6 geç" + +#: ../../WPrefs.app/KeyboardShortcuts.c:119 +msgid "Switch to workspace 7" +msgstr "Çalışma alanı 7'ye geç" + +#: ../../WPrefs.app/KeyboardShortcuts.c:120 +msgid "Switch to workspace 8" +msgstr "Çalışma alanına 8 geç" + +#: ../../WPrefs.app/KeyboardShortcuts.c:121 +msgid "Switch to workspace 9" +msgstr "Çalışma alanına 9 geç" + +#: ../../WPrefs.app/KeyboardShortcuts.c:122 +msgid "Switch to workspace 10" +msgstr "Çalışma alanı 10'a geç" + +#: ../../WPrefs.app/KeyboardShortcuts.c:123 +msgid "Move window to next workspace" +msgstr "Pencereyi bir sonraki çalışma alanına taşı" + +#: ../../WPrefs.app/KeyboardShortcuts.c:124 +msgid "Move window to previous workspace" +msgstr "Pencereyi önceki çalışma alanına taşı" + +#: ../../WPrefs.app/KeyboardShortcuts.c:125 +msgid "Move window to last used workspace" +msgstr "Pencereyi son kullanılan çalışma alanına taşı" + +#: ../../WPrefs.app/KeyboardShortcuts.c:126 +msgid "Move window to next ten workspaces" +msgstr "Pencereyi sonraki on çalışma alanına taşı" + +#: ../../WPrefs.app/KeyboardShortcuts.c:127 +msgid "Move window to previous ten workspaces" +msgstr "Pencereyi önceki on çalışma alanına taşı" + +#: ../../WPrefs.app/KeyboardShortcuts.c:128 +msgid "Move window to workspace 1" +msgstr "Pencereyi çalışma alanına taşıma 1" + +#: ../../WPrefs.app/KeyboardShortcuts.c:129 +msgid "Move window to workspace 2" +msgstr "Pencereyi çalışma alanına 2 taşı" + +#: ../../WPrefs.app/KeyboardShortcuts.c:130 +msgid "Move window to workspace 3" +msgstr "Pencereyi çalışma alanına 3 taşı" + +#: ../../WPrefs.app/KeyboardShortcuts.c:131 +msgid "Move window to workspace 4" +msgstr "Pencereyi çalışma alanına 4 taşı" + +#: ../../WPrefs.app/KeyboardShortcuts.c:132 +msgid "Move window to workspace 5" +msgstr "Pencereyi çalışma alanına taşıma 5" + +#: ../../WPrefs.app/KeyboardShortcuts.c:133 +msgid "Move window to workspace 6" +msgstr "Pencereyi çalışma alanına taşıma 6" + +#: ../../WPrefs.app/KeyboardShortcuts.c:134 +msgid "Move window to workspace 7" +msgstr "Pencereyi çalışma alanına taşıma 7" + +#: ../../WPrefs.app/KeyboardShortcuts.c:135 +msgid "Move window to workspace 8" +msgstr "Pencereyi çalışma alanına 8 taşıma" + +#: ../../WPrefs.app/KeyboardShortcuts.c:136 +msgid "Move window to workspace 9" +msgstr "Pencereyi çalışma alanına 9 taşıma" + +#: ../../WPrefs.app/KeyboardShortcuts.c:137 +msgid "Move window to workspace 10" +msgstr "Pencereyi çalışma alanına taşıma 10" + +#. Window Selection +#: ../../WPrefs.app/KeyboardShortcuts.c:140 +msgid "Shortcut for window 1" +msgstr "Pencere 1 için kısayol" + +#: ../../WPrefs.app/KeyboardShortcuts.c:141 +msgid "Shortcut for window 2" +msgstr "Pencere 2 için kısayol" + +#: ../../WPrefs.app/KeyboardShortcuts.c:142 +msgid "Shortcut for window 3" +msgstr "Pencere 3 için kısayol" + +#: ../../WPrefs.app/KeyboardShortcuts.c:143 +msgid "Shortcut for window 4" +msgstr "Pencere 4 için kısayol" + +#: ../../WPrefs.app/KeyboardShortcuts.c:144 +msgid "Shortcut for window 5" +msgstr "Pencere 5 için kısayol" + +#: ../../WPrefs.app/KeyboardShortcuts.c:145 +msgid "Shortcut for window 6" +msgstr "Pencere 6 için kısayol" + +#: ../../WPrefs.app/KeyboardShortcuts.c:146 +msgid "Shortcut for window 7" +msgstr "Pencere 7 için kısayol" + +#: ../../WPrefs.app/KeyboardShortcuts.c:147 +msgid "Shortcut for window 8" +msgstr "Pencere 8 için kısayol" + +#: ../../WPrefs.app/KeyboardShortcuts.c:148 +msgid "Shortcut for window 9" +msgstr "Pencere 9 için kısayol" + +#: ../../WPrefs.app/KeyboardShortcuts.c:149 +msgid "Shortcut for window 10" +msgstr "Pencere 10 için kısayol" + +#. Head Selection +#: ../../WPrefs.app/KeyboardShortcuts.c:152 +msgid "Move to right/bottom/left/top head" +msgstr "Sağ / alt / sol / üst başa git" + +#: ../../WPrefs.app/KeyboardShortcuts.c:153 +msgid "Move to left/top/right/bottom head" +msgstr "Sola / yukarı / sağa / alta başa git" + +#. Misc. +#: ../../WPrefs.app/KeyboardShortcuts.c:156 +msgid "Launch new instance of application" +msgstr "Yeni uygulama örneği başlat" + +#: ../../WPrefs.app/KeyboardShortcuts.c:157 +msgid "Switch to Next Screen/Monitor" +msgstr "Sonraki Ekrana / Monitöre Geç" + +#: ../../WPrefs.app/KeyboardShortcuts.c:158 +msgid "Run application" +msgstr "Uygulamayı çalıştır" + +#: ../../WPrefs.app/KeyboardShortcuts.c:159 +msgid "Raise/Lower Dock" +msgstr "Yükseltme / indirme istasyonu" + +#: ../../WPrefs.app/KeyboardShortcuts.c:160 +msgid "Raise/Lower Clip" +msgstr "Yükselt / Alt Klip" + +#: ../../WPrefs.app/KeyboardShortcuts.c:162 +msgid "Toggle keyboard language" +msgstr "Klavye dilini aç / kapat" + +#: ../../WPrefs.app/KeyboardShortcuts.c:379 ../../WPrefs.app/Menu.c:275 +#: ../../WPrefs.app/TexturePanel.c:1425 +msgid "Cancel" +msgstr "İptal" + +#: ../../WPrefs.app/KeyboardShortcuts.c:381 +msgid "Press the desired shortcut key(s) or click Cancel to stop capturing." +msgstr "" +"Yakalamayı durdurmak için istediğiniz kısayol tuşlarına basın veya İptal'i " +"tıklayın." + +#: ../../WPrefs.app/KeyboardShortcuts.c:400 +#: ../../WPrefs.app/KeyboardShortcuts.c:570 ../../WPrefs.app/Menu.c:285 +#: ../../WPrefs.app/Menu.c:733 +msgid "Capture" +msgstr "Yakala" + +#: ../../WPrefs.app/KeyboardShortcuts.c:401 +#: ../../WPrefs.app/KeyboardShortcuts.c:578 +msgid "Click on Capture to interactively define the shortcut key." +msgstr "Kısayol tuşunu etkileşimli olarak tanımlamak için Yakala'ya tıklayın." + +#: ../../WPrefs.app/KeyboardShortcuts.c:527 +msgid "Actions" +msgstr "Eylemler" + +#: ../../WPrefs.app/KeyboardShortcuts.c:554 +msgid "Shortcut" +msgstr "Kısayol" + +#: ../../WPrefs.app/KeyboardShortcuts.c:564 ../../WPrefs.app/Menu.c:739 +msgid "Clear" +msgstr "Temizle" + +#: ../../WPrefs.app/KeyboardShortcuts.c:619 +msgid "Keyboard Shortcut Preferences" +msgstr "Klavye Kısayol Tercihleri" + +#: ../../WPrefs.app/KeyboardShortcuts.c:621 +msgid "" +"Change the keyboard shortcuts for actions such\n" +"as changing workspaces and opening menus." +msgstr "" +"Çalışma alanlarını değiştirme ve menüleri açma gibi eylemler için klavye " +"kısayollarını değiştirin." + +#: ../../WPrefs.app/Menu.c:251 +msgid "Select Program" +msgstr "Program Seç" + +#: ../../WPrefs.app/Menu.c:413 +msgid "New Items" +msgstr "Yeni Ürünler" + +#: ../../WPrefs.app/Menu.c:414 +msgid "Sample Commands" +msgstr "Örnek Komutlar" + +#: ../../WPrefs.app/Menu.c:415 +msgid "Sample Submenus" +msgstr "Örnek Alt Menüler" + +#: ../../WPrefs.app/Menu.c:427 +msgid "Run Program" +msgstr "Programı Çalıştır" + +#: ../../WPrefs.app/Menu.c:428 +msgid "Internal Command" +msgstr "Dahili Komut" + +#: ../../WPrefs.app/Menu.c:429 +msgid "Submenu" +msgstr "Alt menü" + +#: ../../WPrefs.app/Menu.c:430 +msgid "External Submenu" +msgstr "Dış Alt menü" + +#: ../../WPrefs.app/Menu.c:431 +msgid "Generated Submenu" +msgstr "Oluşturulan Alt Menü" + +#: ../../WPrefs.app/Menu.c:432 +msgid "Generated PL Menu" +msgstr "Oluşturulmuş PL Menüsü" + +#: ../../WPrefs.app/Menu.c:433 +msgid "Directory Contents" +msgstr "Dizin İçeriği" + +#: ../../WPrefs.app/Menu.c:434 +msgid "Workspace Menu" +msgstr "Çalışma Alanı Menüsü" + +#: ../../WPrefs.app/Menu.c:435 ../../WPrefs.app/MouseSettings.c:58 +msgid "Window List Menu" +msgstr "Pencere Listesi Menüsü" + +#: ../../WPrefs.app/Menu.c:454 +msgid "XTerm" +msgstr "Xterm" + +#: ../../WPrefs.app/Menu.c:457 +msgid "rxvt" +msgstr "" + +#: ../../WPrefs.app/Menu.c:460 +msgid "ETerm" +msgstr "" + +#: ../../WPrefs.app/Menu.c:463 +msgid "Run..." +msgstr "Çalıştır ..." + +#: ../../WPrefs.app/Menu.c:464 +#, c-format +msgid "%A(Run,Type command to run)" +msgstr "%A (Çalıştır, Çalıştırılacak komut)" + +#: ../../WPrefs.app/Menu.c:466 +msgid "Firefox" +msgstr "" + +#: ../../WPrefs.app/Menu.c:469 +msgid "gimp" +msgstr "" + +#: ../../WPrefs.app/Menu.c:472 +msgid "epic" +msgstr "" + +#: ../../WPrefs.app/Menu.c:475 +msgid "ee" +msgstr "" + +#: ../../WPrefs.app/Menu.c:478 +msgid "xv" +msgstr "" + +#: ../../WPrefs.app/Menu.c:481 +msgid "Evince" +msgstr "" + +#: ../../WPrefs.app/Menu.c:484 +msgid "ghostview" +msgstr "" + +#: ../../WPrefs.app/Menu.c:487 ../../WPrefs.app/Menu.c:758 +msgid "Exit Window Maker" +msgstr "Pencere Oluşturucusundan Çık" + +#: ../../WPrefs.app/Menu.c:509 +msgid "Debian Menu" +msgstr "Debian Menüsü" + +#: ../../WPrefs.app/Menu.c:512 +msgid "RedHat Menu" +msgstr "RedHat Menüsü" + +#: ../../WPrefs.app/Menu.c:515 +msgid "Menu Conectiva" +msgstr "Menü Bağlantısı" + +#: ../../WPrefs.app/Menu.c:518 +msgid "Themes" +msgstr "Temalar" + +#: ../../WPrefs.app/Menu.c:524 +msgid "Bg Images (scale)" +msgstr "Bg Görüntüleri (ölçek)" + +#: ../../WPrefs.app/Menu.c:530 +msgid "Bg Images (tile)" +msgstr "Bg Görüntüleri (kutucuk)" + +#: ../../WPrefs.app/Menu.c:536 +msgid "Assorted XTerms" +msgstr "Çeşitli XTerms" + +#: ../../WPrefs.app/Menu.c:538 +msgid "XTerm Yellow on Blue" +msgstr "XTerm Mavi üzerine sarı" + +#: ../../WPrefs.app/Menu.c:541 +msgid "XTerm White on Black" +msgstr "XTerm Siyah üzerine beyaz" + +#: ../../WPrefs.app/Menu.c:544 +msgid "XTerm Black on White" +msgstr "XTerm beyaz üzerine siyah" + +#: ../../WPrefs.app/Menu.c:547 +msgid "XTerm Black on Beige" +msgstr "XTerm Bej üzerine siyah" + +#: ../../WPrefs.app/Menu.c:550 +msgid "XTerm White on Green" +msgstr "XTerm Yeşil Beyaz" + +#: ../../WPrefs.app/Menu.c:553 +msgid "XTerm White on Olive" +msgstr "XTerm Zeytin Üzerine Beyaz" + +#: ../../WPrefs.app/Menu.c:556 +msgid "XTerm Blue on Blue" +msgstr "XTerm Mavi üzerinde mavi" + +#: ../../WPrefs.app/Menu.c:559 +msgid "XTerm BIG FONTS" +msgstr "XTerm BÜYÜK FONTS" + +#: ../../WPrefs.app/Menu.c:580 +msgid "Program to Run" +msgstr "Çalıştırılacak Program" + +#: ../../WPrefs.app/Menu.c:590 +msgid "Browse" +msgstr "Gözat" + +#: ../../WPrefs.app/Menu.c:599 +msgid "Run the program inside a Xterm" +msgstr "Programı bir Xterm içinde çalıştır" + +#: ../../WPrefs.app/Menu.c:608 +msgid "Path for Menu" +msgstr "Menü Yolu" + +#: ../../WPrefs.app/Menu.c:619 +msgid "" +"Enter the path for a file containing a menu\n" +"or a list of directories with the programs you\n" +"want to have listed in the menu. Ex:\n" +"~/GNUstep/Library/WindowMaker/menu\n" +"or\n" +"/usr/bin ~/xbin" +msgstr "" +"Menü içeren bir dosyanın yolunu veya menüde listelenmesini istediğiniz " +"programların bulunduğu dizinlerin bir listesini girin.\n" +"Örnek: ~/GNUstep/Library/WindowMaker/menu\n" +"veya\n" +"/usr/bin ~/xbin" + +#: ../../WPrefs.app/Menu.c:631 ../../WPrefs.app/Menu.c:656 +msgid "Command" +msgstr "Komut" + +#: ../../WPrefs.app/Menu.c:642 +msgid "" +"Enter a command that outputs a menu\n" +"definition to stdout when invoked." +msgstr "Çağrıldığında stdout'a bir menü tanımı veren bir komut girin." + +#: ../../WPrefs.app/Menu.c:647 ../../WPrefs.app/Menu.c:672 +msgid "" +"Cache menu contents after opening for\n" +"the first time" +msgstr "" +"İlk kez açtıktan sonra menü içeriğini önbelleğe al" + +#: ../../WPrefs.app/Menu.c:667 +msgid "" +"Enter a command that outputs a proplist menu\n" +"definition to stdout when invoked." +msgstr "" +"Çağrıldığında stdout'a bir destek listesi menü tanımı veren bir komut girin." + +#: ../../WPrefs.app/Menu.c:681 +msgid "Command to Open Files" +msgstr "Dosyaları Açma Komutu" + +#: ../../WPrefs.app/Menu.c:692 +msgid "" +"Enter the command you want to use to open the\n" +"files in the directories listed below." +msgstr "" +"Dosyaları aşağıda listelenen dizinlerde açmak için kullanmak istediğiniz " +"komutu girin." + +#: ../../WPrefs.app/Menu.c:700 +msgid "Directories with Files" +msgstr "Dosyalı Dizinler" + +#: ../../WPrefs.app/Menu.c:711 +msgid "Strip extensions from file names" +msgstr "Dosya adlarından uzantıları çıkar" + +#: ../../WPrefs.app/Menu.c:722 +msgid "Keyboard Shortcut" +msgstr "Klavye Kısayolu" + +#: ../../WPrefs.app/Menu.c:754 +msgid "Arrange Icons" +msgstr "Simgeleri Yerleştir" + +#: ../../WPrefs.app/Menu.c:755 +msgid "Hide All Windows Except For The Focused One" +msgstr "Odaklanmış Biri Hariç Tüm Pencereleri Gizle" + +#: ../../WPrefs.app/Menu.c:756 +msgid "Show All Windows" +msgstr "Tüm Pencereleri Göster" + +#: ../../WPrefs.app/Menu.c:759 +msgid "Exit X Session" +msgstr "X Oturumundan Çık" + +#: ../../WPrefs.app/Menu.c:760 +msgid "Restart Window Maker" +msgstr "Pencere Oluşturucuyu Yeniden Başlat" + +#: ../../WPrefs.app/Menu.c:761 +msgid "Start Another Window Manager : (" +msgstr "Başka Bir Pencere Yöneticisi Başlat : (" + +#: ../../WPrefs.app/Menu.c:763 +msgid "Save Current Session" +msgstr "Mevcut Oturumu Kaydet" + +#: ../../WPrefs.app/Menu.c:764 +msgid "Clear Saved Session" +msgstr "Kayıtlı Oturumu Temizle" + +#: ../../WPrefs.app/Menu.c:765 +msgid "Refresh Screen" +msgstr "Ekranı Yenile" + +#: ../../WPrefs.app/Menu.c:766 +msgid "Open Info Panel" +msgstr "Bilgi Panelini Aç" + +#: ../../WPrefs.app/Menu.c:767 +msgid "Open Copyright Panel" +msgstr "Telif Hakkı Panelini Aç" + +#: ../../WPrefs.app/Menu.c:772 +msgid "Window Manager to Start" +msgstr "Pencere Yöneticisi Başlatılacak" + +#: ../../WPrefs.app/Menu.c:785 +msgid "Do not confirm action." +msgstr "Eylemi onaylama." + +#: ../../WPrefs.app/Menu.c:792 +msgid "" +"Instructions:\n" +"\n" +" - drag items from the left to the menu to add new items\n" +" - drag items out of the menu to remove items\n" +" - drag items in menu to change their position\n" +" - drag items with Control pressed to copy them\n" +" - double click in a menu item to change the label\n" +" - click on a menu item to change related information" +msgstr "" +"Talimatlar:\n" +"\n" +" - yeni öğeler eklemek için öğeleri soldan menüye sürükleyin \n" +" - öğeleri kaldırmak için öğeleri menüden dışarı sürükleyin \n" +" - konumlarını değiştirmek için menüdeki öğeleri sürükleyin \n" +" - kopyalamak için Control tuşunu basılı tutarak öğeleri sürükleyin \n" +" - bir menü öğesine çift tıklayın etiketi değiştirmek için \n" +" - ilgili bilgileri değiştirmek için bir menü öğesini tıklayın" + +#: ../../WPrefs.app/Menu.c:1031 +#, c-format +msgid "unknown command '%s' in menu" +msgstr "menüde '%s' bilinmeyen komutu" + +#: ../../WPrefs.app/Menu.c:1055 +msgid ": Execute Program" +msgstr ": Programı Yürüt" + +#: ../../WPrefs.app/Menu.c:1059 +msgid ": Perform Internal Command" +msgstr ": Dahili Komutu Gerçekleştir" + +#: ../../WPrefs.app/Menu.c:1063 +msgid ": Open a Submenu" +msgstr ": Bir alt menü aç" + +#: ../../WPrefs.app/Menu.c:1067 +msgid ": Program Generated Submenu" +msgstr ": Program Oluşturulan Alt Menüsü" + +#: ../../WPrefs.app/Menu.c:1071 +msgid ": Program Generated Proplist Submenu" +msgstr ": Program Oluşturulan Destekçi Alt Menüsü" + +#: ../../WPrefs.app/Menu.c:1075 +msgid ": Directory Contents Menu" +msgstr ": Dizin İçeriği Menüsü" + +#: ../../WPrefs.app/Menu.c:1079 +msgid ": Open Workspaces Submenu" +msgstr ": Açık Çalışma Alanları Alt Menüsü" + +#: ../../WPrefs.app/Menu.c:1083 +msgid ": Open Window List Submenu" +msgstr ": Pencere Listesi Alt Menüsünü Aç" + +#: ../../WPrefs.app/Menu.c:1299 +msgid "Remove Submenu" +msgstr "Alt menüyü kaldır" + +#: ../../WPrefs.app/Menu.c:1300 +msgid "" +"Removing this item will destroy all items inside\n" +"the submenu. Do you really want to do that?" +msgstr "" +"Bu öğenin kaldırılması, alt menüdeki tüm öğeleri yok edecektir. Bunu " +"gerçekten yapmak istiyor musun?" + +#: ../../WPrefs.app/Menu.c:1302 +msgid "Yes" +msgstr "Evet" + +#: ../../WPrefs.app/Menu.c:1302 +msgid "No" +msgstr "Hayır" + +#: ../../WPrefs.app/Menu.c:1302 +msgid "Yes, don't ask again" +msgstr "Evet, bir daha sorma" + +#: ../../WPrefs.app/Menu.c:1441 +#, c-format +msgid "Invalid menu command \"%s\" with label \"%s\" cleared" +msgstr "Geçersiz menü komutu \"%s\" etiketli \"%s\" temizlendi" + +#: ../../WPrefs.app/Menu.c:1444 ../../WPrefs.app/Menu.c:1522 +#: ../../WPrefs.app/Menu.c:1537 ../../WPrefs.app/WPrefs.c:668 +msgid "Warning" +msgstr "Uyarı" + +#: ../../WPrefs.app/Menu.c:1444 ../../WPrefs.app/Menu.c:1476 +#: ../../WPrefs.app/Menu.c:1523 ../../WPrefs.app/MouseSettings.c:156 +#: ../../WPrefs.app/MouseSettings.c:176 ../../WPrefs.app/TexturePanel.c:585 +#: ../../WPrefs.app/TexturePanel.c:663 ../../WPrefs.app/TexturePanel.c:1419 +#: ../../WPrefs.app/WPrefs.c:617 ../../WPrefs.app/WPrefs.c:621 +#: ../../WPrefs.app/WPrefs.c:641 ../../WPrefs.app/WPrefs.c:653 +#: ../../WPrefs.app/WPrefs.c:659 ../../WPrefs.app/WPrefs.c:668 +#: ../../WPrefs.app/WPrefs.c:699 ../../WPrefs.app/WPrefs.c:703 +msgid "OK" +msgstr "Tamam" + +#: ../../WPrefs.app/Menu.c:1472 +#, c-format +msgid "Could not open default menu from '%s'" +msgstr "'%s' öğesinden varsayılan menü açılamadı" + +#: ../../WPrefs.app/Menu.c:1476 ../../WPrefs.app/MouseSettings.c:154 +#: ../../WPrefs.app/MouseSettings.c:173 ../../WPrefs.app/TexturePanel.c:585 +#: ../../WPrefs.app/TexturePanel.c:661 ../../WPrefs.app/WPrefs.c:617 +#: ../../WPrefs.app/WPrefs.c:621 ../../WPrefs.app/WPrefs.c:638 +#: ../../WPrefs.app/WPrefs.c:649 ../../WPrefs.app/WPrefs.c:659 +#: ../../WPrefs.app/WPrefs.c:699 ../../WPrefs.app/WPrefs.c:703 +msgid "Error" +msgstr "Hata" + +#: ../../WPrefs.app/Menu.c:1516 +#, c-format +msgid "" +"The menu file \"%s\" referenced by WMRootMenu is read-only.\n" +"You cannot use WPrefs to modify it." +msgstr "" +"WMRootMenu tarafından başvurulan \"%s\" menü dosyası salt okunurdur.\n" +"WPrefs'i değiştirmek için kullanamazsınız." + +#: ../../WPrefs.app/Menu.c:1538 +msgid "" +"The menu file format currently in use is not supported\n" +"by this tool. Do you want to discard the current menu\n" +"to use this tool?" +msgstr "" +"Şu anda kullanımda olan menü dosyası biçimi bu araç tarafından " +"desteklenmiyor. Bu aracı kullanmak için geçerli menüyü silmek istiyor " +"musunuz?" + +#: ../../WPrefs.app/Menu.c:1541 +msgid "Yes, Discard and Update" +msgstr "Evet, Sil ve Güncelle" + +#: ../../WPrefs.app/Menu.c:1541 +msgid "No, Keep Current Menu" +msgstr "Hayır, Geçerli Menüyü Koru" + +#: ../../WPrefs.app/Menu.c:1558 +#, c-format +msgid "" +"\n" +"\n" +"When saved, the menu will be written to the file\n" +"\"%s\"." +msgstr "" +"\n" +"\n" +"Kaydedildiğinde, menü \"%s\" dosyasına yazılır." + +#: ../../WPrefs.app/Menu.c:1792 +msgid "Applications Menu Definition" +msgstr "Uygulamalar Menü Tanımı" + +#: ../../WPrefs.app/Menu.c:1794 +msgid "Edit the menu for launching applications." +msgstr "Uygulamaları başlatmak için menüyü düzenleyin." + +#: ../../WPrefs.app/MenuPreferences.c:105 +msgid "Menu Scrolling Speed" +msgstr "Menü Kaydırma Hızı" + +#: ../../WPrefs.app/MenuPreferences.c:153 +msgid "Submenu Alignment" +msgstr "Alt menü Hizalaması" + +#: ../../WPrefs.app/MenuPreferences.c:197 +msgid "Always open submenus inside the screen, instead of scrolling." +msgstr "Kaydırma yerine her zaman ekranın alt menülerini aç." + +#: ../../WPrefs.app/MenuPreferences.c:202 +msgid "Scroll off-screen menus when pointer is moved over them." +msgstr "İşaretçi üzerine getirildiğinde ekran dışındaki menüleri kaydırın." + +#: ../../WPrefs.app/MenuPreferences.c:206 +msgid "Use h/j/k/l keys to select menu options." +msgstr "Menü seçeneklerini seçmek için h / j / k / l tuşlarını kullanın." + +#: ../../WPrefs.app/MenuPreferences.c:222 +msgid "Menu Preferences" +msgstr "Menü Tercihleri" + +#: ../../WPrefs.app/MenuPreferences.c:224 +msgid "" +"Menu usability related options. Scrolling speed,\n" +"alignment of submenus etc." +msgstr "" +"Menü kullanılabilirliği ile ilgili seçenekler. Kaydırma hızı, alt menülerin " +"hizalanması vb." + +#: ../../WPrefs.app/MouseSettings.c:43 +msgid "Left Button" +msgstr "Sol Düğme" + +#: ../../WPrefs.app/MouseSettings.c:44 +msgid "Middle Button" +msgstr "Orta Düğme" + +#: ../../WPrefs.app/MouseSettings.c:45 +msgid "Right Button" +msgstr "Sağ Düğme" + +#: ../../WPrefs.app/MouseSettings.c:46 +msgid "Back Button" +msgstr "Geri Düğmesi" + +#: ../../WPrefs.app/MouseSettings.c:47 +msgid "Forward Button" +msgstr "İleri Düğmesi" + +#: ../../WPrefs.app/MouseSettings.c:48 +msgid "Mouse Wheel" +msgstr "Fare Tekerleği" + +#: ../../WPrefs.app/MouseSettings.c:49 +msgid "Mouse Wheel Tilt" +msgstr "Fare Tekerleği Eğimi" + +#: ../../WPrefs.app/MouseSettings.c:57 +msgid "Applications Menu" +msgstr "Uygulamalar Menüsü" + +#: ../../WPrefs.app/MouseSettings.c:59 +msgid "Select Windows" +msgstr "Windows'u seç" + +#: ../../WPrefs.app/MouseSettings.c:60 +msgid "Previous Workspace" +msgstr "Önceki Çalışma Alanı" + +#: ../../WPrefs.app/MouseSettings.c:61 +msgid "Next Workspace" +msgstr "Sonraki Çalışma Alanı" + +#: ../../WPrefs.app/MouseSettings.c:62 +msgid "Previous Window" +msgstr "Önceki Pencere" + +#: ../../WPrefs.app/MouseSettings.c:63 +msgid "Next Window" +msgstr "Sonraki Pencere" + +#: ../../WPrefs.app/MouseSettings.c:71 +msgid "Switch Workspaces" +msgstr "Çalışma Alanlarını Değiştir" + +#: ../../WPrefs.app/MouseSettings.c:72 +msgid "Switch Windows" +msgstr "Pencereleri değiştir" + +#: ../../WPrefs.app/MouseSettings.c:155 +msgid "Invalid mouse acceleration value. Must be a positive real value." +msgstr "Geçersiz fare hızlanma değeri. Olumlu bir gerçek değer olmalı." + +#: ../../WPrefs.app/MouseSettings.c:175 +msgid "" +"Invalid mouse acceleration threshold value. Must be the number of pixels to " +"travel before accelerating." +msgstr "" +"Geçersiz fare hızlanma eşik değeri. Hızlanmadan önce gidilecek piksel sayısı " +"olmalıdır." + +#: ../../WPrefs.app/MouseSettings.c:284 +#, c-format +msgid "bad value %s for option %s" +msgstr "%s seçeneği için %s hatalı değeri" + +#: ../../WPrefs.app/MouseSettings.c:343 +#, c-format +msgid "" +"modifier key %s for option ModifierKey was not recognized. Using %s as " +"default" +msgstr "" +"ModifierKey seçeneği için %s değiştirici anahtarı tanınmadı. %s 'yi " +"varsayılan olarak kullanma" + +#: ../../WPrefs.app/MouseSettings.c:364 +msgid "could not retrieve keyboard modifier mapping" +msgstr "klavye değiştirici eşlemesi alınamadı" + +#: ../../WPrefs.app/MouseSettings.c:458 +msgid "Mouse Speed" +msgstr "Fare Hızı" + +#: ../../WPrefs.app/MouseSettings.c:471 ../../WPrefs.app/WPrefs.c:408 +#: ../../WPrefs.app/WPrefs.c:424 ../../WPrefs.app/WindowHandling.c:372 +#: ../../WPrefs.app/WindowHandling.c:423 ../../WPrefs.app/WindowHandling.c:435 +#: ../../WPrefs.app/WindowHandling.c:454 ../../WPrefs.app/WindowHandling.c:466 +#, c-format +msgid "could not load icon %s" +msgstr "%s simgesi yüklenemedi" + +#: ../../WPrefs.app/MouseSettings.c:488 +msgid "Accel.:" +msgstr "Hızlanma:" + +#: ../../WPrefs.app/MouseSettings.c:499 +msgid "Threshold:" +msgstr "Eşik:" + +#: ../../WPrefs.app/MouseSettings.c:512 +msgid "Mouse Grab Modifier" +msgstr "Fare Tutucu Değiştirici" + +#: ../../WPrefs.app/MouseSettings.c:514 +msgid "" +"Keyboard modifier to use for actions that\n" +"involve dragging windows with the mouse,\n" +"clicking inside the window." +msgstr "" +"Pencerenin içini tıklatarak pencereleri fare ile sürüklemeyi içeren eylemler " +"için kullanılacak klavye değiştirici." + +#: ../../WPrefs.app/MouseSettings.c:530 +msgid "Double-Click Delay" +msgstr "Çift Tıklama Gecikmesi" + +#: ../../WPrefs.app/MouseSettings.c:573 +msgid "Test" +msgstr "" + +#: ../../WPrefs.app/MouseSettings.c:604 +msgid "Workspace Mouse Actions" +msgstr "Çalışma Alanı Fare Eylemleri" + +#: ../../WPrefs.app/MouseSettings.c:609 +msgid "Disable mouse actions" +msgstr "Fare eylemlerini devre dışı bırak" + +#: ../../WPrefs.app/MouseSettings.c:659 +#, c-format +msgid "could not create %s" +msgstr "%s oluşturulamadı" + +#: ../../WPrefs.app/MouseSettings.c:674 +#, c-format +msgid "could not create temporary file %s" +msgstr "%s geçici dosyası oluşturulamadı" + +#: ../../WPrefs.app/MouseSettings.c:707 +#, c-format +msgid "could not rename file %s to %s" +msgstr "%s dosyası %s olarak yeniden adlandırılamadı" + +#: ../../WPrefs.app/MouseSettings.c:712 +#, c-format +msgid "could not set permission 0%03o on file \"%s\"" +msgstr "dosyasında izin 0%03o ayarlanamadı (%s)" + +#: ../../WPrefs.app/MouseSettings.c:776 +msgid "Shift" +msgstr "" + +#: ../../WPrefs.app/MouseSettings.c:777 +msgid "Lock" +msgstr "Kilitle" + +#: ../../WPrefs.app/MouseSettings.c:778 +msgid "Control" +msgstr "Kontrol" + +#: ../../WPrefs.app/MouseSettings.c:779 +msgid "Mod1" +msgstr "" + +#: ../../WPrefs.app/MouseSettings.c:780 +msgid "Mod2" +msgstr "" + +#: ../../WPrefs.app/MouseSettings.c:781 +msgid "Mod3" +msgstr "" + +#: ../../WPrefs.app/MouseSettings.c:782 +msgid "Mod4" +msgstr "" + +#: ../../WPrefs.app/MouseSettings.c:783 +msgid "Mod5" +msgstr "" + +#: ../../WPrefs.app/MouseSettings.c:787 +msgid "Mouse Preferences" +msgstr "Fare Tercihleri" + +#: ../../WPrefs.app/MouseSettings.c:789 +msgid "" +"Mouse speed/acceleration, double click delay,\n" +"mouse button bindings etc." +msgstr "" +"Fare hızı / ivmesi, çift tıklama gecikmesi, fare düğmesi bağlantıları vb." + +#: ../../WPrefs.app/Paths.c:78 +msgid "bad value in option IconPath. Using default path list" +msgstr "IconPath seçeneğinde hatalı değer. Varsayılan yol listesini kullanma" + +#: ../../WPrefs.app/Paths.c:95 +msgid "bad value in option PixmapPath. Using default path list" +msgstr "PixmapPath seçeneğinde hatalı değer. Varsayılan yol listesini kullanma" + +#: ../../WPrefs.app/Paths.c:140 +msgid "Select directory" +msgstr "Dizini seç" + +#: ../../WPrefs.app/Paths.c:250 +msgid "Icon Search Paths" +msgstr "Simge Arama Yolları" + +#: ../../WPrefs.app/Paths.c:261 ../../WPrefs.app/Paths.c:292 +#: ../../WPrefs.app/TexturePanel.c:1212 +msgid "Add" +msgstr "Ekle" + +#: ../../WPrefs.app/Paths.c:268 ../../WPrefs.app/Paths.c:299 +msgid "Remove" +msgstr "Kaldır" + +#: ../../WPrefs.app/Paths.c:281 +msgid "Pixmap Search Paths" +msgstr "Pixmap Arama Yolları" + +#: ../../WPrefs.app/Paths.c:316 +msgid "Search Path Configuration" +msgstr "Arama Yolu Yapılandırması" + +#: ../../WPrefs.app/Paths.c:318 +msgid "" +"Search paths to use when looking for pixmaps\n" +"and icons." +msgstr "" +"Pikselleri ararken kullanılacak arama yolları\n" +"ve simgeler." + +#: ../../WPrefs.app/Preferences.c:30 ../../WPrefs.app/Preferences.c:42 +msgid "Corner of screen" +msgstr "Ekranın köşesi" + +#: ../../WPrefs.app/Preferences.c:31 ../../WPrefs.app/Preferences.c:43 +msgid "Center of screen" +msgstr "Ekranın merkezi" + +#: ../../WPrefs.app/Preferences.c:32 ../../WPrefs.app/Preferences.c:44 +msgid "Center of resized window" +msgstr "Yeniden boyutlandırılan pencerenin merkezi" + +#: ../../WPrefs.app/Preferences.c:33 +msgid "Technical drawing-like" +msgstr "Teknik resim benzeri" + +#: ../../WPrefs.app/Preferences.c:34 ../../WPrefs.app/Preferences.c:45 +msgid "Disabled" +msgstr "Devre dışı" + +#: ../../WPrefs.app/Preferences.c:53 +msgid "incomplete window titles" +msgstr "tamamlanmamış pencere başlıkları" + +#: ../../WPrefs.app/Preferences.c:54 +msgid "miniwindow titles" +msgstr "mini pencere başlıkları" + +#: ../../WPrefs.app/Preferences.c:55 +msgid "application/dock icons" +msgstr "uygulama / dock simgeleri" + +#: ../../WPrefs.app/Preferences.c:56 +msgid "internal help" +msgstr "dahili yardım" + +#: ../../WPrefs.app/Preferences.c:65 +msgid "Disable AppIcon bounce" +msgstr "AppIcon sekmesini devre dışı bırak" + +#: ../../WPrefs.app/Preferences.c:66 +msgid "By default, the AppIcon bounces when the application is launched" +msgstr "Uygulama başlatıldığında varsayılan olarak AppIcon sekiyor" + +#: ../../WPrefs.app/Preferences.c:68 +msgid "Bounce when the application wants attention" +msgstr "Uygulama dikkat istediğinde zıpla" + +#: ../../WPrefs.app/Preferences.c:71 +msgid "Raise AppIcon when bouncing" +msgstr "Zıplarken AppIcon'u kaldır" + +#: ../../WPrefs.app/Preferences.c:72 +msgid "" +"Otherwise you will not see it bouncing if\n" +"there is a window in front of the AppIcon" +msgstr "" +"Aksi takdirde, AppIcon'un önünde bir pencere varsa sıçradığını görmezsiniz" + +#: ../../WPrefs.app/Preferences.c:122 +#, c-format +msgid "1 pixel" +msgstr "1 piksel" + +#. 2-4 +#: ../../WPrefs.app/Preferences.c:125 +#, c-format +msgid "%i pixels" +msgstr "%i piksel" + +#. >4 +#: ../../WPrefs.app/Preferences.c:128 +#, c-format +msgid "%i pixels " +msgstr "%i piksel" + +#: ../../WPrefs.app/Preferences.c:236 +msgid "Size Display" +msgstr "Boyut Göstergesi" + +#: ../../WPrefs.app/Preferences.c:238 +msgid "" +"The position or style of the window size\n" +"display that's shown when a window is resized." +msgstr "" +"Pencere yeniden boyutlandırıldığında gösterilen pencere boyutu ekranının " +"konumu veya stili." + +#: ../../WPrefs.app/Preferences.c:253 +msgid "Position Display" +msgstr "Pozisyon Göstergesi" + +#: ../../WPrefs.app/Preferences.c:255 +msgid "" +"The position or style of the window position\n" +"display that's shown when a window is moved." +msgstr "" +"Bir pencere taşındığında gösterilen pencere konumu ekranının konumu veya " +"stili." + +#: ../../WPrefs.app/Preferences.c:270 +msgid "Show balloon for..." +msgstr "Balonu şunun için göster ..." + +#: ../../WPrefs.app/Preferences.c:285 +msgid "AppIcon bouncing" +msgstr "AppIcon sıçrayan" + +#: ../../WPrefs.app/Preferences.c:307 +msgid "Workspace border" +msgstr "Çalışma alanı sınırı" + +#: ../../WPrefs.app/Preferences.c:323 +msgid "Left/Right" +msgstr "Sol / Sağ" + +#: ../../WPrefs.app/Preferences.c:328 +msgid "Top/Bottom" +msgstr "Üst / Alt" + +#: ../../WPrefs.app/Preferences.c:344 +msgid "Miscellaneous Ergonomic Preferences" +msgstr "Çeşitli Ergonomik Tercihler" + +#: ../../WPrefs.app/Preferences.c:345 +msgid "" +"Various settings like balloon text, geometry\n" +"displays etc." +msgstr "Balon metni, geometri göstergeleri vb. Çeşitli ayarlar." + +#: ../../WPrefs.app/TexturePanel.c:296 +msgid "Saturation" +msgstr "Doygunluk" + +#: ../../WPrefs.app/TexturePanel.c:298 +msgid "Brightness" +msgstr "Parlaklık" + +#: ../../WPrefs.app/TexturePanel.c:343 ../../WPrefs.app/TexturePanel.c:349 +msgid "Hue" +msgstr "Ton" + +#: ../../WPrefs.app/TexturePanel.c:582 +msgid "Could not load the selected file: " +msgstr "Seçilen dosya yüklenemedi:" + +#: ../../WPrefs.app/TexturePanel.c:632 +msgid "Open Image" +msgstr "Görüntüyü Aç" + +#: ../../WPrefs.app/TexturePanel.c:662 +msgid "The selected file does not contain a supported image." +msgstr "Seçili dosya desteklenen bir resim içermiyor." + +#: ../../WPrefs.app/TexturePanel.c:995 +#, c-format +msgid "error creating texture %s" +msgstr "%s doku oluşturulurken hata" + +#: ../../WPrefs.app/TexturePanel.c:1157 +msgid "Texture Panel" +msgstr "Doku Paneli" + +#: ../../WPrefs.app/TexturePanel.c:1164 +msgid "Texture Name" +msgstr "Doku Adı" + +#: ../../WPrefs.app/TexturePanel.c:1176 +msgid "Solid Color" +msgstr "Düz Renk" + +#: ../../WPrefs.app/TexturePanel.c:1177 +msgid "Gradient Texture" +msgstr "Degrade Doku" + +#: ../../WPrefs.app/TexturePanel.c:1178 +msgid "Simple Gradient Texture" +msgstr "Basit Degrade Doku" + +#: ../../WPrefs.app/TexturePanel.c:1179 +msgid "Textured Gradient" +msgstr "Dokulu Degrade" + +#: ../../WPrefs.app/TexturePanel.c:1180 +msgid "Image Texture" +msgstr "Görüntü Dokusu" + +#: ../../WPrefs.app/TexturePanel.c:1188 +msgid "Default Color" +msgstr "Varsayılan Renk" + +#: ../../WPrefs.app/TexturePanel.c:1200 +msgid "Gradient Colors" +msgstr "Degrade Renkler" + +#: ../../WPrefs.app/TexturePanel.c:1289 +msgid "Direction" +msgstr "Yön" + +#: ../../WPrefs.app/TexturePanel.c:1317 +msgid "Gradient" +msgstr "Degrade" + +#: ../../WPrefs.app/TexturePanel.c:1333 +msgid "Gradient Opacity" +msgstr "Degrade Opaklığı" + +#: ../../WPrefs.app/TexturePanel.c:1373 +msgid "Image" +msgstr "Görüntü" + +#: ../../WPrefs.app/TexturePanel.c:1393 +msgid "Browse..." +msgstr "Gözat ..." + +#: ../../WPrefs.app/TexturePanel.c:1405 +msgid "Tile" +msgstr "Karo" + +#: ../../WPrefs.app/TexturePanel.c:1406 +msgid "Scale" +msgstr "Ölçek" + +#: ../../WPrefs.app/TexturePanel.c:1408 +msgid "Maximize" +msgstr "Ekranı kapla" + +#: ../../WPrefs.app/TexturePanel.c:1409 +msgid "Fill" +msgstr "Doldur" + +#: ../../WPrefs.app/WPrefs.c:212 ../../WPrefs.app/WPrefs.c:282 +msgid "Window Maker Preferences" +msgstr "Pencere Oluşturucu Tercihleri" + +#: ../../WPrefs.app/WPrefs.c:216 +msgid "Preferences" +msgstr "Tercihler" + +#: ../../WPrefs.app/WPrefs.c:235 +msgid "Revert Page" +msgstr "Sayfayı Geri Al" + +#: ../../WPrefs.app/WPrefs.c:241 +msgid "Revert All" +msgstr "Tümünü Döndür" + +#: ../../WPrefs.app/WPrefs.c:247 +msgid "Save" +msgstr "Kaydet" + +#: ../../WPrefs.app/WPrefs.c:259 +msgid "Balloon Help" +msgstr "Balon Yardımı" + +#: ../../WPrefs.app/WPrefs.c:289 +#, c-format +msgid "Version %s" +msgstr "Sürüm %s" + +#: ../../WPrefs.app/WPrefs.c:296 +msgid "Starting..." +msgstr "Başlatılıyor ..." + +#: ../../WPrefs.app/WPrefs.c:383 +#, c-format +msgid "could not locate image file %s" +msgstr "%s resim dosyası bulunamadı" + +#: ../../WPrefs.app/WPrefs.c:437 +#, c-format +msgid "could not process icon %s: %s" +msgstr "%s: %s simgesi işlenemedi" + +#: ../../WPrefs.app/WPrefs.c:537 +#, c-format +msgid "could not load image file %s:%s" +msgstr "resim dosyası yüklenemedi %s:%s" + +#: ../../WPrefs.app/WPrefs.c:554 +msgid "Loading Window Maker configuration files..." +msgstr "Window Maker yapılandırma dosyaları yükleniyor ..." + +#: ../../WPrefs.app/WPrefs.c:558 +msgid "Initializing configuration panels..." +msgstr "Yapılandırma panelleri başlatılıyor ..." + +#: ../../WPrefs.app/WPrefs.c:616 ../../WPrefs.app/WPrefs.c:698 +#, c-format +msgid "Window Maker domain (%s) is corrupted!" +msgstr "Window Maker etki alanı (%s) bozuk!" + +#: ../../WPrefs.app/WPrefs.c:620 +#, c-format +msgid "Could not load Window Maker domain (%s) from defaults database." +msgstr "Windows Maker etki alanı (%s) varsayılan veritabanından yüklenemedi." + +#: ../../WPrefs.app/WPrefs.c:635 +msgid "could not extract version information from Window Maker" +msgstr "Windows Maker'dan sürüm bilgisi alınamadı" + +#: ../../WPrefs.app/WPrefs.c:636 +msgid "Make sure wmaker is in your search path." +msgstr "Wmaker'ın arama yolunuzda olduğundan emin olun." + +#: ../../WPrefs.app/WPrefs.c:640 +msgid "" +"Could not extract version from Window Maker. Make sure it is correctly " +"installed and is in your PATH environment variable." +msgstr "" +"Windows Maker'dan sürüm alınamadı. Doğru bir şekilde kurulduğundan ve PATH " +"ortam değişkeninizde olduğundan emin olun." + +#: ../../WPrefs.app/WPrefs.c:650 +msgid "" +"Could not extract version from Window Maker. Make sure it is correctly " +"installed and the path where it installed is in the PATH environment " +"variable." +msgstr "" +"Windows Maker'dan sürüm alınamadı. Doğru yüklendiğinden ve yüklendiği yolun " +"PATH ortam değişkeninde olduğundan emin olun." + +#: ../../WPrefs.app/WPrefs.c:657 +#, c-format +msgid "" +"WPrefs only supports Window Maker 0.18.0 or newer.\n" +"The version installed is %i.%i.%i\n" +msgstr "" +"WPrefs yalnızca Window Maker 0.18.0 veya daha yenisini destekler. Yüklü " +"sürüm %i.%i.%i\n" + +#: ../../WPrefs.app/WPrefs.c:666 +#, c-format +msgid "" +"Window Maker %i.%i.%i, which is installed in your system, is not fully " +"supported by this version of WPrefs." +msgstr "" +"Sisteminize yüklenmiş olan Window Maker %i.%i.%i, WPrefs'in bu sürümü " +"tarafından tam olarak desteklenmiyor." + +#: ../../WPrefs.app/WPrefs.c:679 +#, c-format +msgid "could not run \"%s --global_defaults_path\"." +msgstr "\"%s --global_defaults_path\" çalıştırılamadı." + +#: ../../WPrefs.app/WPrefs.c:702 +#, c-format +msgid "Could not load global Window Maker domain (%s)." +msgstr "Genel Window Maker etki alanı (%s) yüklenemedi." + +#: ../../WPrefs.app/WPrefs.c:922 +#, c-format +msgid "bad speed value for option %s; using default Medium" +msgstr "%s seçeneği için hatalı hız değeri; varsayılan Ortamı kullanma" + +#: ../../WPrefs.app/WindowHandling.c:88 +msgid "Automatic" +msgstr "Otomatik" + +#: ../../WPrefs.app/WindowHandling.c:89 +msgid "Random" +msgstr "Rastgele" + +#: ../../WPrefs.app/WindowHandling.c:90 +msgid "Manual" +msgstr "" + +#: ../../WPrefs.app/WindowHandling.c:91 +msgid "Cascade" +msgstr "Çağlayan" + +#: ../../WPrefs.app/WindowHandling.c:92 +msgid "Smart" +msgstr "Akıllı" + +#: ../../WPrefs.app/WindowHandling.c:100 +msgid "...changes its position (normal behavior)" +msgstr "... konumunu değiştiriyor (normal davranış)" + +#: ../../WPrefs.app/WindowHandling.c:101 +msgid "...restores its unmaximized geometry" +msgstr "... eşsiz geometrisini geri yüklüyor" + +#: ../../WPrefs.app/WindowHandling.c:102 +msgid "...considers the window now unmaximized" +msgstr "... pencerenin şimdi belirsiz olduğunu düşünüyor" + +#: ../../WPrefs.app/WindowHandling.c:103 +msgid "...does not move the window" +msgstr "... pencereyi hareket ettirmiyor" + +#: ../../WPrefs.app/WindowHandling.c:178 ../../WPrefs.app/WindowHandling.c:194 +#, c-format +msgid "bad option value %s in WindowPlacement. Using default value" +msgstr "" +"WindowPlacement'da %s hatalı seçenek değeri. Varsayılan değeri kullanma" + +#: ../../WPrefs.app/WindowHandling.c:214 +msgid "invalid data in option WindowPlaceOrigin. Using default (0,0)" +msgstr "" +"WindowPlaceOrigin seçeneğinde geçersiz veriler. Varsayılan (0,0) kullanılması" + +#: ../../WPrefs.app/WindowHandling.c:310 +msgid "Window Placement" +msgstr "Pencere Yerleşimi" + +#: ../../WPrefs.app/WindowHandling.c:311 +msgid "" +"How to place windows when they are first put\n" +"on screen." +msgstr "Pencereleri ilk kez ekrana yerleştirildiklerinde yerleştirme." + +#: ../../WPrefs.app/WindowHandling.c:325 +msgid "Origin:" +msgstr "Menşei:" + +#: ../../WPrefs.app/WindowHandling.c:406 +msgid "Opaque Move/Resize" +msgstr "Opak Taşı / Yeniden Boyutlandır" + +#: ../../WPrefs.app/WindowHandling.c:407 +msgid "" +"Whether the window contents or only a frame should\n" +"be displayed during a move or resize.\n" +msgstr "" +"Taşıma veya yeniden boyutlandırma sırasında pencere içeriğinin veya yalnızca " +"çerçevenin görüntülenip görüntülenmeyeceği.\n" + +#: ../../WPrefs.app/WindowHandling.c:474 +msgid "by keyboard" +msgstr "klavye ile" + +#: ../../WPrefs.app/WindowHandling.c:476 +msgid "" +"When selected, moving or resizing windows\n" +"using keyboard shortcuts will also display its\n" +"content instead of just a frame." +msgstr "" +"Seçildiğinde, klavye kısayollarını kullanarak pencereleri taşımak veya " +"yeniden boyutlandırmak da içeriğini bir çerçeve yerine görüntüler." + +#: ../../WPrefs.app/WindowHandling.c:487 +msgid "When maximizing..." +msgstr "Büyütülürken ..." + +#: ../../WPrefs.app/WindowHandling.c:490 +msgid "...do not cover:" +msgstr "... aşağıdakileri kapsamaz:" + +#: ../../WPrefs.app/WindowHandling.c:497 +msgid "Icons" +msgstr "Simgeler" + +#: ../../WPrefs.app/WindowHandling.c:502 +msgid "The dock" +msgstr "Rıhtım" + +#: ../../WPrefs.app/WindowHandling.c:510 +msgid "Mod+Wheel" +msgstr "Mod + Tekerlek" + +#: ../../WPrefs.app/WindowHandling.c:513 +msgid "Resize increment:" +msgstr "Artışı yeniden boyutlandır:" + +#: ../../WPrefs.app/WindowHandling.c:534 +msgid "Edge Resistance" +msgstr "Kenar Direnci" + +#: ../../WPrefs.app/WindowHandling.c:536 +msgid "" +"Edge resistance will make windows `resist'\n" +"being moved further for the defined threshold\n" +"when moved against other windows or the edges\n" +"of the screen." +msgstr "" +"Kenar direnci, diğer pencerelere veya ekranın kenarlarına taşındığında " +"pencerelerin tanımlanan eşik için daha fazla hareket etmesini sağlayacaktır." + +#: ../../WPrefs.app/WindowHandling.c:555 +msgid "Resist" +msgstr "Direnç" + +#: ../../WPrefs.app/WindowHandling.c:560 +msgid "Attract" +msgstr "Çek" + +#: ../../WPrefs.app/WindowHandling.c:569 +msgid "Dragging a maximized window..." +msgstr "Büyütülmüş bir pencere sürükleniyor ..." + +#: ../../WPrefs.app/WindowHandling.c:598 +msgid "Window Handling Preferences" +msgstr "Pencere İşleme Tercihleri" + +#: ../../WPrefs.app/WindowHandling.c:600 +msgid "" +"Window handling options. Initial placement style\n" +"edge resistance, opaque move etc." +msgstr "" +"Pencere taşıma seçenekleri. İlk yerleştirme stili kenar direnci, opak " +"hareket vb." + +#: ../../WPrefs.app/Workspace.c:118 +msgid "Workspace Navigation" +msgstr "Çalışma Alanında Gezinme" + +#: ../../WPrefs.app/Workspace.c:123 +msgid "Wrap to the first workspace from the last workspace" +msgstr "Son çalışma alanından ilk çalışma alanına sarma" + +#: ../../WPrefs.app/Workspace.c:139 +msgid "Switch workspaces while dragging windows" +msgstr "Pencereleri sürüklerken çalışma alanlarını değiştir" + +#: ../../WPrefs.app/Workspace.c:155 +msgid "Automatically create new workspaces" +msgstr "Otomatik olarak yeni çalışma alanları yarat" + +#. WMSetLabelTextAlignment(panel->posL, WARight); +#: ../../WPrefs.app/Workspace.c:172 +msgid "Position of workspace name display" +msgstr "Çalışma alanı adı görüntüleme konumu" + +#: ../../WPrefs.app/Workspace.c:188 +msgid "Disable" +msgstr "Devre dışı bırak" + +#: ../../WPrefs.app/Workspace.c:190 +msgid "Top" +msgstr "Üst" + +#: ../../WPrefs.app/Workspace.c:191 +msgid "Bottom" +msgstr "Alt" + +#: ../../WPrefs.app/Workspace.c:192 +msgid "Top/Left" +msgstr "Üst / Sol" + +#: ../../WPrefs.app/Workspace.c:193 +msgid "Top/Right" +msgstr "Üst / Sağ" + +#: ../../WPrefs.app/Workspace.c:194 +msgid "Bottom/Left" +msgstr "Alt / Sol" + +#: ../../WPrefs.app/Workspace.c:195 +msgid "Bottom/Right" +msgstr "Alt / Sağ" + +#: ../../WPrefs.app/Workspace.c:224 +msgid "Workspace Preferences" +msgstr "Çalışma Alanı Tercihleri" + +#: ../../WPrefs.app/Workspace.c:226 +msgid "" +"Workspace navigation features\n" +"and workspace name display settings." +msgstr "" +"Çalışma alanı gezinme özellikleri ve çalışma alanı adı görüntüleme ayarları." + +#: ../../WPrefs.app/main.c:62 +#, c-format +msgid "usage: %s [options]\n" +msgstr "kullanım: %s [seçenekler]\n" + +#: ../../WPrefs.app/main.c:63 +msgid "options:" +msgstr "seçenekler:" + +#: ../../WPrefs.app/main.c:64 +msgid " -display <display>\tdisplay to be used" +msgstr "-display <display>\tkullanılacak ekran" + +#: ../../WPrefs.app/main.c:65 +msgid " --version\t\tprint version number and exit" +msgstr " --versiyon\t\tbaskı sürüm numarası ve çıkış" + +#: ../../WPrefs.app/main.c:66 +msgid " --help\t\tprint this message and exit" +msgstr " --help\t\tbu mesajı yazdır ve çık" + +#: ../../WPrefs.app/main.c:120 +#, c-format +msgid "too few arguments for %s" +msgstr "%s için çok az argüman" + +#: ../../WPrefs.app/main.c:142 +msgid "X server does not support locale" +msgstr "X sunucusu yerel ayarı desteklemiyor" + +#: ../../WPrefs.app/main.c:145 +msgid "cannot set locale modifiers" +msgstr "yerel ayar değiştiricileri ayarlanamıyor" + +#: ../../WPrefs.app/main.c:151 +#, c-format +msgid "could not open display %s" +msgstr "%s ekranı açılamadı" + +#: ../../WPrefs.app/main.c:156 +msgid "could not initialize application" +msgstr "uygulama başlatılamadı" + +#: ../../WPrefs.app/xmodifier.c:125 +#, c-format +msgid "%s (0x%x) generates %s which is generated by %s" +msgstr "%s (0x%x) %s tarafından oluşturulan %s üretir" + +#: ../../WPrefs.app/xmodifier.c:129 ../../WPrefs.app/xmodifier.c:134 +#, c-format +msgid "%s (0x%x) generates %s which is nonsensical" +msgstr "%s (0x%x), saçma olmayan %s üretir" + +#: ../../WPrefs.app/xmodifier.c:139 +#, c-format +msgid "%s (0x%x) generates both %s and %s which is nonsensical" +msgstr "%s (0x%x) hem %s hem de %s üretiyor, bu da saçma" + +#: ../../WPrefs.app/xmodifier.c:160 +msgid "XGetModifierMapping returned NULL, there is no modifier or no memory" +msgstr "XGetModifierMapping NULL döndürdü, değiştirici veya bellek yok" + +#: ../../WPrefs.app/xmodifier.c:268 +#, c-format +msgid "%s is being used for both %s and %s" +msgstr "%s, hem %s hem de %s için kullanılıyor"
roblillack/wmaker
f6742662ecac2b696056d6e4ff8bba3bbe1af2a4
Tell git to ignore files created during i18n preparation
diff --git a/.gitignore b/.gitignore index fc76e1c..96eb11c 100644 --- a/.gitignore +++ b/.gitignore @@ -1,126 +1,136 @@ # These files are generated by the AutoTools *Makefile *Makefile.in .deps/ .libs/ INSTALL aclocal.m4 autom4te.cache* compile config-paths.h config.guess config.h config.h.in config.log config.status config.sub configure depcomp install-sh libtool ltmain.sh missing mkinstalldirs stamp-h1 m4/ld-version-script.m4 m4/libtool.m4 m4/ltoptions.m4 m4/ltsugar.m4 m4/ltversion.m4 m4/lt~obsolete.m4 src/wconfig.h # These files are generated by scripts INSTALL-WMAKER README.i18n # These files are compilation stuff *.lo *.o *.la *.a # These are compilation results src/wmaker test/wtest util/convertfonts util/geticonset util/getstyle util/seticons util/setstyle util/wdread util/wdwrite util/wmagnify util/wmaker.inst util/wmgenmenu util/wmiv util/wmmenugen util/wmsetbg util/wmsetup util/wxcopy util/wxpaste wrlib/tests/testdraw wrlib/tests/testgrad wrlib/tests/testrot wrlib/tests/view WINGs/Examples/colorpick WINGs/Examples/connect WINGs/Examples/fontl WINGs/Examples/puzzle WINGs/Examples/server WINGs/Extras/test WINGs/Tests/testmywidget WINGs/Tests/wmfile WINGs/Tests/wmquery WINGs/Tests/wtest WPrefs.app/WPrefs # These files are generated from make rules wrlib/wrlib.pc WINGs/WINGs.pc WINGs/WUtil.pc wrlib/libwraster.map WindowMaker/appearance.menu WindowMaker/menu WindowMaker/menu.bg WindowMaker/menu.fi WindowMaker/menu.fy WindowMaker/menu.hu WindowMaker/menu.ko WindowMaker/menu.nl WindowMaker/menu.ro WindowMaker/menu.sk WindowMaker/menu.zh_TW WindowMaker/plmenu WindowMaker/plmenu.bg WindowMaker/plmenu.es WindowMaker/plmenu.fi WindowMaker/plmenu.fy WindowMaker/plmenu.ja WindowMaker/plmenu.ko WindowMaker/plmenu.nl WindowMaker/plmenu.pl WindowMaker/plmenu.ro WindowMaker/plmenu.sk WindowMaker/plmenu.zh_CN WindowMaker/plmenu.zh_TW WindowMaker/wmmacros WindowMaker/Defaults/WMRootMenu WindowMaker/Defaults/WMState WindowMaker/Defaults/WMWindowAttributes WindowMaker/Defaults/WindowMaker WindowMaker/IconSets/Default.iconset +# These files are generated by the i18n process +/po/WindowMaker.pot +/po/*.mo +/WINGs/po/WINGs.pot +/WINGs/po/*.mo +/WPrefs.app/po/WPrefs.pot +/WPrefs.app/po/*.mo +/util/po/*.pot +/util/po/*.mo + # Some text editors generate backup files *~ .pc
roblillack/wmaker
583f66ec4ebb9c8c8c22d7e80bc0c66763596dee
Turn off automake's warning messages about using GNU make extensions
diff --git a/configure.ac b/configure.ac index 64c9dd6..d8a4c35 100644 --- a/configure.ac +++ b/configure.ac @@ -1,556 +1,556 @@ dnl ============================================================================ dnl dnl Window Maker autoconf input dnl AC_COPYRIGHT([Copyright (c) 2001-2015 The Window Maker Team]) dnl dnl ============================================================================ dnl dnl This program is free software; you can redistribute it and/or modify dnl it under the terms of the GNU General Public License as published by dnl the Free Software Foundation; either version 2 of the License, or dnl (at your option) any later version. dnl dnl This program is distributed in the hope that it will be useful, dnl but WITHOUT ANY WARRANTY; without even the implied warranty of dnl MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the dnl GNU General Public License for more details. dnl dnl You should have received a copy of the GNU General Public License along dnl with this program; see the file COPYING. dnl dnl ============================================================================ dnl dnl Process with: ./autogen.sh dnl Due to a bug in Autoconf 2.68 (apparently a regression), we need at least dnl version 2.68b which includes this patch: dnl http://git.savannah.gnu.org/gitweb/?p=autoconf.git;a=commit;h=2b0d95faef68d7ed7c08b0edb9ff1c38728376fa dnl dnl Because the 2.69 was released only a few month later, let's just ask for it AC_PREREQ([2.69]) dnl Configuration for Autoconf and Automake dnl ======================================= AC_INIT([WindowMaker],[0.95.9],[[email protected]],[WindowMaker],[http://www.windowmaker.org/]) AC_CONFIG_MACRO_DIR([m4]) AC_CONFIG_HEADERS([config.h]) dnl We need the EXTRA_xxx_DEPENDENCIES keyword in Makefiles which have been dnl introduced in the version 1.11.3; because the 1.12 was realeased shortly dnl after, we just ask for it -AM_INIT_AUTOMAKE([1.12 silent-rules]) +AM_INIT_AUTOMAKE([1.12 silent-rules -Wno-portability]) dnl Reference file used by 'configure' to make sure the path to sources is valid AC_CONFIG_SRCDIR([src/WindowMaker.h]) dnl Include at the end of 'config.h', this file is generated by top-level Makefile AH_BOTTOM([@%:@include "config-paths.h"]) dnl libtool library versioning dnl ========================== dnl dnl current dnl revision dnl age dnl dnl 1. Start with version information of ‘0:0:0’ for each libtool library. dnl 2. Update the version information only immediately before a public dnl release of your software. More frequent updates are unnecessary, and dnl only guarantee that the current interface number gets larger faster. dnl 3. If the library source code has changed at all since the last dnl update, then increment revision (‘c:r:a’ becomes ‘c:r+1:a’). dnl 4. If any interfaces have been added, removed, or changed since the dnl last update, increment current, and set revision to 0. dnl 5. If any interfaces have been added since the last public release, dnl then increment age. dnl 6. If any interfaces have been removed or changed since the last dnl public release, then set age to 0. dnl dnl libwraster WRASTER_CURRENT=6 WRASTER_REVISION=0 WRASTER_AGE=0 WRASTER_VERSION=$WRASTER_CURRENT:$WRASTER_REVISION:$WRASTER_AGE AC_SUBST(WRASTER_VERSION) dnl dnl libWINGs WINGS_CURRENT=4 WINGS_REVISION=0 WINGS_AGE=1 WINGS_VERSION=$WINGS_CURRENT:$WINGS_REVISION:$WINGS_AGE AC_SUBST(WINGS_VERSION) dnl dnl libWUtil WUTIL_CURRENT=5 WUTIL_REVISION=0 WUTIL_AGE=0 WUTIL_VERSION=$WUTIL_CURRENT:$WUTIL_REVISION:$WUTIL_AGE AC_SUBST(WUTIL_VERSION) dnl Checks for programs dnl =================== AC_PROG_CC WM_PROG_CC_C11 AC_PROG_LN_S AC_PROG_GCC_TRADITIONAL LT_INIT dnl Debugging Options dnl ================= AC_ARG_ENABLE([debug], [AS_HELP_STRING([--enable-debug], [enable debugging options, @<:@default=no@:>@])], [AS_CASE(["$enableval"], [yes], [debug=yes], [no], [debug=no], [AC_MSG_ERROR([bad value $enableval for --enable-debug])] )], [debug=no]) AS_IF([test "x$debug" = "xyes"], [dnl This flag should have already been detected and added, but if user dnl provided an explicit CFLAGS it may not be the case AS_IF([echo " $CFLAGS " | grep " -g " 2>&1 > /dev/null], [@%:@ Debug symbol already activated], [AX_CFLAGS_GCC_OPTION([-g])]) dnl dnl This flag generally makes debugging nightmarish, remove it if present CFLAGS="`echo "$CFLAGS" | sed -e 's/-fomit-frame-pointer *//' `" dnl dnl Enable internal debug code CPPFLAGS="$CPPFLAGS -DDEBUG" ], [dnl dnl When debug is not enabled, the user probably does not wants to keep dnl assertions in the final program CPPFLAGS="$CPPFLAGS -DNDEBUG" ]) AX_CFLAGS_GCC_OPTION([-Wall]) AX_CFLAGS_GCC_OPTION([-Wextra -Wno-sign-compare]) dnl dnl The use of trampolines cause code that can crash on some secured OS, it is dnl also known to be a source of crash if not used properly, in a more general dnl way it tends to generate binary code that may not be optimal, and it is dnl not compatible with the 'nested-func-to-macro' workaround WM_CFLAGS_CHECK_FIRST([-Wtrampolines], [-Werror=trampolines dnl try to generate an error if possible -Wtrampolines dnl if not, try to fall back to a simple warning ]) dnl AS_IF([test "x$debug" = "xyes"], [dnl When debug is enabled, we try to activate more checks from dnl the compiler. They are on independant check because the dnl macro checks all the options at once, but we may have cases dnl where some options are not supported and we don't want to dnl loose all of them. dnl dnl clang, suggest parenthesis on bit operations that could be dnl misunderstood due to C operator precedence AX_CFLAGS_GCC_OPTION([-Wbitwise-op-parentheses]) dnl dnl Points at code that gcc thinks is so complicated that gcc dnl gives up trying to optimize, which probably also means it is dnl too complicated to maintain AX_CFLAGS_GCC_OPTION([-Wdisabled-optimization]) dnl dnl Because of C's type promotion, the compiler has to generate dnl less optimal code when a double constant is used in a dnl float expression AX_CFLAGS_GCC_OPTION([-Wdouble-promotion]) dnl dnl Floating-point comparison is not a good idea AX_CFLAGS_GCC_OPTION([-Wfloat-equal]) dnl dnl clang warns about constants that may have portability issues due dnl to the endianness of the host AX_CFLAGS_GCC_OPTION([-Wfour-char-constants]) dnl dnl clang warns about constant that may be too big to be portable AX_CFLAGS_GCC_OPTION([-Wliteral-range]) dnl dnl Try to report misuses of '&' versus '&&' and similar AX_CFLAGS_GCC_OPTION([-Wlogical-op]) dnl dnl clang, reports cases where the code assumes everyone is an dnl expert in C operator precedence... which is unlikely! AX_CFLAGS_GCC_OPTION([-Wlogical-op-parentheses]) dnl dnl Reports declaration of global things that are done inside dnl a local environment, instead of using the appropriate dnl header AX_CFLAGS_GCC_OPTION([-Wnested-externs]) dnl dnl Warn about constant strings that could pose portability issues AX_CFLAGS_GCC_OPTION([-Woverlength-strings]) dnl dnl Use of 'sizeof()' on inappropriate pointer types AX_CFLAGS_GCC_OPTION([-Wpointer-arith]) dnl dnl Having more than 1 prototype for a function makes code updates dnl more difficult, so try to avoid it AX_CFLAGS_GCC_OPTION([-Wredundant-decls]) dnl dnl clang, detect some misuses of sizeof. We also count in our code dnl on the use of the macro 'wlength' which contains a check if the dnl compiler support C11's static_assert AX_CFLAGS_GCC_OPTION([-Wsizeof-array-argument]) dnl dnl Prototype of function must be explicit, no deprecated K&R syntax dnl and no empty argument list which prevents compiler from doing dnl type checking when using the function WM_CFLAGS_GCC_OPTION_STRICTPROTO dnl dnl Proper attributes helps the compiler to produce better code WM_CFLAGS_CHECK_FIRST([format attribute suggest], [-Wsuggest-attribute=format dnl new gcc syntax -Wmissing-format-attribute dnl old gcc syntax, clang ]) WM_CFLAGS_CHECK_FIRST([no-return attribute suggest], [-Wsuggest-attribute=noreturn dnl gcc syntax -Wmissing-noreturn dnl clang syntax ]) dnl dnl GCC provides a couple of checks to detect incorrect macro uses AX_CFLAGS_GCC_OPTION([-Wundef]) WM_CFLAGS_GCC_OPTION_UNUSEDMACROS dnl dnl clang reports stuff marked unused but which is actually used AX_CFLAGS_GCC_OPTION([-Wused-but-marked-unused]) ], [dnl dnl When debug not enabled, we try to avoid some non-necessary dnl messages from the compiler dnl dnl To support legacy X servers, we have sometime to use dnl functions marked as deprecated. We do not wish our users dnl to be worried about it AX_CFLAGS_GCC_OPTION([-Wno-deprecated]) AX_CFLAGS_GCC_OPTION([-Wno-deprecated-declarations]) ]) dnl Support for Nested Functions by the compiler dnl ============================================ WM_PROG_CC_NESTEDFUNC dnl Posix thread dnl ============ dnl they are used by util/wmiv AX_PTHREAD dnl Tracking on what is detected for final status dnl ============================================= unsupported="" supported_core="" supported_xext="" supported_gfx="" dnl Platform-specific Makefile setup dnl ================================ AS_CASE(["$host"], [*-*-linux*|*-*-cygwin*|*-gnu*], [WM_OSDEP="linux" ; CPPFLAGS="$CPPFLAGS -D_XOPEN_SOURCE=600"], [*-*-freebsd*|*-k*bsd-gnu*], [WM_OSDEP="bsd" ; CPPFLAGS="$CPPFLAGS -D_XOPEN_SOURCE=600 -DFREEBSD"], [*-*-netbsd*], [WM_OSDEP="bsd" ; CPPFLAGS="$CPPFLAGS -DNETBSD"], [*-*-openbsd*], [WM_OSDEP="bsd" ; CPPFLAGS="$CPPFLAGS -DOPENBSD"], [*-*-dragonfly*], [WM_OSDEP="bsd" ; CPPFLAGS="$CPPFLAGS -DDRAGONFLYBSD"], [*-apple-darwin*], [WM_OSDEP="darwin"], [*-*-solaris*], [WM_OSDEP="stub"], dnl solaris.c when done [WM_OSDEP="stub"]) AM_CONDITIONAL([WM_OSDEP_LINUX], [test "x$WM_OSDEP" = "xlinux"]) AM_CONDITIONAL([WM_OSDEP_BSD], [test "x$WM_OSDEP" = "xbsd"]) AM_CONDITIONAL([WM_OSDEP_DARWIN], [test "x$WM_OSDEP" = "xdarwin"]) AM_CONDITIONAL([WM_OSDEP_GENERIC], [test "x$WM_OSDEP" = "xstub"]) dnl the prefix dnl ========== dnl dnl move this earlier in the script... anyone know why this is handled dnl in such a bizarre way? test "x$prefix" = xNONE && prefix=$ac_default_prefix dnl Let make expand exec_prefix. test "x$exec_prefix" = xNONE && exec_prefix='${prefix}' _bindir=`eval echo $bindir` _bindir=`eval echo $_bindir` _libdir=`eval echo $libdir` _libdir=`eval echo $_libdir` dnl =============================================== dnl Specify paths to look for libraries and headers dnl =============================================== AC_ARG_WITH(libs-from, AS_HELP_STRING([--with-libs-from], [pass compiler flags to look for libraries]), [lib_search_path="$withval"], [lib_search_path='-L${libdir}']) AC_ARG_WITH(incs-from, AS_HELP_STRING([--with-incs-from], [pass compiler flags to look for header files]), [inc_search_path="$withval"], [inc_search_path='-I${includedir}']) dnl Features Configuration dnl ====================== AC_ARG_ENABLE([animations], [AS_HELP_STRING([--disable-animations], [disable permanently animations @<:@default=enabled@:>@])], [AS_CASE(["$enableval"], [yes|no], [], [AC_MSG_ERROR([bad value $enableval for --enable-animations])])], [enable_animations="yes"]) AS_IF([test "x$enable_animations" = "xno"], [unsupported="$unsupported Animations"], [AC_DEFINE([USE_ANIMATIONS], [1], [Defined when user did not request to disable animations]) supported_core="$supported_core Animations"]) AC_ARG_ENABLE([mwm-hints], [AS_HELP_STRING([--disable-mwm-hints], [disable support for Motif WM hints @<:@default=enabled@:>@])], [AS_CASE(["$enableval"], [yes|no], [], [AC_MSG_ERROR([bad value $enableval for --enable-mwm-hints])])], [enable_mwm_hints="yes"]) AS_IF([test "x$enable_mwm_hints" = "xno"], [unsupported="$unsupported MWMHints"], [AC_DEFINE([USE_MWM_HINTS], [1], [Defined when used did not request to disable Motif WM hints]) supported_core="$supported_core MWMHints"]) AM_CONDITIONAL([USE_MWM_HINTS], [test "x$enable_mwm_hints" != "xno"]) dnl Boehm GC dnl ======== AC_ARG_ENABLE([boehm-gc], [AS_HELP_STRING([--enable-boehm-gc], [use Boehm GC instead of the default libc malloc() [default=no]])], [AS_CASE(["$enableval"], [yes], [with_boehm_gc=yes], [no], [with_boehm_gc=no], [AC_MSG_ERROR([bad value $enableval for --enable-boehm-gc])] )], [with_boehm_gc=no]) AS_IF([test "x$with_boehm_gc" = "xyes"], AC_SEARCH_LIBS([GC_malloc], [gc], [AC_DEFINE(USE_BOEHM_GC, 1, [Define if Boehm GC is to be used])], [AC_MSG_FAILURE([--enable-boehm-gc specified but test for libgc failed])])) dnl LCOV dnl ==== AC_ARG_ENABLE([lcov], [AS_HELP_STRING([--enable-lcov[=output-directory]], [enable coverage data generation using LCOV (GCC only) [default=no]])], [], [enable_lcov=no]) AS_IF([test "x$enable_lcov" != "xno"], [AX_CFLAGS_GCC_OPTION(-fprofile-arcs -ftest-coverage) AS_IF([test "x$enable_lcov" = "xyes"], [lcov_output_directory="coverage-report"], [lcov_output_directory="${enable_lcov}/coverage-report"]) AC_SUBST(lcov_output_directory)]) AM_CONDITIONAL([USE_LCOV], [test "x$enable_lcov" != "xno"]) dnl ============================ dnl Checks for library functions dnl ============================ AC_FUNC_MEMCMP AC_FUNC_VPRINTF WM_FUNC_SECURE_GETENV AC_CHECK_FUNCS(gethostname select poll strcasecmp strncasecmp \ setsid mallinfo mkstemp sysconf) AC_SEARCH_LIBS([strerror], [cposix]) dnl nanosleep is generally available in standard libc, although not always the dnl case. One known example is Solaris which needs -lrt AC_SEARCH_LIBS([nanosleep], [rt], [], [AC_MSG_ERROR([function 'nanosleep' not found, please report to [email protected]])]) dnl the flag 'O_NOFOLLOW' for 'open' is used in WINGs WM_FUNC_OPEN_NOFOLLOW dnl Check for strlcat/strlcpy dnl ========================= AC_ARG_WITH([libbsd], [AS_HELP_STRING([--without-libbsd], [do not use libbsd for strlcat and strlcpy [default=check]])], [AS_IF([test "x$with_libbsd" != "xno"], [with_libbsd=bsd] [with_libbsd=] )], [with_libbsd=bsd]) tmp_libs=$LIBS AC_SEARCH_LIBS([strlcat],[$with_libbsd], [AC_DEFINE(HAVE_STRLCAT, 1, [Define if strlcat is available])], [], [] ) AC_SEARCH_LIBS([strlcpy],[$with_libbsd], [AC_DEFINE(HAVE_STRLCAT, 1, [Define if strlcpy is available])], [], [] ) LIBS=$tmp_libs LIBBSD= AS_IF([test "x$ac_cv_search_strlcat" = "x-lbsd" -o "x$ac_cv_search_strlcpy" = "x-lbsd"], [LIBBSD=-lbsd AC_CHECK_HEADERS([bsd/string.h])] ) AC_SUBST(LIBBSD) dnl Check for OpenBSD kernel memory interface - kvm(3) dnl ================================================== AS_IF([test "x$WM_OSDEP" = "xbsd"], AC_SEARCH_LIBS([kvm_openfiles], [kvm]) ) dnl Check for inotify dnl ================= dnl It is used by WindowMaker to reload automatically the configuration when the dnl user changed it using WPref or wdwrite AC_CHECK_HEADERS([sys/inotify.h], [AC_DEFINE([HAVE_INOTIFY], [1], [Check for inotify])]) dnl Check for syslog dnl ================ dnl It is used by WUtil to log the wwarning, werror and wfatal AC_CHECK_HEADERS([syslog.h], [AC_DEFINE([HAVE_SYSLOG], [1], [Check for syslog])]) dnl Checks for header files dnl ======================= AC_HEADER_SYS_WAIT AC_HEADER_TIME AC_CHECK_HEADERS(fcntl.h limits.h sys/ioctl.h libintl.h poll.h malloc.h ctype.h \ string.h strings.h) dnl Checks for typedefs, structures, and compiler characteristics dnl ============================================================= AC_C_CONST AC_C_INLINE WM_C_NORETURN AC_TYPE_SIZE_T AC_TYPE_PID_T WM_TYPE_SIGNAL dnl pkg-config dnl ========== PKG_PROG_PKG_CONFIG AS_IF([test -z "$PKG_CONFIG"],[AC_MSG_ERROR([pkg-config is required.])]) dnl Internationalization dnl ==================== dnl Detect the language for translations to be installed and check dnl that the gettext environment works WM_I18N_LANGUAGES WM_I18N_XGETTEXT WM_I18N_MENUTEXTDOMAIN dnl =========================================== dnl Stuff that uses X dnl =========================================== AC_PATH_XTRA AS_IF([test "x$no_x" = "xyes"], [AC_MSG_ERROR([The path for the X11 files not found! Make sure you have X and its headers and libraries (the -devel packages in Linux) installed.])]) X_LIBRARY_PATH=$x_libraries XCFLAGS="$X_CFLAGS" XLFLAGS="$X_LIBS" XLIBS="-lX11 $X_EXTRA_LIBS" lib_search_path="$lib_search_path $XLFLAGS" inc_search_path="$inc_search_path $XCFLAGS" AC_SUBST(X_LIBRARY_PATH) dnl Decide which locale function to use, setlocale() or _Xsetlocale() dnl by MANOME Tomonori dnl =========================================== WM_I18N_XLOCALE dnl Check whether XInternAtoms() exist dnl ================================== AC_CHECK_LIB([X11], [XInternAtoms], [AC_DEFINE([HAVE_XINTERNATOMS], [1], [define if your X server has XInternAtoms() (set by configure)])], [], [$XLFLAGS $XLIBS]) dnl Check whether XConvertCase() exist dnl ================================== AC_CHECK_LIB([X11], [XConvertCase], [AC_DEFINE([HAVE_XCONVERTCASE], [1], [define if your X server has XConvertCase() (set by configure)])], [], [$XLFLAGS $XLIBS]) dnl XKB keyboard language status dnl ============================ AC_ARG_ENABLE([modelock], [AS_HELP_STRING([--enable-modelock], [XKB keyboard language status support])], [AS_CASE([$enableval], [yes|no], [], [AC_MSG_ERROR([bad value '$enableval' for --enable-modelock])])], [enable_modelock=no]) AS_IF([test "x$enable_modelock" = "xyes"], [AC_DEFINE([XKB_MODELOCK], [1], [whether XKB language MODELOCK should be enabled]) ]) dnl XDND Drag-nd-Drop support dnl ========================= AC_ARG_ENABLE([xdnd], [AS_HELP_STRING([--disable-xdnd], [disable support for Drag-and-Drop on the dock @<:@default=enabled@:>@])], [AS_CASE(["$enableval"], [yes|no], [], [AC_MSG_ERROR([bad value $enableval for --disable-xdnd]) ]) ], [enable_xdnd=yes]) AS_IF([test "x$enable_xdnd" = "xyes"], [supported_core="$supported_core XDnD" AC_DEFINE([USE_DOCK_XDND], [1], [whether Drag-and-Drop on the dock should be enabled])], [unsupported="$unsupported XDnd"]) AM_CONDITIONAL([USE_DOCK_XDND], [test "x$enable_xdnd" != "xno"]) dnl Support for ICCCM 2.0 Window Manager replacement dnl ================================================ AC_ARG_ENABLE([wmreplace], [AS_HELP_STRING([--enable-wmreplace], [support for ICCCM window manager replacement])], [AS_CASE([$enableval], [yes|no], [], [AC_MSG_ERROR([bad value '$enableval' for --enable-wmreplace])])], [enable_wmreplace=no]) AS_IF([test "x$enable_wmreplace" = "xyes"], [AC_DEFINE([USE_ICCCM_WMREPLACE], [1], [define to support ICCCM protocol for window manager replacement]) supported_xext="$supported_xext WMReplace"]) dnl XShape support dnl ============== AC_ARG_ENABLE([shape], [AS_HELP_STRING([--disable-shape], [disable shaped window extension support])], [AS_CASE(["$enableval"], [yes|no], [], [AC_MSG_ERROR([bad value $enableval for --enable-shape]) ]) ], [enable_shape=auto]) WM_XEXT_CHECK_XSHAPE dnl MIT-SHM support
roblillack/wmaker
230a501d36e098867d4c6f692f6c9c9102ffa899
Fix typo on defining imagemagick version.
diff --git a/m4/wm_imgfmt_check.m4 b/m4/wm_imgfmt_check.m4 index 2236e6c..6f9ecc4 100644 --- a/m4/wm_imgfmt_check.m4 +++ b/m4/wm_imgfmt_check.m4 @@ -1,336 +1,336 @@ # wm_imgfmt_check.m4 - Macros to check for image file format support libraries # # Copyright (c) 2013 Christophe CURIS # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # WM_IMGFMT_CHECK_GIF # ------------------- # # Check for GIF file support through 'libgif', 'libungif' or 'giflib v5' # The check depends on variable 'enable_gif' being either: # yes - detect, fail if not found # no - do not detect, disable support # auto - detect, disable if not found # # When found, append appropriate stuff in GFXLIBS, and append info to # the variable 'supported_gfx' # When not found, append info to variable 'unsupported' AC_DEFUN_ONCE([WM_IMGFMT_CHECK_GIF], [AC_REQUIRE([_WM_LIB_CHECK_FUNCTS]) AS_IF([test "x$enable_gif" = "xno"], [unsupported="$unsupported GIF"], [AC_CACHE_CHECK([for GIF support library], [wm_cv_imgfmt_gif], [wm_cv_imgfmt_gif=no wm_save_LIBS="$LIBS" dnl dnl We check first if one of the known libraries is available for wm_arg in "-lgif" "-lungif" ; do AS_IF([wm_fn_lib_try_link "DGifOpenFileName" "$XLFLAGS $XLIBS $wm_arg"], [wm_cv_imgfmt_gif="$wm_arg" ; break]) done LIBS="$wm_save_LIBS" AS_IF([test "x$enable_gif$wm_cv_imgfmt_gif" = "xyesno"], [AC_MSG_ERROR([explicit GIF support requested but no library found])]) AS_IF([test "x$wm_cv_imgfmt_gif" != "xno"], [dnl dnl A library was found, now check for the appropriate header wm_save_CFLAGS="$CFLAGS" AS_IF([wm_fn_lib_try_compile "gif_lib.h" "" "return 0" ""], [], [AC_MSG_ERROR([found $wm_cv_imgfmt_gif but could not find appropriate header - are you missing libgif-dev package?])]) AS_IF([wm_fn_lib_try_compile "gif_lib.h" 'const char *filename = "dummy";' "DGifOpenFileName(filename)" ""], [wm_cv_imgfmt_gif="$wm_cv_imgfmt_gif version:4"], [AC_COMPILE_IFELSE( [AC_LANG_PROGRAM( [@%:@include <gif_lib.h> const char *filename = "dummy";], [ int error_code; DGifOpenFileName(filename, &error_code);] )], [wm_cv_imgfmt_gif="$wm_cv_imgfmt_gif version:5"], [AC_MSG_ERROR([found $wm_cv_imgfmt_gif and header, but cannot compile - unsupported version?])])dnl ] ) CFLAGS="$wm_save_CFLAGS"]) ]) AS_IF([test "x$wm_cv_imgfmt_gif" = "xno"], [unsupported="$unsupported GIF" enable_gif="no"], [supported_gfx="$supported_gfx GIF" WM_APPEND_ONCE([`echo "$wm_cv_imgfmt_gif" | sed -e 's, *version:.*,,' `], [GFXLIBS]) AC_DEFINE_UNQUOTED([USE_GIF], [`echo "$wm_cv_imgfmt_gif" | sed -e 's,.*version:,,' `], [defined when valid GIF library with header was found])]) ]) AM_CONDITIONAL([USE_GIF], [test "x$enable_gif" != "xno"])dnl ]) dnl AC_DEFUN # WM_IMGFMT_CHECK_JPEG # -------------------- # # Check for JPEG file support through 'libjpeg' # The check depends on variable 'enable_jpeg' being either: # yes - detect, fail if not found # no - do not detect, disable support # auto - detect, disable if not found # # When found, append appropriate stuff in GFXLIBS, and append info to # the variable 'supported_gfx' # When not found, append info to variable 'unsupported' AC_DEFUN_ONCE([WM_IMGFMT_CHECK_JPEG], [WM_LIB_CHECK([JPEG], [-ljpeg], [jpeg_destroy_compress], [$XLFLAGS $XLIBS], [AC_COMPILE_IFELSE( [AC_LANG_PROGRAM( [@%:@include <stdlib.h> @%:@include <stdio.h> @%:@include <jpeglib.h>], [ struct jpeg_decompress_struct cinfo; jpeg_destroy_decompress(&cinfo);])], [], [AS_ECHO([failed]) AS_ECHO(["$as_me: error: found $CACHEVAR but cannot compile header"]) AS_ECHO(["$as_me: error: - does header 'jpeglib.h' exists? (is package 'jpeg-dev' missing?)"]) AS_ECHO(["$as_me: error: - version of header is not supported? (report to dev team)"]) AC_MSG_ERROR([JPEG library is not usable, cannot continue])]) ], [supported_gfx], [GFXLIBS])dnl ]) dnl AC_DEFUN # WM_IMGFMT_CHECK_PNG # ------------------- # # Check for PNG file support through 'libpng' # The check depends on variable 'enable_png' being either: # yes - detect, fail if not found # no - do not detect, disable support # auto - detect, disable if not found # # When found, append appropriate stuff in GFXLIBS, and append info to # the variable 'supported_gfx' # When not found, append info to variable 'unsupported' AC_DEFUN_ONCE([WM_IMGFMT_CHECK_PNG], [WM_LIB_CHECK([PNG], ["-lpng" "-lpng -lz" "-lpng -lz -lm"], [png_get_valid], [$XLFLAGS $XLIBS], [wm_save_CFLAGS="$CFLAGS" AS_IF([wm_fn_lib_try_compile "png.h" "" "return 0" ""], [], [AC_MSG_ERROR([found $CACHEVAR but could not find appropriate header - are you missing libpng-dev package?])]) AS_IF([wm_fn_lib_try_compile "png.h" "" "png_get_valid(NULL, NULL, PNG_INFO_tRNS)" ""], [], [AC_MSG_ERROR([found $CACHEVAR and header, but cannot compile - unsupported version?])]) CFLAGS="$wm_save_CFLAGS"], [supported_gfx], [GFXLIBS])dnl ]) dnl AC_DEFUN # WM_IMGFMT_CHECK_TIFF # -------------------- # # Check for TIFF file support through 'libtiff' # The check depends on variable 'enable_tiff' being either: # yes - detect, fail if not found # no - do not detect, disable support # auto - detect, disable if not found # # When found, append appropriate stuff in GFXLIBS, and append info to # the variable 'supported_gfx' # When not found, append info to variable 'unsupported' AC_DEFUN_ONCE([WM_IMGFMT_CHECK_TIFF], [WM_LIB_CHECK([TIFF], ["-ltiff" \ dnl TIFF can have a dependancy over zlib "-ltiff -lz" "-ltiff -lz -lm" \ dnl It may also have a dependancy to jpeg_lib "-ltiff -ljpeg" "-ltiff -ljpeg -lz" "-ltiff -ljpeg -lz -lm" \ dnl There is also a possible dependancy on JBIGKit "-ltiff -ljpeg -ljbig -lz" \ dnl Probably for historical reasons? "-ltiff34" "-ltiff34 -ljpeg" "-ltiff34 -ljpeg -lm"], [TIFFGetVersion], [$XLFLAGS $XLIBS], [wm_save_CFLAGS="$CFLAGS" AS_IF([wm_fn_lib_try_compile "tiffio.h" "" "return 0" ""], [], [AC_MSG_ERROR([found $CACHEVAR but could not find appropriate header - are you missing libtiff-dev package?])]) AS_IF([wm_fn_lib_try_compile "tiffio.h" 'const char *filename = "dummy";' 'TIFFOpen(filename, "r")' ""], [], [AC_MSG_ERROR([found $CACHEVAR and header, but cannot compile - unsupported version?])]) CFLAGS="$wm_save_CFLAGS"], [supported_gfx], [GFXLIBS])dnl ]) dnl AC_DEFUN # WM_IMGFMT_CHECK_WEBP # -------------------- # # Check for WEBP file support through 'libwebp' # The check depends on variable 'enable_webp' being either: # yes - detect, fail if not found # no - do not detect, disable support # auto - detect, disable if not found # # When found, append appropriate stuff in GFXLIBS, and append info to # the variable 'supported_gfx' # When not found, append info to variable 'unsupported' AC_DEFUN_ONCE([WM_IMGFMT_CHECK_WEBP], [AS_IF([test "x$enable_webp" = "xno"], [unsupported="$unsupported WebP"], [AC_CACHE_CHECK([for WebP support library], [wm_cv_imgfmt_webp], [wm_cv_imgfmt_webp=no dnl dnl The library is using a special trick on the functions to provide dnl compatibility between versions, so we cannot try linking against dnl a symbol without first using the header to handle it wm_save_LIBS="$LIBS" LIBS="$LIBS -lwebp" AC_TRY_LINK( [@%:@include <webp/decode.h>], [WebPGetFeatures(NULL, 1024, NULL);], [wm_cv_imgfmt_webp="-lwebp"]) LIBS="$wm_save_LIBS" AS_IF([test "x$enable_webp$wm_cv_imgfmt_webp" = "xyesno"], [AC_MSG_ERROR([explicit WebP support requested but no library found])])dnl ]) AS_IF([test "x$wm_cv_imgfmt_webp" = "xno"], [unsupported="$unsupported WebP" enable_webp="no"], [supported_gfx="$supported_gfx WebP" WM_APPEND_ONCE([$wm_cv_imgfmt_webp], [GFXLIBS])dnl AC_DEFINE([USE_WEBP], [1], [defined when valid Webp library with header was found])])dnl ]) AM_CONDITIONAL([USE_WEBP], [test "x$enable_webp" != "xno"])dnl ]) # WM_IMGFMT_CHECK_XPM # ------------------- # # Check for XPM file support through 'libXpm' # The check depends on variable 'enable_xpm' being either: # yes - detect, fail if not found # no - do not detect, use internal support # auto - detect, use internal if not found # # When found, append appropriate stuff in GFXLIBS, and append info to # the variable 'supported_gfx' AC_DEFUN_ONCE([WM_IMGFMT_CHECK_XPM], [AC_REQUIRE([_WM_LIB_CHECK_FUNCTS]) AS_IF([test "x$enable_xpm" = "xno"], [supported_gfx="$supported_gfx builtin-XPM"], [AC_CACHE_CHECK([for XPM support library], [wm_cv_imgfmt_xpm], [wm_cv_imgfmt_xpm=no dnl dnl We check first if one of the known libraries is available wm_save_LIBS="$LIBS" AS_IF([wm_fn_lib_try_link "XpmCreatePixmapFromData" "$XLFLAGS $XLIBS -lXpm"], [wm_cv_imgfmt_xpm="-lXpm" ; break]) LIBS="$wm_save_LIBS" AS_IF([test "x$enable_xpm$wm_cv_imgfmt_xpm" = "xyesno"], [AC_MSG_ERROR([explicit libXpm support requested but no library found])]) AS_IF([test "x$wm_cv_imgfmt_xpm" != "xno"], [dnl dnl A library was found, now check for the appropriate header wm_save_CFLAGS="$CFLAGS" AS_IF([wm_fn_lib_try_compile "X11/xpm.h" "" "return 0" "$XCFLAGS"], [], [AC_MSG_ERROR([found $wm_cv_imgfmt_xpm but could not find appropriate header - are you missing libXpm-dev package?])]) AS_IF([wm_fn_lib_try_compile "X11/xpm.h" 'char *filename = "dummy";' 'XpmReadFileToXpmImage(filename, NULL, NULL)' "$XCFLAGS"], [], [AC_MSG_ERROR([found $wm_cv_imgfmt_xpm and header, but cannot compile - unsupported version?])]) CFLAGS="$wm_save_CFLAGS"]) ]) AS_IF([test "x$wm_cv_imgfmt_xpm" = "xno"], [supported_gfx="$supported_gfx builtin-XPM" enable_xpm="no"], [supported_gfx="$supported_gfx XPM" WM_APPEND_ONCE([$wm_cv_imgfmt_xpm], [GFXLIBS]) AC_DEFINE([USE_XPM], [1], [defined when valid XPM library with header was found])]) ]) AM_CONDITIONAL([USE_XPM], [test "x$enable_xpm" != "xno"])dnl ]) dnl AC_DEFUN # WM_IMGFMT_CHECK_MAGICK # ---------------------- # # Check for MagickWand library to support more image file formats # The check depends on variable 'enable_magick' being either: # yes - detect, fail if not found # no - do not detect, disable support # auto - detect, disable if not found # # When found, store the appropriate compilation flags in MAGICKFLAGS # and MAGICKLIBS, and append info to the variable 'supported_gfx' # When not found, append info to variable 'unsupported' AC_DEFUN_ONCE([WM_IMGFMT_CHECK_MAGICK], [AC_REQUIRE([_WM_LIB_CHECK_FUNCTS]) AS_IF([test "x$enable_magick" = "xno"], [unsupported="$unsupported Magick"], [AC_CACHE_CHECK([for Magick support library], [wm_cv_libchk_magick], [wm_cv_libchk_magick=no dnl First try to get the configuration from either pkg-config (the official way) dnl or with the fallback MagickWand-config AS_IF([test "x$PKG_CONFIG" = "x"], [AC_PATH_PROGS_FEATURE_CHECK([magickwand], [MagickWand-config], [wm_cv_libchk_magick_cflags=`$ac_path_magickwand --cflags` wm_cv_libchk_magick_libs=`$ac_path_magickwand --ldflags` wm_cv_libchk_magick=magickwand])], [AS_IF([$PKG_CONFIG --exists MagickWand], [wm_cv_libchk_magick_cflags=`$PKG_CONFIG --cflags MagickWand` wm_cv_libchk_magick_libs=`$PKG_CONFIG --libs MagickWand` wm_cv_libchk_magick=pkgconfig])]) AS_IF([test "x$wm_cv_libchk_magick" = "xno"], [AS_IF([test "x$enable_magick" != "xauto"], [AC_MSG_RESULT([not found]) AC_MSG_ERROR([explicit Magick support requested but configuration not found with pkg-config and MagickWand-config - are you missing libmagickwand-dev package?])])], [dnl The configuration was found, check that it actually works wm_save_LIBS="$LIBS" dnl dnl We check that the library is available AS_IF([wm_fn_lib_try_link "NewMagickWand" "$wm_cv_libchk_magick_libs"], [wm_cv_libchk_magick=maybe]) LIBS="$wm_save_LIBS" AS_IF([test "x$wm_cv_libchk_magick" != "xmaybe"], [AC_MSG_ERROR([MagickWand was found but the library does not link])]) dnl dnl The library was found, check if header is available and compiles wm_save_CFLAGS="$CFLAGS" AS_IF([wm_fn_lib_try_compile "MagickWand/MagickWand.h" "MagickWand *wand;" "wand = NewMagickWand()" "$wm_cv_libchk_magick_cflags"], [wm_cv_libchk_magick="$wm_cv_libchk_magick_cflags % $wm_cv_libchk_magick_libs" - wm_cv_libchk_mgick_version=7], + wm_cv_libchk_magick_version=7], [wm_fn_lib_try_compile "wand/magick_wand.h" "MagickWand *wand;" "wand = NewMagickWand()" "$wm_cv_libchk_magick_cflags"], [wm_cv_libchk_magick="$wm_cv_libchk_magick_cflags % $wm_cv_libchk_magick_libs" wm_cv_libchk_magick_version=6], [AC_MSG_ERROR([found MagickWand library but could not compile its header])]) CFLAGS="$wm_save_CFLAGS"])dnl ]) AS_IF([test "x$wm_cv_libchk_magick" = "xno"], [unsupported="$unsupported Magick" enable_magick="no"], [supported_gfx="$supported_gfx Magick" MAGICKFLAGS=`echo "$wm_cv_libchk_magick" | sed -e 's, *%.*$,,' ` MAGICKLIBS=`echo "$wm_cv_libchk_magick" | sed -e 's,^.*% *,,' ` AC_DEFINE_UNQUOTED([USE_MAGICK], [$wm_cv_libchk_magick_version], [defined when MagickWand library with header was found])]) ]) AM_CONDITIONAL([USE_MAGICK], [test "x$enable_magick" != "xno"])dnl AC_SUBST(MAGICKFLAGS)dnl AC_SUBST(MAGICKLIBS)dnl ]) dnl AC_DEFUN
roblillack/wmaker
3022edd060cef498b957dde02ed38617cc01226b
wrlib: Fix typo in macro containing ImageMagick version
diff --git a/wrlib/load_magick.c b/wrlib/load_magick.c index dbbfe92..876db90 100644 --- a/wrlib/load_magick.c +++ b/wrlib/load_magick.c @@ -1,127 +1,129 @@ /* load_magick.c - load image file using ImageMagick * * Raster graphics library * * Copyright (c) 2014 Window Maker Team * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "config.h" -#if USE_MAGIC < 7 +#ifdef USE_MAGICK +#if USE_MAGICK < 7 #include <wand/magick_wand.h> #else #include <MagickWand/MagickWand.h> #endif +#endif #include "wraster.h" #include "imgformat.h" static int RInitMagickIfNeeded(void); RImage *RLoadMagick(const char *file_name) { RImage *image = NULL; unsigned char *ptr; unsigned long w,h; MagickWand *m_wand = NULL; MagickBooleanType mrc; MagickBooleanType hasAlfa; PixelWand *bg_wand = NULL; if (RInitMagickIfNeeded()) { RErrorCode = RERR_BADFORMAT; return NULL; } /* Create a wand */ m_wand = NewMagickWand(); /* set the default background as transparent */ bg_wand = NewPixelWand(); PixelSetColor(bg_wand, "none"); MagickSetBackgroundColor(m_wand, bg_wand); /* Read the input image */ if (!MagickReadImage(m_wand, file_name)) { RErrorCode = RERR_BADIMAGEFILE; goto bye; } w = MagickGetImageWidth(m_wand); h = MagickGetImageHeight(m_wand); hasAlfa = MagickGetImageAlphaChannel(m_wand); image = RCreateImage(w, h, (unsigned int) hasAlfa); if (!image) { RErrorCode = RERR_NOMEMORY; goto bye; } ptr = image->data; if (hasAlfa == MagickFalse) mrc = MagickExportImagePixels(m_wand, 0, 0, (size_t)w, (size_t)h, "RGB", CharPixel, ptr); else mrc = MagickExportImagePixels(m_wand, 0, 0, (size_t)w, (size_t)h, "RGBA", CharPixel, ptr); if (mrc == MagickFalse) { RErrorCode = RERR_BADIMAGEFILE; RReleaseImage(image); image = NULL; goto bye; } bye: /* Tidy up */ DestroyPixelWand(bg_wand); MagickClearException(m_wand); DestroyMagickWand(m_wand); return image; } /* Track the state of the library in memory */ static enum { MW_NotReady, MW_Ready } magick_state; /* * Initialise MagickWand, but only if it was not already done * * Return ok(0) when MagickWand is usable and fail(!0) if not usable */ static int RInitMagickIfNeeded(void) { if (magick_state == MW_NotReady) { MagickWandGenesis(); magick_state = MW_Ready; } return 0; } void RReleaseMagick(void) { if (magick_state == MW_Ready) { MagickWandTerminus(); magick_state = MW_NotReady; } }
roblillack/wmaker
1713a88656d0bb1a46f7972b381eac2605a04413
debian: Remove ImageMagick patch; an equivalent patch now exists in next
diff --git a/debian/patches/10_support_imagemagick6.diff b/debian/patches/10_support_imagemagick6.diff deleted file mode 100644 index 014b070..0000000 --- a/debian/patches/10_support_imagemagick6.diff +++ /dev/null @@ -1,27 +0,0 @@ -Description: Restore support for ImageMagick v6, as v7 not in Debian. -Origin: https://repo.or.cz/wmaker-crm.git/commitdiff/1dace56 (reversed) -Bug-Debian: https://bugs.debian.org/929825 -Last-Update: 2020-04-05 - ---- a/m4/wm_imgfmt_check.m4 -+++ b/m4/wm_imgfmt_check.m4 -@@ -312,7 +312,7 @@ - dnl - dnl The library was found, check if header is available and compiles - wm_save_CFLAGS="$CFLAGS" -- AS_IF([wm_fn_lib_try_compile "MagickWand/MagickWand.h" "MagickWand *wand;" "wand = NewMagickWand()" "$wm_cv_libchk_magick_cflags"], -+ AS_IF([wm_fn_lib_try_compile "wand/magick_wand.h" "MagickWand *wand;" "wand = NewMagickWand()" "$wm_cv_libchk_magick_cflags"], - [wm_cv_libchk_magick="$wm_cv_libchk_magick_cflags % $wm_cv_libchk_magick_libs"], - [AC_MSG_ERROR([found MagickWand library but could not compile its header])]) - CFLAGS="$wm_save_CFLAGS"])dnl ---- a/wrlib/load_magick.c -+++ b/wrlib/load_magick.c -@@ -22,7 +22,7 @@ - - #include "config.h" - --#include <MagickWand/MagickWand.h> -+#include <wand/MagickWand.h> - - #include "wraster.h" - #include "imgformat.h" diff --git a/debian/patches/series b/debian/patches/series index 2c16510..da2bfa9 100644 --- a/debian/patches/series +++ b/debian/patches/series @@ -1,3 +1,2 @@ -10_support_imagemagick6.diff 53_Debian_WMState.diff 75_WPrefs_to_bindir_when_gnustedir_is_set.diff
roblillack/wmaker
00a25db9ea6168d60e60cfdcb6fb6ba065236802
checkpatch.pl: Escape curly braces in regexes
diff --git a/checkpatch.pl b/checkpatch.pl index 86155bd..eee8d6e 100755 --- a/checkpatch.pl +++ b/checkpatch.pl @@ -1910,1804 +1910,1806 @@ sub process { if (WARN("SPACE_BEFORE_TAB", "please, no space before tabs\n" . $herevet) && $fix) { while ($fixed[$linenr - 1] =~ s/(^\+.*) {8,8}\t/$1\t\t/) {} while ($fixed[$linenr - 1] =~ s/(^\+.*) +\t/$1\t/) {} } } # check for && or || at the start of a line if ($rawline =~ /^\+\s*(&&|\|\|)/) { CHK("LOGICAL_CONTINUATIONS", "Logical continuations should be on the previous line\n" . $hereprev); } # check multi-line statement indentation matches previous line if ($^V && $^V ge 5.10.0 && $prevline =~ /^\+([ \t]*)((?:$c90_Keywords(?:\s+if)\s*)|(?:$Declare\s*)?(?:$Ident|\(\s*\*\s*$Ident\s*\))\s*|$Ident\s*=\s*$Ident\s*)\(.*(\&\&|\|\||,)\s*$/) { $prevline =~ /^\+(\t*)(.*)$/; my $oldindent = $1; my $rest = $2; my $pos = pos_last_openparen($rest); if ($pos >= 0) { $line =~ /^(\+| )([ \t]*)/; my $newindent = $2; my $goodtabindent = $oldindent . "\t" x ($pos / 8) . " " x ($pos % 8); my $goodspaceindent = $oldindent . " " x $pos; if ($newindent ne $goodtabindent && $newindent ne $goodspaceindent) { if (CHK("PARENTHESIS_ALIGNMENT", "Alignment should match open parenthesis\n" . $hereprev) && $fix && $line =~ /^\+/) { $fixed[$linenr - 1] =~ s/^\+[ \t]*/\+$goodtabindent/; } } } } if ($line =~ /^\+.*\*[ \t]*\)[ \t]+(?!$Assignment|$Arithmetic)/) { if (CHK("SPACING", "No space is necessary after a cast\n" . $hereprev) && $fix) { $fixed[$linenr - 1] =~ s/^(\+.*\*[ \t]*\))[ \t]+/$1/; } } # check for spaces at the beginning of a line. # Exceptions: # 1) within comments # 2) indented preprocessor commands # 3) hanging labels if ($rawline =~ /^\+ / && $line !~ /^\+ *(?:$;|#|$Ident:)/) { my $herevet = "$here\n" . cat_vet($rawline) . "\n"; if (WARN("LEADING_SPACE", "please, no spaces at the start of a line\n" . $herevet) && $fix) { $fixed[$linenr - 1] =~ s/^\+([ \t]+)/"\+" . tabify($1)/e; } } # check we are in a valid C source file if not then ignore this hunk next if ($realfile !~ /\.(h|c)$/); # check for RCS/CVS revision markers if ($rawline =~ /^\+.*\$(Revision|Log|Id)(?:\$|)/) { WARN("CVS_KEYWORD", "CVS style keyword markers, these will _not_ be updated\n". $herecurr); } # Check for potential 'bare' types my ($stat, $cond, $line_nr_next, $remain_next, $off_next, $realline_next); #print "LINE<$line>\n"; if ($linenr >= $suppress_statement && $realcnt && $sline =~ /.\s*\S/) { ($stat, $cond, $line_nr_next, $remain_next, $off_next) = ctx_statement_block($linenr, $realcnt, 0); $stat =~ s/\n./\n /g; $cond =~ s/\n./\n /g; #print "linenr<$linenr> <$stat>\n"; # If this statement has no statement boundaries within # it there is no point in retrying a statement scan # until we hit end of it. my $frag = $stat; $frag =~ s/;+\s*$//; if ($frag !~ /(?:{|;)/) { #print "skip<$line_nr_next>\n"; $suppress_statement = $line_nr_next; } # Find the real next line. $realline_next = $line_nr_next; if (defined $realline_next && (!defined $lines[$realline_next - 1] || substr($lines[$realline_next - 1], $off_next) =~ /^\s*$/)) { $realline_next++; } my $s = $stat; $s =~ s/{.*$//s; # Ignore goto labels. if ($s =~ /$Ident:\*$/s) { # Ignore functions being called } elsif ($s =~ /^.\s*$Ident\s*\(/s) { } elsif ($s =~ /^.\s*else\b/s) { # declarations always start with types } elsif ($prev_values eq 'E' && $s =~ /^.\s*(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?((?:\s*$Ident)+?)\b(?:\s+$Sparse)?\s*\**\s*(?:$Ident|\(\*[^\)]*\))(?:\s*$Modifier)?\s*(?:;|=|,|\()/s) { my $type = $1; $type =~ s/\s+/ /g; possible($type, "A:" . $s); # definitions in global scope can only start with types } elsif ($s =~ /^.(?:$Storage\s+)?(?:$Inline\s+)?(?:const\s+)?($Ident)\b\s*(?!:)/s) { possible($1, "B:" . $s); } # any (foo ... *) is a pointer cast, and foo is a type while ($s =~ /\(($Ident)(?:\s+$Sparse)*[\s\*]+\s*\)/sg) { possible($1, "C:" . $s); } # Check for any sort of function declaration. # int foo(something bar, other baz); # void (*store_gdt)(x86_descr_ptr *); if ($prev_values eq 'E' && $s =~ /^(.(?:typedef\s*)?(?:(?:$Storage|$Inline)\s*)*\s*$Type\s*(?:\b$Ident|\(\*\s*$Ident\))\s*)\(/s) { my ($name_len) = length($1); my $ctx = $s; substr($ctx, 0, $name_len + 1, ''); $ctx =~ s/\)[^\)]*$//; for my $arg (split(/\s*,\s*/, $ctx)) { if ($arg =~ /^(?:const\s+)?($Ident)(?:\s+$Sparse)*\s*\**\s*(:?\b$Ident)?$/s || $arg =~ /^($Ident)$/s) { possible($1, "D:" . $s); } } } } # # Checks which may be anchored in the context. # # Check for switch () and associated case and default # statements should be at the same indent. if ($line=~/\bswitch\s*\(.*\)/) { my $err = ''; my $sep = ''; my @ctx = ctx_block_outer($linenr, $realcnt); shift(@ctx); for my $ctx (@ctx) { my ($clen, $cindent) = line_stats($ctx); if ($ctx =~ /^\+\s*(case\s+|default:)/ && $indent != $cindent) { $err .= "$sep$ctx\n"; $sep = ''; } else { $sep = "[...]\n"; } } if ($err ne '') { ERROR("SWITCH_CASE_INDENT_LEVEL", "switch and case should be at the same indent\n$hereline$err"); } } # if/while/etc brace do not go on next line, unless defining a do while loop, # or if that brace on the next line is for something else if ($line =~ /(.*)\b((?:if|while|for|switch)\s*\(|do\b|else\b)/ && $line !~ /^.\s*\#/) { my $pre_ctx = "$1$2"; my ($level, @ctx) = ctx_statement_level($linenr, $realcnt, 0); if ($line =~ /^\+\t{6,}/) { WARN("DEEP_INDENTATION", "Too many leading tabs - consider code refactoring\n" . $herecurr); } my $ctx_cnt = $realcnt - $#ctx - 1; my $ctx = join("\n", @ctx); my $ctx_ln = $linenr; my $ctx_skip = $realcnt; while ($ctx_skip > $ctx_cnt || ($ctx_skip == $ctx_cnt && defined $lines[$ctx_ln - 1] && $lines[$ctx_ln - 1] =~ /^-/)) { ##print "SKIP<$ctx_skip> CNT<$ctx_cnt>\n"; $ctx_skip-- if (!defined $lines[$ctx_ln - 1] || $lines[$ctx_ln - 1] !~ /^-/); $ctx_ln++; } #print "realcnt<$realcnt> ctx_cnt<$ctx_cnt>\n"; #print "pre<$pre_ctx>\nline<$line>\nctx<$ctx>\nnext<$lines[$ctx_ln - 1]>\n"; if ($ctx !~ /{\s*/ && defined($lines[$ctx_ln -1]) && $lines[$ctx_ln - 1] =~ /^\+\s*{/) { ERROR("OPEN_BRACE", "that open brace { should be on the previous line\n" . "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n"); } if ($level == 0 && $pre_ctx !~ /}\s*while\s*\($/ && $ctx =~ /\)\s*\;\s*$/ && defined $lines[$ctx_ln - 1]) { my ($nlength, $nindent) = line_stats($lines[$ctx_ln - 1]); if ($nindent > $indent) { WARN("TRAILING_SEMICOLON", "trailing semicolon indicates no statements, indent implies otherwise\n" . "$here\n$ctx\n$rawlines[$ctx_ln - 1]\n"); } } } # Check relative indent for conditionals and blocks. if ($line =~ /\b(?:(?:if|while|for)\s*\(|do\b)/ && $line !~ /^.\s*#/ && $line !~ /\}\s*while\s*/) { ($stat, $cond, $line_nr_next, $remain_next, $off_next) = ctx_statement_block($linenr, $realcnt, 0) if (!defined $stat); my ($s, $c) = ($stat, $cond); substr($s, 0, length($c), ''); # Make sure we remove the line prefixes as we have # none on the first line, and are going to readd them # where necessary. $s =~ s/\n./\n/gs; # Find out how long the conditional actually is. my @newlines = ($c =~ /\n/gs); my $cond_lines = 1 + $#newlines; # We want to check the first line inside the block # starting at the end of the conditional, so remove: # 1) any blank line termination # 2) any opening brace { on end of the line # 3) any do (...) { my $continuation = 0; my $check = 0; $s =~ s/^.*\bdo\b//; $s =~ s/^\s*{//; if ($s =~ s/^\s*\\//) { $continuation = 1; } if ($s =~ s/^\s*?\n//) { $check = 1; $cond_lines++; } # Also ignore a loop construct at the end of a # preprocessor statement. if (($prevline =~ /^.\s*#\s*define\s/ || $prevline =~ /\\\s*$/) && $continuation == 0) { $check = 0; } my $cond_ptr = -1; $continuation = 0; while ($cond_ptr != $cond_lines) { $cond_ptr = $cond_lines; # If we see an #else/#elif then the code # is not linear. if ($s =~ /^\s*\#\s*(?:else|elif)/) { $check = 0; } # Ignore: # 1) blank lines, they should be at 0, # 2) preprocessor lines, and # 3) labels. if ($continuation || $s =~ /^\s*?\n/ || $s =~ /^\s*#\s*?/ || $s =~ /^\s*$Ident\s*:/) { $continuation = ($s =~ /^.*?\\\n/) ? 1 : 0; if ($s =~ s/^.*?\n//) { $cond_lines++; } } } my (undef, $sindent) = line_stats("+" . $s); my $stat_real = raw_line($linenr, $cond_lines); # Check if either of these lines are modified, else # this is not this patch's fault. if (!defined($stat_real) || $stat !~ /^\+/ && $stat_real !~ /^\+/) { $check = 0; } if (defined($stat_real) && $cond_lines > 1) { $stat_real = "[...]\n$stat_real"; } #print "line<$line> prevline<$prevline> indent<$indent> sindent<$sindent> check<$check> continuation<$continuation> s<$s> cond_lines<$cond_lines> stat_real<$stat_real> stat<$stat>\n"; if ($check && (($sindent % 8) != 0 || ($sindent <= $indent && $s ne ''))) { WARN("SUSPECT_CODE_INDENT", "suspect code indent for conditional statements ($indent, $sindent)\n" . $herecurr . "$stat_real\n"); } } # Track the 'values' across context and added lines. my $opline = $line; $opline =~ s/^./ /; my ($curr_values, $curr_vars) = annotate_values($opline . "\n", $prev_values); $curr_values = $prev_values . $curr_values; if ($dbg_values) { my $outline = $opline; $outline =~ s/\t/ /g; print "$linenr > .$outline\n"; print "$linenr > $curr_values\n"; print "$linenr > $curr_vars\n"; } $prev_values = substr($curr_values, -1); #ignore lines not being added next if ($line =~ /^[^\+]/); # TEST: allow direct testing of the type matcher. if ($dbg_type) { if ($line =~ /^.\s*$Declare\s*$/) { ERROR("TEST_TYPE", "TEST: is type\n" . $herecurr); } elsif ($dbg_type > 1 && $line =~ /^.+($Declare)/) { ERROR("TEST_NOT_TYPE", "TEST: is not type ($1 is)\n". $herecurr); } next; } # TEST: allow direct testing of the attribute matcher. if ($dbg_attr) { if ($line =~ /^.\s*$Modifier\s*$/) { ERROR("TEST_ATTR", "TEST: is attr\n" . $herecurr); } elsif ($dbg_attr > 1 && $line =~ /^.+($Modifier)/) { ERROR("TEST_NOT_ATTR", "TEST: is not attr ($1 is)\n". $herecurr); } next; } # check for initialisation to aggregates open brace on the next line if ($line =~ /^.\s*{/ && $prevline =~ /(?:^|[^=])=\s*$/) { ERROR("OPEN_BRACE", "that open brace { should be on the previous line\n" . $hereprev); } # # Checks which are anchored on the added line. # # check for malformed paths in #include statements (uses RAW line) if ($rawline =~ m{^.\s*\#\s*include\s+[<"](.*)[">]}) { my $path = $1; if ($path =~ m{//}) { ERROR("MALFORMED_INCLUDE", "malformed #include filename\n" . $herecurr); } } # no C99 // comments if ($line =~ m{//}) { if (ERROR("C99_COMMENTS", "do not use C99 // comments\n" . $herecurr) && $fix) { my $line = $fixed[$linenr - 1]; if ($line =~ /\/\/(.*)$/) { my $comment = trim($1); $fixed[$linenr - 1] =~ s@\/\/(.*)$@/\* $comment \*/@; } } } # Remove C99 comments. $line =~ s@//.*@@; $opline =~ s@//.*@@; # check for global initialisers. if ($line =~ /^\+(\s*$Type\s*$Ident\s*(?:\s+$Modifier))*\s*=\s*(0|NULL|false)\s*;/) { if (ERROR("GLOBAL_INITIALISERS", "do not initialise globals to 0 or NULL\n" . $herecurr) && $fix) { $fixed[$linenr - 1] =~ s/($Type\s*$Ident\s*(?:\s+$Modifier))*\s*=\s*(0|NULL|false)\s*;/$1;/; } } # check for static initialisers. if ($line =~ /^\+.*\bstatic\s.*=\s*(0|NULL|false)\s*;/) { if (ERROR("INITIALISED_STATIC", "do not initialise statics to 0 or NULL\n" . $herecurr) && $fix) { $fixed[$linenr - 1] =~ s/(\bstatic\s.*?)\s*=\s*(0|NULL|false)\s*;/$1;/; } } # check for static const char * arrays. if ($line =~ /\bstatic\s+const\s+char\s*\*\s*(\w+)\s*\[\s*\]\s*=\s*/) { WARN("STATIC_CONST_CHAR_ARRAY", "static const char * array should probably be static const char * const\n" . $herecurr); } # check for static char foo[] = "bar" declarations. if ($line =~ /\bstatic\s+char\s+(\w+)\s*\[\s*\]\s*=\s*"/) { WARN("STATIC_CONST_CHAR_ARRAY", "static char array declaration should probably be static const char\n" . $herecurr); } # check for non-global char *foo[] = {"bar", ...} declarations. if ($line =~ /^.\s+(?:static\s+|const\s+)?char\s+\*\s*\w+\s*\[\s*\]\s*=\s*\{/) { WARN("STATIC_CONST_CHAR_ARRAY", "char * array declaration might be better as static const\n" . $herecurr); } # check for function declarations without arguments like "int foo()" if ($line =~ /(\b$Type\s+$Ident)\s*\(\s*\)/) { if (ERROR("FUNCTION_WITHOUT_ARGS", "Bad function definition - $1() should probably be $1(void)\n" . $herecurr) && $fix) { $fixed[$linenr - 1] =~ s/(\b($Type)\s+($Ident))\s*\(\s*\)/$2 $3(void)/; } } # check for new typedefs, only function parameters and sparse annotations # make sense. if ($line =~ /\btypedef\s/ && $line !~ /\btypedef\s+$Type\s*\(\s*\*?$Ident\s*\)\s*\(/ && $line !~ /\btypedef\s+$Type\s+$Ident\s*\(/ && $line !~ /\b$typeTypedefs\b/ && $line !~ /\b__bitwise(?:__|)\b/) { WARN("NEW_TYPEDEFS", "do not add new typedefs\n" . $herecurr); } # * goes on variable not on type # (char*[ const]) while ($line =~ m{(\($NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)\))}g) { #print "AA<$1>\n"; my ($ident, $from, $to) = ($1, $2, $2); # Should start with a space. $to =~ s/^(\S)/ $1/; # Should not end with a space. $to =~ s/\s+$//; # '*'s should not have spaces between. while ($to =~ s/\*\s+\*/\*\*/) { } ## print "1: from<$from> to<$to> ident<$ident>\n"; if ($from ne $to) { if (ERROR("POINTER_LOCATION", "\"(foo$from)\" should be \"(foo$to)\"\n" . $herecurr) && $fix) { my $sub_from = $ident; my $sub_to = $ident; $sub_to =~ s/\Q$from\E/$to/; $fixed[$linenr - 1] =~ s@\Q$sub_from\E@$sub_to@; } } } while ($line =~ m{(\b$NonptrType(\s*(?:$Modifier\b\s*|\*\s*)+)($Ident))}g) { #print "BB<$1>\n"; my ($match, $from, $to, $ident) = ($1, $2, $2, $3); # Should start with a space. $to =~ s/^(\S)/ $1/; # Should not end with a space. $to =~ s/\s+$//; # '*'s should not have spaces between. while ($to =~ s/\*\s+\*/\*\*/) { } # Modifiers should have spaces. $to =~ s/(\b$Modifier$)/$1 /; ## print "2: from<$from> to<$to> ident<$ident>\n"; if ($from ne $to && $ident !~ /^$Modifier$/) { if (ERROR("POINTER_LOCATION", "\"foo${from}bar\" should be \"foo${to}bar\"\n" . $herecurr) && $fix) { my $sub_from = $match; my $sub_to = $match; $sub_to =~ s/\Q$from\E/$to/; $fixed[$linenr - 1] =~ s@\Q$sub_from\E@$sub_to@; } } } # function brace can't be on same line, except for #defines of do while, # or if closed on same line - if (($line=~/$Type\s*$Ident\(.*\).*\s{/) and - !($line=~/\#\s*define.*do\s{/) and !($line=~/}/)) { + if ($line =~ /$Type\s*$Ident\s*$balanced_parens\s*\{/ && + $line !~ /\#\s*define\b.*do\s*\{/ && + $line !~ /}/) { + ERROR("OPEN_BRACE", "open brace '{' following function declarations go on the next line\n" . $herecurr); } # open braces for enum, union and struct go on the same line. if ($line =~ /^.\s*{/ && $prevline =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident)?\s*$/) { ERROR("OPEN_BRACE", "open brace '{' following $1 go on the same line\n" . $hereprev); } # missing space after union, struct or enum definition if ($line =~ /^.\s*(?:typedef\s+)?(enum|union|struct)(?:\s+$Ident){1,2}[=\{]/) { if (WARN("SPACING", "missing space after $1 definition\n" . $herecurr) && $fix) { $fixed[$linenr - 1] =~ s/^(.\s*(?:typedef\s+)?(?:enum|union|struct)(?:\s+$Ident){1,2})([=\{])/$1 $2/; } } # Function pointer declarations # check spacing between type, funcptr, and args # canonical declaration is "type (*funcptr)(args...)" if ($line =~ /^.\s*($Declare)\((\s*)\*(\s*)($Ident)(\s*)\)(\s*)\(/) { my $declare = $1; my $pre_pointer_space = $2; my $post_pointer_space = $3; my $funcname = $4; my $post_funcname_space = $5; my $pre_args_space = $6; # the $Declare variable will capture all spaces after the type # so check it for a missing trailing missing space but pointer return types # don't need a space so don't warn for those. my $post_declare_space = ""; if ($declare =~ /(\s+)$/) { $post_declare_space = $1; $declare = rtrim($declare); } if ($declare !~ /\*$/ && $post_declare_space =~ /^$/) { WARN("SPACING", "missing space after return type\n" . $herecurr); $post_declare_space = " "; } # unnecessary space "type (*funcptr)(args...)" # This test is not currently implemented because these declarations are # equivalent to # int foo(int bar, ...) # and this is form shouldn't/doesn't generate a checkpatch warning. # # elsif ($declare =~ /\s{2,}$/) { # WARN("SPACING", # "Multiple spaces after return type\n" . $herecurr); # } # unnecessary space "type ( *funcptr)(args...)" if (defined $pre_pointer_space && $pre_pointer_space =~ /^\s/) { WARN("SPACING", "Unnecessary space after function pointer open parenthesis\n" . $herecurr); } # unnecessary space "type (* funcptr)(args...)" if (defined $post_pointer_space && $post_pointer_space =~ /^\s/) { WARN("SPACING", "Unnecessary space before function pointer name\n" . $herecurr); } # unnecessary space "type (*funcptr )(args...)" if (defined $post_funcname_space && $post_funcname_space =~ /^\s/) { WARN("SPACING", "Unnecessary space after function pointer name\n" . $herecurr); } # unnecessary space "type (*funcptr) (args...)" if (defined $pre_args_space && $pre_args_space =~ /^\s/) { WARN("SPACING", "Unnecessary space before function pointer arguments\n" . $herecurr); } if (show_type("SPACING") && $fix) { $fixed[$linenr - 1] =~ s/^(.\s*)$Declare\s*\(\s*\*\s*$Ident\s*\)\s*\(/$1 . $declare . $post_declare_space . '(*' . $funcname . ')('/ex; } } # check for spacing round square brackets; allowed: # 1. with a type on the left -- int [] a; # 2. at the beginning of a line for slice initialisers -- [0...10] = 5, # 3. inside a curly brace -- = { [0...10] = 5 } while ($line =~ /(.*?\s)\[/g) { my ($where, $prefix) = ($-[1], $1); if ($prefix !~ /$Type\s+$/ && ($where != 0 || $prefix !~ /^.\s+$/) && $prefix !~ /[{,]\s+$/) { if (ERROR("BRACKET_SPACE", "space prohibited before open square bracket '['\n" . $herecurr) && $fix) { $fixed[$linenr - 1] =~ s/^(\+.*?)\s+\[/$1\[/; } } } # check for spaces between functions and their parentheses. while ($line =~ /($Ident)\s+\(/g) { my $name = $1; my $ctx_before = substr($line, 0, $-[1]); my $ctx = "$ctx_before$name"; # Ignore those directives where spaces _are_ permitted. if ($name =~ /^(?: if|for|while|switch|return|case| volatile|__volatile__| __attribute__|format|__extension__| asm|__asm__)$/x) { # cpp #define statements have non-optional spaces, ie # if there is a space between the name and the open # parenthesis it is simply not a parameter group. } elsif ($ctx_before =~ /^.\s*\#\s*define\s*$/) { # cpp #elif statement condition may start with a ( } elsif ($ctx =~ /^.\s*\#\s*elif\s*$/) { # If this whole things ends with a type its most # likely a typedef for a function. } elsif ($ctx =~ /$Type$/) { } else { if (WARN("SPACING", "space prohibited between function name and open parenthesis '('\n" . $herecurr) && $fix) { $fixed[$linenr - 1] =~ s/\b$name\s+\(/$name\(/; } } } # Check operator spacing. if (!($line=~/\#\s*include/)) { my $fixed_line = ""; my $line_fixed = 0; my $ops = qr{ <<=|>>=|<=|>=|==|!=| \+=|-=|\*=|\/=|%=|\^=|\|=|&=| =>|->|<<|>>|<|>|=|!|~| &&|\|\||,|\^|\+\+|--|&|\||\+|-|\*|\/|%| \?:|\?|: }x; my @elements = split(/($ops|;)/, $opline); my @fix_elements = (); my $off = 0; foreach my $el (@elements) { push(@fix_elements, substr($rawline, $off, length($el))); $off += length($el); } $off = 0; my $blank = copy_spacing($opline); my $last_after = -1; for (my $n = 0; $n < $#elements; $n += 2) { my $good = $fix_elements[$n] . $fix_elements[$n + 1]; ## print("n: <$n> good: <$good>\n"); $off += length($elements[$n]); # Pick up the preceding and succeeding characters. my $ca = substr($opline, 0, $off); my $cc = ''; if (length($opline) >= ($off + length($elements[$n + 1]))) { $cc = substr($opline, $off + length($elements[$n + 1])); } my $cb = "$ca$;$cc"; my $a = ''; $a = 'V' if ($elements[$n] ne ''); $a = 'W' if ($elements[$n] =~ /\s$/); $a = 'C' if ($elements[$n] =~ /$;$/); $a = 'B' if ($elements[$n] =~ /(\[|\()$/); $a = 'O' if ($elements[$n] eq ''); $a = 'E' if ($ca =~ /^\s*$/); my $op = $elements[$n + 1]; my $c = ''; if (defined $elements[$n + 2]) { $c = 'V' if ($elements[$n + 2] ne ''); $c = 'W' if ($elements[$n + 2] =~ /^\s/); $c = 'C' if ($elements[$n + 2] =~ /^$;/); $c = 'B' if ($elements[$n + 2] =~ /^(\)|\]|;)/); $c = 'O' if ($elements[$n + 2] eq ''); $c = 'E' if ($elements[$n + 2] =~ /^\s*\\$/); } else { $c = 'E'; } my $ctx = "${a}x${c}"; my $at = "(ctx:$ctx)"; my $ptr = substr($blank, 0, $off) . "^"; my $hereptr = "$hereline$ptr\n"; # Pull out the value of this operator. my $op_type = substr($curr_values, $off + 1, 1); # Get the full operator variant. my $opv = $op . substr($curr_vars, $off, 1); # Ignore operators passed as parameters. if ($op_type ne 'V' && $ca =~ /\s$/ && $cc =~ /^\s*,/) { # # Ignore comments # } elsif ($op =~ /^$;+$/) { # ; should have either the end of line or a space or \ after it } elsif ($op eq ';') { if ($ctx !~ /.x[WEBC]/ && $cc !~ /^\\/ && $cc !~ /^;/) { if (ERROR("SPACING", "space required after that '$op' $at\n" . $hereptr)) { $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " "; $line_fixed = 1; } } # // is a comment } elsif ($op eq '//') { # : when part of a bitfield } elsif ($opv eq ':B') { # skip the bitfield test for now # No spaces for: # -> } elsif ($op eq '->') { if ($ctx =~ /Wx.|.xW/) { if (ERROR("SPACING", "spaces prohibited around that '$op' $at\n" . $hereptr)) { $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]); if (defined $fix_elements[$n + 2]) { $fix_elements[$n + 2] =~ s/^\s+//; } $line_fixed = 1; } } # , must have a space on the right. } elsif ($op eq ',') { if ($ctx !~ /.x[WEC]/ && $cc !~ /^}/) { if (ERROR("SPACING", "space required after that '$op' $at\n" . $hereptr)) { $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " "; $line_fixed = 1; $last_after = $n; } } # '*' as part of a type definition -- reported already. } elsif ($opv eq '*_') { #warn "'*' is part of type\n"; # unary operators should have a space before and # none after. May be left adjacent to another # unary operator, or a cast } elsif ($op eq '!' || $op eq '~' || $opv eq '*U' || $opv eq '-U' || $opv eq '&U' || $opv eq '&&U') { if ($ctx !~ /[WEBC]x./ && $ca !~ /(?:\)|!|~|\*|-|\&|\||\+\+|\-\-|\{)$/) { if (ERROR("SPACING", "space required before that '$op' $at\n" . $hereptr)) { if ($n != $last_after + 2) { $good = $fix_elements[$n] . " " . ltrim($fix_elements[$n + 1]); $line_fixed = 1; } } } if ($op eq '*' && $cc =~/\s*$Modifier\b/) { # A unary '*' may be const } elsif ($ctx =~ /.xW/) { if (ERROR("SPACING", "space prohibited after that '$op' $at\n" . $hereptr)) { $good = $fix_elements[$n] . rtrim($fix_elements[$n + 1]); if (defined $fix_elements[$n + 2]) { $fix_elements[$n + 2] =~ s/^\s+//; } $line_fixed = 1; } } # unary ++ and unary -- are allowed no space on one side. } elsif ($op eq '++' or $op eq '--') { if ($ctx !~ /[WEOBC]x[^W]/ && $ctx !~ /[^W]x[WOBEC]/) { if (ERROR("SPACING", "space required one side of that '$op' $at\n" . $hereptr)) { $good = $fix_elements[$n] . trim($fix_elements[$n + 1]) . " "; $line_fixed = 1; } } if ($ctx =~ /Wx[BE]/ || ($ctx =~ /Wx./ && $cc =~ /^;/)) { if (ERROR("SPACING", "space prohibited before that '$op' $at\n" . $hereptr)) { $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]); $line_fixed = 1; } } if ($ctx =~ /ExW/) { if (ERROR("SPACING", "space prohibited after that '$op' $at\n" . $hereptr)) { $good = $fix_elements[$n] . trim($fix_elements[$n + 1]); if (defined $fix_elements[$n + 2]) { $fix_elements[$n + 2] =~ s/^\s+//; } $line_fixed = 1; } } # << and >> may either have or not have spaces both sides } elsif ($op eq '<<' or $op eq '>>' or $op eq '&' or $op eq '^' or $op eq '|' or $op eq '+' or $op eq '-' or $op eq '*' or $op eq '/' or $op eq '%') { if ($ctx =~ /Wx[^WCE]|[^WCE]xW/) { if (ERROR("SPACING", "need consistent spacing around '$op' $at\n" . $hereptr)) { $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " "; if (defined $fix_elements[$n + 2]) { $fix_elements[$n + 2] =~ s/^\s+//; } $line_fixed = 1; } } # A colon needs no spaces before when it is # terminating a case value or a label. } elsif ($opv eq ':C' || $opv eq ':L') { if ($ctx =~ /Wx./) { if (ERROR("SPACING", "space prohibited before that '$op' $at\n" . $hereptr)) { $good = rtrim($fix_elements[$n]) . trim($fix_elements[$n + 1]); $line_fixed = 1; } } # All the others need spaces both sides. } elsif ($ctx !~ /[EWC]x[CWE]/) { my $ok = 0; # Ignore email addresses <foo@bar> if (($op eq '<' && $cc =~ /^\S+\@\S+>/) || ($op eq '>' && $ca =~ /<\S+\@\S+$/)) { $ok = 1; } # messages are ERROR, but ?: are CHK if ($ok == 0) { my $msg_type = \&ERROR; $msg_type = \&CHK if (($op eq '?:' || $op eq '?' || $op eq ':') && $ctx =~ /VxV/); if (&{$msg_type}("SPACING", "spaces required around that '$op' $at\n" . $hereptr)) { $good = rtrim($fix_elements[$n]) . " " . trim($fix_elements[$n + 1]) . " "; if (defined $fix_elements[$n + 2]) { $fix_elements[$n + 2] =~ s/^\s+//; } $line_fixed = 1; } } } $off += length($elements[$n + 1]); ## print("n: <$n> GOOD: <$good>\n"); $fixed_line = $fixed_line . $good; } if (($#elements % 2) == 0) { $fixed_line = $fixed_line . $fix_elements[$#elements]; } if ($fix && $line_fixed && $fixed_line ne $fixed[$linenr - 1]) { $fixed[$linenr - 1] = $fixed_line; } } # check for whitespace before a non-naked semicolon if ($line =~ /^\+.*\S\s+;\s*$/) { if (WARN("SPACING", "space prohibited before semicolon\n" . $herecurr) && $fix) { 1 while $fixed[$linenr - 1] =~ s/^(\+.*\S)\s+;/$1;/; } } # check for multiple assignments if ($line =~ /^.\s*$Lval\s*=\s*$Lval\s*=(?!=)/) { CHK("MULTIPLE_ASSIGNMENTS", "multiple assignments should be avoided\n" . $herecurr); } #need space before brace following if, while, etc - if (($line =~ /\(.*\){/ && $line !~ /\($Type\){/) || - $line =~ /do{/) { + if (($line =~ /\(.*\)\{/ && $line !~ /\($Type\)\{/) || + $line =~ /\b(?:else|do)\{/) { if (ERROR("SPACING", "space required before the open brace '{'\n" . $herecurr) && $fix) { - $fixed[$linenr - 1] =~ s/^(\+.*(?:do|\))){/$1 {/; + $fixed[$linenr - 1] =~ s/^(\+.*(?:do|else|\)))\{/$1 {/; } } # closing brace should have a space following it when it has anything # on the line if ($line =~ /}(?!(?:,|;|\)))\S/) { if (ERROR("SPACING", "space required after that close brace '}'\n" . $herecurr) && $fix) { $fixed[$linenr - 1] =~ s/}((?!(?:,|;|\)))\S)/} $1/; } } # check spacing on square brackets if ($line =~ /\[\s/ && $line !~ /\[\s*$/) { if (ERROR("SPACING", "space prohibited after that open square bracket '['\n" . $herecurr) && $fix) { $fixed[$linenr - 1] =~ s/\[\s+/\[/; } } if ($line =~ /\s\]/) { if (ERROR("SPACING", "space prohibited before that close square bracket ']'\n" . $herecurr) && $fix) { $fixed[$linenr - 1] =~ s/\s+\]/\]/; } } # check spacing on parentheses if ($line =~ /\(\s/ && $line !~ /\(\s*(?:\\)?$/ && $line !~ /for\s*\(\s+;/) { if (ERROR("SPACING", "space prohibited after that open parenthesis '('\n" . $herecurr) && $fix) { $fixed[$linenr - 1] =~ s/\(\s+/\(/; } } if ($line =~ /(\s+)\)/ && $line !~ /^.\s*\)/ && $line !~ /for\s*\(.*;\s+\)/ && $line !~ /:\s+\)/) { if (ERROR("SPACING", "space prohibited before that close parenthesis ')'\n" . $herecurr) && $fix) { $fixed[$linenr - 1] =~ s/\s+\)/\)/; } } #goto labels aren't indented, allow a single space however if ($line=~/^.\s+[A-Za-z\d_]+:(?![0-9]+)/ and !($line=~/^. [A-Za-z\d_]+:/) and !($line=~/^.\s+default:/)) { if (WARN("INDENTED_LABEL", "labels should not be indented\n" . $herecurr) && $fix) { $fixed[$linenr - 1] =~ s/^(.)\s+/$1/; } } # return is not a function if (defined($stat) && $stat =~ /^.\s*return(\s*)\(/s) { my $spacing = $1; if ($^V && $^V ge 5.10.0 && $stat =~ /^.\s*return\s*($balanced_parens)\s*;\s*$/) { my $value = $1; $value = deparenthesize($value); if ($value =~ m/^\s*$FuncArg\s*(?:\?|$)/) { ERROR("RETURN_PARENTHESES", "return is not a function, parentheses are not required\n" . $herecurr); } } elsif ($spacing !~ /\s+/) { ERROR("SPACING", "space required before the open parenthesis '('\n" . $herecurr); } } # if statements using unnecessary parentheses - ie: if ((foo == bar)) if ($^V && $^V ge 5.10.0 && $line =~ /\bif\s*((?:\(\s*){2,})/) { my $openparens = $1; my $count = $openparens =~ tr@\(@\(@; my $msg = ""; if ($line =~ /\bif\s*(?:\(\s*){$count,$count}$LvalOrFunc\s*($Compare)\s*$LvalOrFunc(?:\s*\)){$count,$count}/) { my $comp = $4; #Not $1 because of $LvalOrFunc $msg = " - maybe == should be = ?" if ($comp eq "=="); WARN("UNNECESSARY_PARENTHESES", "Unnecessary parentheses$msg\n" . $herecurr); } } # Return of what appears to be an errno should normally be -'ve if ($line =~ /^.\s*return\s*(E[A-Z]*)\s*;/) { my $name = $1; if ($name ne 'EOF' && $name ne 'ERROR') { WARN("USE_NEGATIVE_ERRNO", "return of an errno should typically be -ve (return -$1)\n" . $herecurr); } } # Need a space before open parenthesis after if, while etc if ($line =~ /\b(if|while|for|switch)\(/) { if (ERROR("SPACING", "space required before the open parenthesis '('\n" . $herecurr) && $fix) { $fixed[$linenr - 1] =~ s/\b(if|while|for|switch)\(/$1 \(/; } } # Check for illegal assignment in if conditional -- and check for trailing # statements after the conditional. if ($line =~ /do\s*(?!{)/) { ($stat, $cond, $line_nr_next, $remain_next, $off_next) = ctx_statement_block($linenr, $realcnt, 0) if (!defined $stat); my ($stat_next) = ctx_statement_block($line_nr_next, $remain_next, $off_next); $stat_next =~ s/\n./\n /g; ##print "stat<$stat> stat_next<$stat_next>\n"; if ($stat_next =~ /^\s*while\b/) { # If the statement carries leading newlines, # then count those as offsets. my ($whitespace) = ($stat_next =~ /^((?:\s*\n[+-])*\s*)/s); my $offset = statement_rawlines($whitespace) - 1; $suppress_whiletrailers{$line_nr_next + $offset} = 1; } } if (!defined $suppress_whiletrailers{$linenr} && defined($stat) && defined($cond) && $line =~ /\b(?:if|while|for)\s*\(/ && $line !~ /^.\s*#/) { my ($s, $c) = ($stat, $cond); if ($c =~ /\bif\s*\(.*[^<>!=]=[^=].*/s) { ERROR("ASSIGN_IN_IF", "do not use assignment in if condition\n" . $herecurr); } # Find out what is on the end of the line after the # conditional. substr($s, 0, length($c), ''); $s =~ s/\n.*//g; $s =~ s/$;//g; # Remove any comments if (length($c) && $s !~ /^\s*{?\s*\\*\s*$/ && $c !~ /}\s*while\s*/) { # Find out how long the conditional actually is. my @newlines = ($c =~ /\n/gs); my $cond_lines = 1 + $#newlines; my $stat_real = ''; $stat_real = raw_line($linenr, $cond_lines) . "\n" if ($cond_lines); if (defined($stat_real) && $cond_lines > 1) { $stat_real = "[...]\n$stat_real"; } ERROR("TRAILING_STATEMENTS", "trailing statements should be on next line\n" . $herecurr . $stat_real); } } # Check for bitwise tests written as boolean if ($line =~ / (?: (?:\[|\(|\&\&|\|\|) \s*0[xX][0-9]+\s* (?:\&\&|\|\|) | (?:\&\&|\|\|) \s*0[xX][0-9]+\s* (?:\&\&|\|\||\)|\]) )/x) { WARN("HEXADECIMAL_BOOLEAN_TEST", "boolean test with hexadecimal, perhaps just 1 \& or \|?\n" . $herecurr); } # if and else should not have general statements after it if ($line =~ /^.\s*(?:}\s*)?else\b(.*)/) { my $s = $1; $s =~ s/$;//g; # Remove any comments if ($s !~ /^\s*(?:\sif|(?:{|)\s*\\?\s*$)/) { ERROR("TRAILING_STATEMENTS", "trailing statements should be on next line\n" . $herecurr); } } # if should not continue a brace if ($line =~ /}\s*if\b/) { ERROR("TRAILING_STATEMENTS", "trailing statements should be on next line\n" . $herecurr); } # case and default should not have general statements after them if ($line =~ /^.\s*(?:case\s*.*|default\s*):/g && $line !~ /\G(?: (?:\s*$;*)(?:\s*{)?(?:\s*$;*)(?:\s*\\)?\s*$| \s*return\s+ )/xg) { ERROR("TRAILING_STATEMENTS", "trailing statements should be on next line\n" . $herecurr); } # Check for }<nl>else {, these must be at the same # indent level to be relevant to each other. if ($prevline=~/}\s*$/ and $line=~/^.\s*else\s*/ and $previndent == $indent) { ERROR("ELSE_AFTER_BRACE", "else should follow close brace '}'\n" . $hereprev); } if ($prevline=~/}\s*$/ and $line=~/^.\s*while\s*/ and $previndent == $indent) { my ($s, $c) = ctx_statement_block($linenr, $realcnt, 0); # Find out what is on the end of the line after the # conditional. substr($s, 0, length($c), ''); $s =~ s/\n.*//g; if ($s =~ /^\s*;/) { ERROR("WHILE_AFTER_BRACE", "while should follow close brace '}'\n" . $hereprev); } } #Specific variable tests while ($line =~ m{($Constant|$Lval)}g) { my $var = $1; #gcc binary extension if ($var =~ /^$Binary$/) { if (WARN("GCC_BINARY_CONSTANT", "Avoid gcc v4.3+ binary constant extension: <$var>\n" . $herecurr) && $fix) { my $hexval = sprintf("0x%x", oct($var)); $fixed[$linenr - 1] =~ s/\b$var\b/$hexval/; } } #CamelCase if ($var !~ /^$Constant$/ && $var =~ /[A-Z][a-z]|[a-z][A-Z]/ && #Ignore Page<foo> variants $var !~ /^(?:Clear|Set|TestClear|TestSet|)Page[A-Z]/ && #Ignore SI style variants like nS, mV and dB (ie: max_uV, regulator_min_uA_show) $var !~ /^(?:[a-z_]*?)_?[a-z][A-Z](?:_[a-z_]+)?$/) { while ($var =~ m{($Ident)}g) { my $word = $1; next if ($word !~ /[A-Z][a-z]|[a-z][A-Z]/); if ($check) { seed_camelcase_includes(); if (!$file && !$camelcase_file_seeded) { seed_camelcase_file($realfile); $camelcase_file_seeded = 1; } } if (!defined $camelcase{$word}) { $camelcase{$word} = 1; CHK("CAMELCASE", "Avoid CamelCase: <$word>\n" . $herecurr); } } } } #no spaces allowed after \ in define if ($line =~ /\#\s*define.*\\\s+$/) { if (WARN("WHITESPACE_AFTER_LINE_CONTINUATION", "Whitespace after \\ makes next lines useless\n" . $herecurr) && $fix) { $fixed[$linenr - 1] =~ s/\s+$//; } } # multi-statement macros should be enclosed in a do while loop, grab the # first statement and ensure its the whole macro if its not enclosed # in a known good container if ($realfile !~ m@/vmlinux.lds.h$@ && $line =~ /^.\s*\#\s*define\s*$Ident(\()?/) { my $ln = $linenr; my $cnt = $realcnt; my ($off, $dstat, $dcond, $rest); my $ctx = ''; ($dstat, $dcond, $ln, $cnt, $off) = ctx_statement_block($linenr, $realcnt, 0); $ctx = $dstat; #print "dstat<$dstat> dcond<$dcond> cnt<$cnt> off<$off>\n"; #print "LINE<$lines[$ln-1]> len<" . length($lines[$ln-1]) . "\n"; $dstat =~ s/^.\s*\#\s*define\s+$Ident(?:\([^\)]*\))?\s*//; $dstat =~ s/$;//g; $dstat =~ s/\\\n.//g; $dstat =~ s/^\s*//s; $dstat =~ s/\s*$//s; # Flatten any parentheses and braces while ($dstat =~ s/\([^\(\)]*\)/1/ || $dstat =~ s/\{[^\{\}]*\}/1/ || $dstat =~ s/\[[^\[\]]*\]/1/) { } # Flatten any obvious string concatentation. while ($dstat =~ s/("X*")\s*$Ident/$1/ || $dstat =~ s/$Ident\s*("X*")/$1/) { } my $exceptions = qr{ $Declare| module_param_named| MODULE_PARM_DESC| DECLARE_PER_CPU| DEFINE_PER_CPU| __typeof__\(| union| struct| \.$Ident\s*=\s*| ^\"|\"$ }x; #print "REST<$rest> dstat<$dstat> ctx<$ctx>\n"; if ($dstat ne '' && $dstat !~ /^(?:$Ident|-?$Constant),$/ && # 10, // foo(), $dstat !~ /^(?:$Ident|-?$Constant);$/ && # foo(); $dstat !~ /^[!~-]?(?:$Lval|$Constant)$/ && # 10 // foo() // !foo // ~foo // -foo // foo->bar // foo.bar->baz $dstat !~ /^'X'$/ && # character constants $dstat !~ /$exceptions/ && $dstat !~ /^\.$Ident\s*=/ && # .foo = $dstat !~ /^(?:\#\s*$Ident|\#\s*$Constant)\s*$/ && # stringification #foo $dstat !~ /^do\s*$Constant\s*while\s*$Constant;?$/ && # do {...} while (...); // do {...} while (...) $dstat !~ /^for\s*$Constant$/ && # for (...) $dstat !~ /^for\s*$Constant\s+(?:$Ident|-?$Constant)$/ && # for (...) bar() $dstat !~ /^do\s*{/ && # do {... - $dstat !~ /^\({/ && # ({... + $dstat !~ /^\(\{/ && # ({... $ctx !~ /^.\s*#\s*define\s+TRACE_(?:SYSTEM|INCLUDE_FILE|INCLUDE_PATH)\b/) { $ctx =~ s/\n*$//; my $herectx = $here . "\n"; my $cnt = statement_rawlines($ctx); for (my $n = 0; $n < $cnt; $n++) { $herectx .= raw_line($linenr, $n) . "\n"; } if ($dstat =~ /;/) { ERROR("MULTISTATEMENT_MACRO_USE_DO_WHILE", "Macros with multiple statements should be enclosed in a do - while loop\n" . "$herectx"); } else { ERROR("COMPLEX_MACRO", "Macros with complex values should be enclosed in parenthesis\n" . "$herectx"); } } # check for line continuations outside of #defines, preprocessor #, and asm } else { if ($prevline !~ /^..*\\$/ && $line !~ /^\+\s*\#.*\\$/ && # preprocessor $line !~ /^\+.*\b(__asm__|asm)\b.*\\$/ && # asm $line =~ /^\+.*\\$/) { WARN("LINE_CONTINUATIONS", "Avoid unnecessary line continuations\n" . $herecurr); } } # do {} while (0) macro tests: # single-statement macros do not need to be enclosed in do while (0) loop, # macro should not end with a semicolon if ($^V && $^V ge 5.10.0 && $realfile !~ m@/vmlinux.lds.h$@ && $line =~ /^.\s*\#\s*define\s+$Ident(\()?/) { my $ln = $linenr; my $cnt = $realcnt; my ($off, $dstat, $dcond, $rest); my $ctx = ''; ($dstat, $dcond, $ln, $cnt, $off) = ctx_statement_block($linenr, $realcnt, 0); $ctx = $dstat; $dstat =~ s/\\\n.//g; if ($dstat =~ /^\+\s*#\s*define\s+$Ident\s*${balanced_parens}\s*do\s*{(.*)\s*}\s*while\s*\(\s*0\s*\)\s*([;\s]*)\s*$/) { my $stmts = $2; my $semis = $3; $ctx =~ s/\n*$//; my $cnt = statement_rawlines($ctx); my $herectx = $here . "\n"; for (my $n = 0; $n < $cnt; $n++) { $herectx .= raw_line($linenr, $n) . "\n"; } if (($stmts =~ tr/;/;/) == 1 && $stmts !~ /^\s*(if|while|for|switch)\b/) { WARN("SINGLE_STATEMENT_DO_WHILE_MACRO", "Single statement macros should not use a do {} while (0) loop\n" . "$herectx"); } if (defined $semis && $semis ne "") { WARN("DO_WHILE_MACRO_WITH_TRAILING_SEMICOLON", "do {} while (0) macros should not be semicolon terminated\n" . "$herectx"); } } } # check for redundant bracing round if etc if ($line =~ /(^.*)\bif\b/ && $1 !~ /else\s*$/) { my ($level, $endln, @chunks) = ctx_statement_full($linenr, $realcnt, 1); #print "chunks<$#chunks> linenr<$linenr> endln<$endln> level<$level>\n"; #print "APW: <<$chunks[1][0]>><<$chunks[1][1]>>\n"; if ($#chunks > 0 && $level == 0) { my @allowed = (); my $allow = 0; my $seen = 0; my $herectx = $here . "\n"; my $ln = $linenr - 1; for my $chunk (@chunks) { my ($cond, $block) = @{$chunk}; # If the condition carries leading newlines, then count those as offsets. my ($whitespace) = ($cond =~ /^((?:\s*\n[+-])*\s*)/s); my $offset = statement_rawlines($whitespace) - 1; $allowed[$allow] = 0; #print "COND<$cond> whitespace<$whitespace> offset<$offset>\n"; # We have looked at and allowed this specific line. $suppress_ifbraces{$ln + $offset} = 1; $herectx .= "$rawlines[$ln + $offset]\n[...]\n"; $ln += statement_rawlines($block) - 1; substr($block, 0, length($cond), ''); $seen++ if ($block =~ /^\s*{/); #print "cond<$cond> block<$block> allowed<$allowed[$allow]>\n"; if (statement_lines($cond) > 1) { #print "APW: ALLOWED: cond<$cond>\n"; $allowed[$allow] = 1; } if ($block =~/\b(?:if|for|while)\b/) { #print "APW: ALLOWED: block<$block>\n"; $allowed[$allow] = 1; } if (statement_block_size($block) > 1) { #print "APW: ALLOWED: lines block<$block>\n"; $allowed[$allow] = 1; } $allow++; } if ($seen) { my $sum_allowed = 0; foreach (@allowed) { $sum_allowed += $_; } if ($sum_allowed == 0) { WARN("BRACES", "braces {} are not necessary for any arm of this statement\n" . $herectx); } elsif ($sum_allowed != $allow && $seen != $allow) { CHK("BRACES", "braces {} should be used on all arms of this statement\n" . $herectx); } } } } if (!defined $suppress_ifbraces{$linenr - 1} && $line =~ /\b(if|while|for|else)\b/) { my $allowed = 0; # Check the pre-context. if (substr($line, 0, $-[0]) =~ /(\}\s*)$/) { #print "APW: ALLOWED: pre<$1>\n"; $allowed = 1; } my ($level, $endln, @chunks) = ctx_statement_full($linenr, $realcnt, $-[0]); # Check the condition. my ($cond, $block) = @{$chunks[0]}; #print "CHECKING<$linenr> cond<$cond> block<$block>\n"; if (defined $cond) { substr($block, 0, length($cond), ''); } if (statement_lines($cond) > 1) { #print "APW: ALLOWED: cond<$cond>\n"; $allowed = 1; } if ($block =~/\b(?:if|for|while)\b/) { #print "APW: ALLOWED: block<$block>\n"; $allowed = 1; } if (statement_block_size($block) > 1) { #print "APW: ALLOWED: lines block<$block>\n"; $allowed = 1; } # Check the post-context. if (defined $chunks[1]) { my ($cond, $block) = @{$chunks[1]}; if (defined $cond) { substr($block, 0, length($cond), ''); } if ($block =~ /^\s*\{/) { #print "APW: ALLOWED: chunk-1 block<$block>\n"; $allowed = 1; } } if ($level == 0 && $block =~ /^\s*\{/ && !$allowed) { my $herectx = $here . "\n"; my $cnt = statement_rawlines($block); for (my $n = 0; $n < $cnt; $n++) { $herectx .= raw_line($linenr, $n) . "\n"; } WARN("BRACES", "braces {} are not necessary for single statement blocks\n" . $herectx); } } # check for unnecessary blank lines around braces if (($line =~ /^.\s*}\s*$/ && $prevrawline =~ /^.\s*$/)) { CHK("BRACES", "Blank lines aren't necessary before a close brace '}'\n" . $hereprev); } if (($rawline =~ /^.\s*$/ && $prevline =~ /^..*{\s*$/)) { CHK("BRACES", "Blank lines aren't necessary after an open brace '{'\n" . $hereprev); } # warn about #if 0 if ($line =~ /^.\s*\#\s*if\s+0\b/) { CHK("REDUNDANT_CODE", "if this code is redundant consider removing it\n" . $herecurr); } # check for needless "if (<foo>) fn(<foo>)" uses if ($prevline =~ /\bif\s*\(\s*($Lval)\s*\)/) { my $expr = '\s*\(\s*' . quotemeta($1) . '\s*\)\s*;'; if ($line =~ /\b(kfree|usb_free_urb|debugfs_remove(?:_recursive)?)$expr/) { WARN('NEEDLESS_IF', "$1(NULL) is safe this check is probably not required\n" . $hereprev); } } # check for bad placement of section $InitAttribute (e.g.: __initdata) if ($line =~ /(\b$InitAttribute\b)/) { my $attr = $1; if ($line =~ /^\+\s*static\s+(?:const\s+)?(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*[=;]/) { my $ptr = $1; my $var = $2; if ((($ptr =~ /\b(union|struct)\s+$attr\b/ && ERROR("MISPLACED_INIT", "$attr should be placed after $var\n" . $herecurr)) || ($ptr !~ /\b(union|struct)\s+$attr\b/ && WARN("MISPLACED_INIT", "$attr should be placed after $var\n" . $herecurr))) && $fix) { $fixed[$linenr - 1] =~ s/(\bstatic\s+(?:const\s+)?)(?:$attr\s+)?($NonptrTypeWithAttr)\s+(?:$attr\s+)?($Ident(?:\[[^]]*\])?)\s*([=;])\s*/"$1" . trim(string_find_replace($2, "\\s*$attr\\s*", " ")) . " " . trim(string_find_replace($3, "\\s*$attr\\s*", "")) . " $attr" . ("$4" eq ";" ? ";" : " = ")/e; } } } # check for $InitAttributeData (ie: __initdata) with const if ($line =~ /\bconst\b/ && $line =~ /($InitAttributeData)/) { my $attr = $1; $attr =~ /($InitAttributePrefix)(.*)/; my $attr_prefix = $1; my $attr_type = $2; if (ERROR("INIT_ATTRIBUTE", "Use of const init definition must use ${attr_prefix}initconst\n" . $herecurr) && $fix) { $fixed[$linenr - 1] =~ s/$InitAttributeData/${attr_prefix}initconst/; } } # check for $InitAttributeConst (ie: __initconst) without const if ($line !~ /\bconst\b/ && $line =~ /($InitAttributeConst)/) { my $attr = $1; if (ERROR("INIT_ATTRIBUTE", "Use of $attr requires a separate use of const\n" . $herecurr) && $fix) { my $lead = $fixed[$linenr - 1] =~ /(^\+\s*(?:static\s+))/; $lead = rtrim($1); $lead = "$lead " if ($lead !~ /^\+$/); $lead = "${lead}const "; $fixed[$linenr - 1] =~ s/(^\+\s*(?:static\s+))/$lead/; } } # warn about #ifdefs in C files # if ($line =~ /^.\s*\#\s*if(|n)def/ && ($realfile =~ /\.c$/)) { # print "#ifdef in C files should be avoided\n"; # print "$herecurr"; # $clean = 0; # } # warn about spacing in #ifdefs if ($line =~ /^.\s*\#\s*(ifdef|ifndef|elif)\s\s+/) { if (ERROR("SPACING", "exactly one space required after that #$1\n" . $herecurr) && $fix) { $fixed[$linenr - 1] =~ s/^(.\s*\#\s*(ifdef|ifndef|elif))\s{2,}/$1 /; } } # Check that the storage class is at the beginning of a declaration if ($line =~ /\b$Storage\b/ && $line !~ /^.\s*$Storage\b/) { WARN("STORAGE_CLASS", "storage class should be at the beginning of the declaration\n" . $herecurr) } # check the location of the inline attribute, that it is between # storage class and type. if ($line =~ /\b$Type\s+$Inline\b/ || $line =~ /\b$Inline\s+$Storage\b/) { ERROR("INLINE_LOCATION", "inline keyword should sit between storage class and type\n" . $herecurr); } # Check for __inline__ and __inline, prefer inline if ($realfile !~ m@\binclude/uapi/@ && $line =~ /\b(__inline__|__inline)\b/) { if (WARN("INLINE", "plain inline is preferred over $1\n" . $herecurr) && $fix) { $fixed[$linenr - 1] =~ s/\b(__inline__|__inline)\b/inline/; } } # Check for __attribute__ packed, prefer __packed if ($realfile !~ m@\binclude/uapi/@ && $line =~ /\b__attribute__\s*\(\s*\(.*\bpacked\b/) { WARN("PREFER_PACKED", "__packed is preferred over __attribute__((packed))\n" . $herecurr); } # Check for __attribute__ aligned, prefer __aligned if ($realfile !~ m@\binclude/uapi/@ && $line =~ /\b__attribute__\s*\(\s*\(.*aligned/) { WARN("PREFER_ALIGNED", "__aligned(size) is preferred over __attribute__((aligned(size)))\n" . $herecurr); } # Check for __attribute__ format(printf, prefer __printf if ($realfile !~ m@\binclude/uapi/@ && $line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf/) { if (WARN("PREFER_PRINTF", "__printf(string-index, first-to-check) is preferred over __attribute__((format(printf, string-index, first-to-check)))\n" . $herecurr) && $fix) { $fixed[$linenr - 1] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*printf\s*,\s*(.*)\)\s*\)\s*\)/"__printf(" . trim($1) . ")"/ex; } } # Check for __attribute__ format(scanf, prefer __scanf if ($realfile !~ m@\binclude/uapi/@ && $line =~ /\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\b/) { if (WARN("PREFER_SCANF", "__scanf(string-index, first-to-check) is preferred over __attribute__((format(scanf, string-index, first-to-check)))\n" . $herecurr) && $fix) { $fixed[$linenr - 1] =~ s/\b__attribute__\s*\(\s*\(\s*format\s*\(\s*scanf\s*,\s*(.*)\)\s*\)\s*\)/"__scanf(" . trim($1) . ")"/ex; } } # check for sizeof(&) if ($line =~ /\bsizeof\s*\(\s*\&/) { WARN("SIZEOF_ADDRESS", "sizeof(& should be avoided\n" . $herecurr); } # check for sizeof without parenthesis if ($line =~ /\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/) { if (WARN("SIZEOF_PARENTHESIS", "sizeof $1 should be sizeof($1)\n" . $herecurr) && $fix) { $fixed[$linenr - 1] =~ s/\bsizeof\s+((?:\*\s*|)$Lval|$Type(?:\s+$Lval|))/"sizeof(" . trim($1) . ")"/ex; } } # check for line continuations in quoted strings with odd counts of " if ($rawline =~ /\\$/ && $rawline =~ tr/"/"/ % 2) { WARN("LINE_CONTINUATIONS", "Avoid line continuations in quoted strings\n" . $herecurr); } # Check for misused memsets if ($^V && $^V ge 5.10.0 && defined $stat && $stat =~ /^\+(?:.*?)\bmemset\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\,\s*$FuncArg\s*\)/s) { my $ms_addr = $2; my $ms_val = $7; my $ms_size = $12; if ($ms_size =~ /^(0x|)0$/i) { ERROR("MEMSET", "memset to 0's uses 0 as the 2nd argument, not the 3rd\n" . "$here\n$stat\n"); } elsif ($ms_size =~ /^(0x|)1$/i) { WARN("MEMSET", "single byte memset is suspicious. Swapped 2nd/3rd argument?\n" . "$here\n$stat\n"); } } # typecasts on min/max could be min_t/max_t if ($^V && $^V ge 5.10.0 && defined $stat && $stat =~ /^\+(?:.*?)\b(min|max)\s*\(\s*$FuncArg\s*,\s*$FuncArg\s*\)/) { if (defined $2 || defined $7) { my $call = $1; my $cast1 = deparenthesize($2); my $arg1 = $3; my $cast2 = deparenthesize($7); my $arg2 = $8; my $cast; if ($cast1 ne "" && $cast2 ne "" && $cast1 ne $cast2) { $cast = "$cast1 or $cast2"; } elsif ($cast1 ne "") { $cast = $cast1; } else { $cast = $cast2; } WARN("MINMAX", "$call() should probably be ${call}_t($cast, $arg1, $arg2)\n" . "$here\n$stat\n"); } } # check for naked sscanf if ($^V && $^V ge 5.10.0 && defined $stat && $line =~ /\bsscanf\b/ && ($stat !~ /$Ident\s*=\s*sscanf\s*$balanced_parens/ && $stat !~ /\bsscanf\s*$balanced_parens\s*(?:$Compare)/ && $stat !~ /(?:$Compare)\s*\bsscanf\s*$balanced_parens/)) { my $lc = $stat =~ tr@\n@@; $lc = $lc + $linenr; my $stat_real = raw_line($linenr, 0); for (my $count = $linenr + 1; $count <= $lc; $count++) { $stat_real = $stat_real . "\n" . raw_line($count, 0); } WARN("NAKED_SSCANF", "unchecked sscanf return value\n" . "$here\n$stat_real\n"); } # check for new externs in .h files. if ($realfile =~ /\.h$/ && $line =~ /^\+\s*(extern\s+)$Type\s*$Ident\s*\(/s) { if (CHK("AVOID_EXTERNS", "extern prototypes should be avoided in .h files\n" . $herecurr) && $fix) { $fixed[$linenr - 1] =~ s/(.*)\bextern\b\s*(.*)/$1$2/; } } # check for new externs in .c files. if ($realfile =~ /\.c$/ && defined $stat && $stat =~ /^.\s*(?:extern\s+)?$Type\s+($Ident)(\s*)\(/s) { my $function_name = $1; my $paren_space = $2; my $s = $stat; if (defined $cond) { substr($s, 0, length($cond), ''); } if ($s =~ /^\s*;/ && $function_name ne 'uninitialized_var') { WARN("AVOID_EXTERNS", "externs should be avoided in .c files\n" . $herecurr); } if ($paren_space =~ /\n/) { WARN("FUNCTION_ARGUMENTS", "arguments for function declarations should follow identifier\n" . $herecurr); } } elsif ($realfile =~ /\.c$/ && defined $stat && $stat =~ /^.\s*extern\s+/) { WARN("AVOID_EXTERNS", "externs should be avoided in .c files\n" . $herecurr); } # check for multiple semicolons if ($line =~ /;\s*;\s*$/) { if (WARN("ONE_SEMICOLON", "Statements terminations use 1 semicolon\n" . $herecurr) && $fix) { $fixed[$linenr - 1] =~ s/(\s*;\s*){2,}$/;/g; } } # check for case / default statements not preceeded by break/fallthrough/switch if ($line =~ /^.\s*(?:case\s+(?:$Ident|$Constant)\s*|default):/) { my $has_break = 0; my $has_statement = 0; my $count = 0; my $prevline = $linenr; while ($prevline > 1 && $count < 3 && !$has_break) { $prevline--; my $rline = $rawlines[$prevline - 1]; my $fline = $lines[$prevline - 1]; last if ($fline =~ /^\@\@/); next if ($fline =~ /^\-/); next if ($fline =~ /^.(?:\s*(?:case\s+(?:$Ident|$Constant)[\s$;]*|default):[\s$;]*)*$/); $has_break = 1 if ($rline =~ /fall[\s_-]*(through|thru)/i); next if ($fline =~ /^.[\s$;]*$/); $has_statement = 1; $count++; $has_break = 1 if ($fline =~ /\bswitch\b|\b(?:break\s*;[\s$;]*$|return\b|goto\b|continue\b)/); } if (!$has_break && $has_statement) { WARN("MISSING_BREAK", "Possible switch case/default not preceeded by break or fallthrough comment\n" . $herecurr); } } # check for switch/default statements without a break; if ($^V && $^V ge 5.10.0 && defined $stat && $stat =~ /^\+[$;\s]*(?:case[$;\s]+\w+[$;\s]*:[$;\s]*|)*[$;\s]*\bdefault[$;\s]*:[$;\s]*;/g) { my $ctx = ''; my $herectx = $here . "\n"; my $cnt = statement_rawlines($stat); for (my $n = 0; $n < $cnt; $n++) { $herectx .= raw_line($linenr, $n) . "\n"; } WARN("DEFAULT_NO_BREAK", "switch default: should use break\n" . $herectx); } # check for gcc specific __FUNCTION__ if ($line =~ /\b__FUNCTION__\b/) { if (WARN("USE_FUNC",
roblillack/wmaker
c678580621e38c1869d1b2e65a4b77987d124865
debian: Update with version 0.95.9-2 packaging.
diff --git a/debian/changelog b/debian/changelog index 4736fde..a352802 100644 --- a/debian/changelog +++ b/debian/changelog @@ -1,512 +1,519 @@ +wmaker (0.95.9-2) unstable; urgency=low + + * Ship manpages from as-installed location (debian/tmp) instead of + sourcetree to make dh_missing output more useful. + + -- Andreas Metzler <[email protected]> Sat, 18 Apr 2020 11:30:41 +0200 + wmaker (0.95.9-1) experimental; urgency=low [ Doug Torrance ] * New upstream release. - No longer sets GNUSTEP_USER_ROOT environment variable (Closes: #922284). - Prefers TryExec to Exec when generating menu entries from XDG desktop files (closes: #930674). - Drop patches previously pulled from upstream GIT: 10_util-fix-parsing-of-XDG-menus-with-multiple-groups.patch 11_XDG-menu-categories.patch 12_reference-proplist-menus.patch 60_fix_pkg-config_variable_typo.patch - Unfuzz 75_WPrefs_to_bindir_when_gnustedir_is_set.diff - 54_Debian_wmmacros.diff dropped, main functionality included upstream. * debian/compat - Remove file; compatibility level now handled by debhelper-compat package. * debian/control - Bump Standards-Version to 4.5.0. - Switch Build-Depends on debhelper to debhelper-compat for compatibility level 12. * debian/lib*.symbols - Add Build-Depends-Package fields. * debian/libwings3.symbols - Add new WINGs symbols. * debian/patches/10_support_imagemagick6.diff - New patch; restore support for ImageMagick v6, as v7 is not in Debian yet. * debian/patches/.keepme - Remove unnecessary file; was causing patch-file-present-but-not-mentioned-in-series Lintian warning. * debian/README.Debian - Fix typo. * debian/rules - Remove replacement of #wmdatadir# to $(WMSHAREDIR) in some menu files; this is now done by upstream during build. - Install README's from WindowMaker directory correctly. Avoids package-contains-documentation-outside-usr-share-doc Lintian warning. * debian/wmaker-common.docs - Use wildcard to catch all the README's that have been renamed in d/rules. -- Andreas Metzler <[email protected]> Tue, 14 Apr 2020 18:06:26 +0200 wmaker (0.95.8-3) unstable; urgency=low [ Doug Torrance ] * debian/compat - Bump debhelper compatibility level to 11. * debian/control - Bump versioned dependency on debhelper to >= 11. - Drop automake (>= 1:1.12) from Build-Depends; automake 1.14 is now in oldstable. - Add libmagickwand-6.q16-dev to Build-Depends. - Add libpango1.0-dev to Build-Depends. We have been passing --enable-pango to configure during build since version 0.95.7-1, but it has been failing. - Bump Standards-Version to 4.2.1. - Use https in Homepage. - Update Vcs-* after migration to Salsa. * debian/copyright - Update Format to https. * debian/patches/60_fix_pkg-config_variable_typo.patch - New patch; correctly call pkg-config when building with ImageMagick support. * debian/README.Debian - Add documentation for new FreeDesktop-style menu which replaced the deprecated Debian menu (Closes: #872879). * debian/rules - Add --enable-magick configure option to enable ImageMagick support (Closes: #905608). - Remove --parallel option to dh; default after debhelper 10. * debian/watch - Use https for download link. [ Andreas Metzler ] * Delete trailing whitespace in Debian changelog. (Thanks, lintian) * 75_WPrefs_to_bindir_when_gnustedir_is_set.diff: Install main WPrefs executable to /usr/bin even if --with-gnustepdir is used. Build with --with-gnustepdir=/usr/share/GNUstep (instead of /usr/share/lib/...) and fix references in debian/* accordingly. (LP: #1742842) * Set Rules-Requires-Root: no. -- Andreas Metzler <[email protected]> Thu, 13 Sep 2018 19:16:14 +0200 wmaker (0.95.8-2) unstable; urgency=low [ Doug Torrance ] * Remove and replace the deprecated Debian menu. The list of applications is now generated by the wmmenugen utility (with some patches from upstream's development branch) from .desktop files in /usr/share/applications. This gives a decent approximation of compliance with freedesktop.org's menu standards (Closes: #868431). * Bump Standards-Version to 4.0.1. * Use dh_installwm to register Window Maker with update-alternatives. In particular, we add a new file, debian/wmaker.wm, and a new target, override_dh_installwm, to debian/rules which sets the priority. To accommodate this, we move the manpage from wmaker-common to wmaker. * Bump debhelper compatibility level to 10. * Remove explicit call to dh_autoreconf; enabled by default in debhelper 10. [ Andreas Metzler ] * Handle removal of menu-methods on upgrades (orphaned conffiles) with debian/wmaker{,-common}.maintscript. Remove generated menufiles (etc/GNUstep/Defaults/appearance.menu and /etc/GNUstep/Defaults/menu.hook on upgrades and purge. * Because of the moved manpage (which in turn is needed for using dh_installwm) wmaker breaks/replaces wmaker-common (<< 0.95.8-2~). * Ship our menu as /etc/GNUstep/Defaults/plmenu.Debian and add a symlink to it as /usr/share/WindowMaker/menu.hook to make the menu accessible for upgraded installations. -- Andreas Metzler <[email protected]> Mon, 14 Aug 2017 14:11:24 +0200 wmaker (0.95.8-1) unstable; urgency=low * Upload to unstable. -- Andreas Metzler <[email protected]> Sun, 09 Jul 2017 13:35:24 +0200 wmaker (0.95.8-1~exp2) experimental; urgency=medium [ Doug Torrance ] * debian/debianfiles/Themes/Debian.style - Rename from just "Debian" for consistency with other Window Maker themes. * debian/debianfiles/upgrade-windowmaker-defaults - Delete archaic script. It was intended to help users upgrade Window Maker 15+ years ago when the configuration file syntax was not stable. No longer necessary. * debian/libwings3.symbols - Remove MISSING comment lines. * debian/libwings-dev.examples - New file; install WINGs examples. * debian/libwmaker-dev.install - Install libwmaker pkg-config file. * debian/patches/50_def_config_paths.diff - Remove unnecessary patch. It added /etc/GNUstep/Defaults to the DEF_CONFIG_PATHS macro, but the files needed in the paths referenced in this macro (in particular, menu, autostart, and exitscript) will not be located there. * debian/patches/53_Debian_WMState.diff - Update patch. The path to WPrefs is already set correctly during build; we do not need to set it explicitly. * debian/README.Debian - Remove notes about upgrading from very old (15+ years ago) versions of Window Maker. * debian/watch - Bump to uscan v4 and simplify using new strings. * debian/wmaker.dirs - Remove unnecessary file * debian/wmaker-common.dirs - Remove redundant lines. * debian/wmaker-common.docs - Do not specify installation of debian/copyright; dh_installdocs already installs it by default. * debian/wmaker-common.{docs,install} - Move installation of various README files from dh_install to dh_installdocs. * debian/wmaker-common.install - Simplify by giving directories instead of individual files where possible. * debian/wmaker-common.links - Remove unnecessary file. It created a link which was a workaround for a bug fixed in the latest upstream release. * debian/wmaker-common.maintscript - Sort with wrap-and-sort. * debian/rules - New override_dh_installdocs target; contains code renaming README files from override_dh_install target. [ Andreas Metzler ] * Drop Rodolfo García Peñas from uploaders. - Thanks for your work! Closes: #866854 * 10_util-fix-parsing-of-XDG-menus-with-multiple-groups.patch from upstream GIT next: Fix wmmenugen parsing of XDG menu files with more than one group. [ Doug Torrance / Andreas Metzler ] * Add dependency on wmaker-common (>= ${source:Version}) to libwutil5 and libwings3 to make it possible to use these libraries without wmaker. -- Andreas Metzler <[email protected]> Sat, 08 Jul 2017 11:43:39 +0200 wmaker (0.95.8-1~exp1) experimental; urgency=medium * New upstream release. - Menus may be shaded (Closes: #72038). - Follow window placement rules when placing windows on non-active workspaces (Closes: #181735). - Windows list sorted by workspace (Closes: #280851). - New keyboard shortcuts (Closes: #306808). - Default menu uses correct path to WPrefs (Closes: #851737). - Use PKG_PROG_PKG_CONFIG macro to allow cross building (Closes: #853236). * debian/control - Add xterm to Suggests as it is referenced in the default Window Maker menus (LP: #1429495). * debian/libwraster* - Rename libwraster5 -> libwraster6 for soname version bump. * debian/patches - Remove patches which were either applied or otherwise made unnecessary with the new upstream release. In particular, + 51_wmaker_man.diff + 55_ungif_problem.diff + 56_ignore_runstatedir.diff + 57_ignore_with-aix-soname.diff + 60_fix_wraster_symbol_versioning.diff + 61_fix_wmmenugen_segfault.diff * debian/rules - Use new --with-defsdatadir configure option to specify global defaults directory instead of old GLOBAL_DEFAULTS_SUBDIR macro. - Use renamed --with-xlocale configure option instead of old --with-locale. - Drop --with-localedir configure option, as it does not exist. It should have been --localedir, but the default is what we want anyway. - Add -Wl,--as-needed to LDFLAGS to avoid useless dependencies. * debian/wmaker-common.install - Update path for system WMGLOBAL and WMState config files. -- Doug Torrance <[email protected]> Mon, 13 Mar 2017 14:26:52 -0400 wmaker (0.95.7-8) unstable; urgency=medium * debian/control - Add libwmaker1 to libwmaker-dev Depends (Closes: #857164). -- Doug Torrance <[email protected]> Wed, 08 Mar 2017 10:59:29 -0500 wmaker (0.95.7-7) unstable; urgency=medium * Add missing license information to debian/copyright. * Fix segfault in wmmenugen (Closes: #844783). -- Doug Torrance <[email protected]> Sat, 19 Nov 2016 10:35:50 -0500 wmaker (0.95.7-6) unstable; urgency=medium * Split wxcopy and wxpaste into new wmaker-utils package (Closes: #78119). * Restore libwmaker packages. -- Doug Torrance <[email protected]> Wed, 09 Mar 2016 00:08:43 -0500 wmaker (0.95.7-5) unstable; urgency=medium * Clean up debian/copyright. Add some files which were missed in the LGPL paragraph and bump its version to 2+. Restore debian/* paragraph. * Remove useless debian/*.changelog-upstream files. * Remove out of date file README.build. * Drop wmaker-dbg package in favor of automatically generated wmaker-dbgsym. * New file debian/wmaker-common.maintscript; removes obsolete config files (Closes: #726075). * Do not use buggy --enable-randr configure option (Closes: #816993). -- Doug Torrance <[email protected]> Mon, 07 Mar 2016 11:04:33 -0500 wmaker (0.95.7-4) unstable; urgency=medium * Update Vcs-Browser to use https; fixes vcs-field-uses-insecure-uri Lintian warning. * Fix typo in README.Debian; fixes spelling-error-in-readme-debian Lintian warning. * Enable all hardening flags; fixes hardening-no-{bindnow,pie} Lintian warnings. * Bump Standards-Version to 3.9.7, no changes required. * 57_ignore_with-aix-soname.diff: Ignore missing documentation for --with-aix-soname in INSTALL-WMAKER (Closes: #814213). -- Doug Torrance <[email protected]> Fri, 12 Feb 2016 22:27:08 -0500 wmaker (0.95.7-3) unstable; urgency=low * Patch back libwraster symbol version to LIBWRASTER3. Temporarily mark RDrawLine@LIBWRASTER3 with a dep >= 0.95.7-3~ to force lockstep upgrades from broken 0.95.7-2. Closes: #811304 -- Andreas Metzler <[email protected]> Wed, 20 Jan 2016 20:19:27 +0100 wmaker (0.95.7-2) unstable; urgency=medium [ Andreas Metzler ] * Drop unused (since at least 0.95.0+20111028-1) b-d on grep-dctrl. * Upload to unstable. [ Doug Torrance ] * Switch Build-Depends from libtiff5-dev to libtiff-dev for possible future libtiff transitions; also allows backports to earlier releases, e.g., wheezy/precise. * The theme that was removed in version 0.92.0-6 has been reintroduced as an option, now named "DebianLegacy". Because it now contains two themes, the directory debian/debianfiles/Theme has been renamed to Themes. The file Debian.theme.txt in this directory, which actually describes the DebianLegacy theme but was never removed, has been renamed to DebianLegacy.txt. A corresponding paragraph has been added to debian/copyright. (Closes: #393143) -- Andreas Metzler <[email protected]> Sat, 16 Jan 2016 17:53:44 +0100 wmaker (0.95.7-1) experimental; urgency=medium [ Rodolfo García Peñas (kix) ] * New upstream version 0.95.7. * debian/changelog, removed debian files (lintian warning). * Updated debian/libwings3.symbols. * Updated libwraster5.symbols * Changed the test for the update-menu command in these files to avoid a lintian warning (command-with-path-in-maintainer-script): * debian/wmaker.postrm * debian/wmaker-common.postrm * Removed the Encoding field in debian/debianfiles/wmaker-common.desktop to avoid a lintian warning (desktop-entry-contains-encoding-key). * Updated debian/rules to include pango support (--enable-pango). * Updated all debian/patches only with quilt refresh. * Updated some debian files because the manpages are moved from section 1x to 1: * debian/patches/51_wmaker_man.diff * debian/wmaker-common.manpages * debian/wmaker.install * debian/wmaker.manpages * Removed upstream file FAQ.I18N in debian/wmaker-common.docs. [ Andreas Metzler ] * 56_ignore_runstatedir.diff: Ignore missing documentation for --runstatedir in INSTALL. * Use dh_autoreconf instead of invoking autogen.sh in the configure target. * Simplify debian/rules and use dh_auto_configure, especially for handling dpkg-buildflags. * wmaker manpage was also moved from section 1x to 1. Fix pointer in README.Debian and update-alternatives slave link. [ Doug Torrance ] * Switch maintenance to Debian Window Maker Team with kix, Andreas, and myself as uploaders. * Tidy up packaging using wrap-and-sort. * Remove Breaks/Replaces wmaker (<< 0.95.0+20111028-3); this version is no longer in Debian. * Switch Depends to wmaker-common (= ${source:Version}) so common files are also updated on upgrade. * Add Vcs-* fields to debian/control. * Update Format field in debian/copyright. * Update debian/watch from sepwatch project. * Remove files from debian/source/options which are handled now by dh-autoreconf. Add distros directory (present in upstream git but not tarball) and doc files modified during build. * Add multiarch support. In particular, add Multi-Arch fields to debian/control, add wildcards for multiarch triplets to debian/*.install, and remove --libdir from dh_auto_configure in debian/rules. * Use wildcards for locales in debian/wmaker-common.install for maintainability. -- Andreas Metzler <[email protected]> Sun, 10 Jan 2016 11:38:11 +0100 wmaker (0.95.6-1.2) unstable; urgency=medium * Non-maintainer upload, with maintainer approval. * Pull 56_wrlib-add-support-for-release-5.1.0-of-the-libgif.patch from upstream to allow building against giflib 5. Closes: #803292 -- Andreas Metzler <[email protected]> Wed, 16 Dec 2015 19:16:51 +0100 wmaker (0.95.6-1.1) unstable; urgency=medium * Non-maintainer upload. * debian/control: - Add Breaks/Replaces for libwraster3-dev; remove Provides for libwraster-dev (Closes: #784711). -- Doug Torrance <[email protected]> Thu, 21 May 2015 13:34:40 -0500 wmaker (0.95.6-1) unstable; urgency=medium * New upstream version 0.95.6. [Closes: #148856] * Bumped to standard version 3.9.6. No changes. * Removed patch 55_typo.diff because is now in upstream. * Patch 56_ungif_problem.diff updated: * New name: 55_ungif_problem.diff * Now udpates the file m4/wm_imgfmt_check.m4, because upstream moved the ungif code from configure.ac to this m4 file. * Removed Encoding in debianfiles/wmaker-common.desktop. * The Encoding key is now deprecated by the FreeDesktop. * Moved library libwings2 to libwings3. * Changed in debian/control. * Moved libwings2.changelog-upstream to libwings3.changelog-upstream. * Moved libwings2.install to libwings3.install. * Moved libwings2.symbols to libwings3.symbols. * Moved libwraster3-dev to libwraster-dev. * Changed in debian/control. * Moved libwraster3-dev.changelog-upstream to libwraster-dev.changelog-upstream. * Moved libwraster3-dev.install to libwraster-dev.install. * Moved libwraster3-dev.docs to libwraster-dev.docs. * Moved libwraster3-dev.manpages to libwraster-dev.manpages. * Updated symbols. * Moved libwraster3 to libwraster5. * Changed in debian/control. * Moved libwraster3.changelog-upstream to libwraster5.changelog-upstream. * Moved libwraster3.docs to libwraster5.docs. * Moved libwraster3.install to libwraster5.install. * Moved libwraster3.symbols to libwraster5.symbols. * Updated symbols. * Moved libwutil3 to libwutil5. * Changed in debian/control. * Moved libwutil3.changelog-upstream to libwutil5.changelog-upstream. * Moved libwutil3.install to libwutil5.install. * Moved libwutil3.symbols to libwutil5.symbols. * Updated symbols. * Removed WindowMaker/Icons/sound.tiff in debian/copyright. * Avoid lintian warning. * Added Keywords in debianfiles/wmaker-common.desktop. * Avoid lintian warning. -- Rodolfo García Peñas (kix) <[email protected]> Thu, 09 Oct 2014 05:59:36 +0200 wmaker (0.95.5-2) unstable; urgency=low * New patch debian/patches/56_ungif_problem.diff. [Closes: #733353] This patch removes the link against -lungif. * Bumped to standard version 3.9.5. No changes. -- Rodolfo García Peñas (kix) <[email protected]> Tue, 31 Dec 2013 00:20:43 +0100 wmaker (0.95.5-1) unstable; urgency=low * New upstream version 0.95.5. [Closes: #723840] - New WUtil library version 3. - Updated debian/control file, replacing libwutil2 with libwutil3. - Files moved in debian folder: - libwutil2.changelog-upstream -> libwutil3.changelog-upstream - libwutil2.install -> libwutil3.install - Removed file libwutil2.symbols - New file libwutil3.symbols * "Build-Depends: libtiff5-dev" in packages wmaker and libwraster3-dev, since libtiff-dev introduces dependency to libtiff4 which is in oldlibs. * Included the word "WindowMaker" in the wmaker package description, to found it easily. [Closes: #685424] -- Rodolfo García Peñas (kix) <[email protected]> Sun, 22 Sep 2013 10:08:02 +0200 wmaker (0.95.4-2) unstable; urgency=low * Package moved from experimental to unstable and updated. * Changed permissions to menu-methods/wmaker to a+x. Updated the debian/wmaker-common.postinst and debian/wmaker.postinst [Closes: #705160] * debian/control - Removed DM Upload flag (obsolete). - Updated maintainer email address, from [email protected] to [email protected]. - Now using libtiff-dev to build packages (libtiff4-dev is in oldlibs). - Removed xosview as suggested package (not in all archs). * Bumped to standard version 3.9.4. -- Rodolfo García Peñas (kix) <[email protected]> Tue, 06 Aug 2013 06:34:14 +0200 wmaker (0.95.4-1) experimental; urgency=low * New upstream version 0.95.4. - Better icon management. [Closes: #35587, #404729] - Now cpp is not needed. Updated the debian/README.Debian file - New symbols in debian/libwutil2.symbols * Updated some icon paths in debianfiles/conf/WindowMaker - Removed ~/pixmap folder * debian/control: - Debconf version 9 (see debian/compat too). - New debug scheme for multi-platform. Removed debian/wmaker-dbg.dirs, because the path for debug files is now using hashes (/usr/lib/debug/build-id). * debian/rules: - Removed the get-*-flags scripts fix. Not needed (and was wrong). - Removed the HOSTSPEC stuff. Not needed with debconf 9. * debian/README.Debian: - Changed /etc path for appearance.menu. -- Rodolfo García Peñas (kix) <[email protected]> Wed, 3 Jan 2013 00:17:31 +0100 wmaker (0.95.3-2) unstable; urgency=low * Hardened. debian/rules changed. * DM-Upload-Allowed set. -- Rodolfo García Peñas (kix) <[email protected]> Thu, 10 Jun 2012 23:35:31 +0200 wmaker (0.95.3-1) unstable; urgency=low * New upstream release 0.95.3 * Removed debian/clean file. Upstream removes now the files. * Bumped to standard version 3.9.3 * Important!: Removed symbol "W_DraggingInfo" in libwutil2 and libwings2, because the struct W_DraggingInfo is now declared as "typedef", therefore the struct is not included. This change is included in upstream, see line 126 of the file WINGs/WINGs/WINGsP.h * Patch 53_Debian_WMState.diff changed, because the WMState file in upstream is now different. Now, the dock launch WPrefs. * Removed /etc/X11/WindowMaker files. * Removed from debian/wmaker-common.dirs * Removed (duplicated) files in debian/wmaker-common.install * New path for menu.hook: /usr/share/WindowMaker * Changed in the menu-method files (wmaker and wmappearance. * Removed menu.posthook and menu.prehook. * Changed the menu behaviour. Applications/* contents moved to the root menu. -- Rodolfo García Peñas (kix) <[email protected]> Thu, 23 May 2012 21:32:22 +0200 wmaker (0.95.2-1) unstable; urgency=low * New upstream version 0.95.2 [Closes: #69669, #486542, #270877] [Closes: #283240, #48550, #297019, #108432, #72917] diff --git a/debian/wmaker-utils.manpages b/debian/wmaker-utils.manpages index decf97d..78ee737 100644 --- a/debian/wmaker-utils.manpages +++ b/debian/wmaker-utils.manpages @@ -1,2 +1,2 @@ -doc/wxcopy.1 -doc/wxpaste.1 +usr/share/man/man1/wxcopy.1 +usr/share/man/man1/wxpaste.1 diff --git a/debian/wmaker.manpages b/debian/wmaker.manpages index 0563656..72463b5 100644 --- a/debian/wmaker.manpages +++ b/debian/wmaker.manpages @@ -1,14 +1,14 @@ -doc/WPrefs.1 -doc/WindowMaker.1 -doc/geticonset.1 -doc/getstyle.1 -doc/seticons.1 -doc/setstyle.1 -doc/wdread.1 -doc/wdwrite.1 -doc/wmagnify.1 -doc/wmaker.1 -doc/wmgenmenu.1 -doc/wmiv.1 -doc/wmmenugen.1 -doc/wmsetbg.1 +usr/share/man/man1/geticonset.1 +usr/share/man/man1/getstyle.1 +usr/share/man/man1/seticons.1 +usr/share/man/man1/setstyle.1 +usr/share/man/man1/wdread.1 +usr/share/man/man1/wdwrite.1 +usr/share/man/man1/WindowMaker.1 +usr/share/man/man1/wmagnify.1 +usr/share/man/man1/wmaker.1 +usr/share/man/man1/wmgenmenu.1 +usr/share/man/man1/wmiv.1 +usr/share/man/man1/wmmenugen.1 +usr/share/man/man1/wmsetbg.1 +usr/share/man/man1/WPrefs.1
roblillack/wmaker
44bc9cc264ba13a6033c1145ba2b15f48395356f
Fix various abs() issues.
diff --git a/WPrefs.app/FontSimple.c b/WPrefs.app/FontSimple.c index eac0411..2147b98 100644 --- a/WPrefs.app/FontSimple.c +++ b/WPrefs.app/FontSimple.c @@ -1,750 +1,751 @@ /* FontSimple.c- simplified font configuration panel * * WPrefs - Window Maker Preferences Program * * Copyright (c) 1998-2004 Alfredo K. Kojima * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "WPrefs.h" #include <unistd.h> #include <fontconfig/fontconfig.h> +#include <math.h> /* workaround for older fontconfig, that doesn't define these constants */ #ifndef FC_WEIGHT_NORMAL /* Weights */ # define FC_WEIGHT_THIN 10 # define FC_WEIGHT_EXTRALIGHT 40 # define FC_WEIGHT_ULTRALIGHT FC_WEIGHT_EXTRALIGHT # define FC_WEIGHT_REGULAR 80 # define FC_WEIGHT_NORMAL FC_WEIGHT_REGULAR # define FC_WEIGHT_SEMIBOLD FC_WEIGHT_DEMIBOLD # define FC_WEIGHT_EXTRABOLD 205 # define FC_WEIGHT_ULTRABOLD FC_WEIGHT_EXTRABOLD # define FC_WEIGHT_HEAVY FC_WEIGHT_BLACK /* Widths */ # define FC_WIDTH "width" # define FC_WIDTH_ULTRACONDENSED 50 # define FC_WIDTH_EXTRACONDENSED 63 # define FC_WIDTH_CONDENSED 75 # define FC_WIDTH_SEMICONDENSED 87 # define FC_WIDTH_NORMAL 100 # define FC_WIDTH_SEMIEXPANDED 113 # define FC_WIDTH_EXPANDED 125 # define FC_WIDTH_EXTRAEXPANDED 150 # define FC_WIDTH_ULTRAEXPANDED 200 #endif #define SAMPLE_TEXT "The Lazy Fox Jumped Ipsum Foobar 1234 - 56789" typedef struct { int weight; int width; int slant; } FontStyle; typedef struct { char *name; int stylen; FontStyle *styles; } FontFamily; typedef struct { int familyn; FontFamily *families; } FontList; typedef struct _Panel { WMBox *box; char *sectionName; char *description; CallbackRec callbacks; WMWidget *parent; WMPopUpButton *optionP; WMList *familyL; WMList *styleL; WMList *sizeL; WMTextField *sampleT; FontList *fonts; } _Panel; #define ICON_FILE "fonts" static const struct { const char *option; const char *label; } fontOptions[] = { { "WindowTitleFont", N_("Window Title") }, { "MenuTitleFont", N_("Menu Title") }, { "MenuTextFont", N_("Menu Text") }, { "IconTitleFont", N_("Icon Title") }, { "ClipTitleFont", N_("Clip Title") }, { "LargeDisplayFont", N_("Desktop Caption") }, { "SystemFont", N_("System Font") }, { "BoldSystemFont", N_("Bold System Font")} }; static const char *standardSizes[] = { "6", "8", "9", "10", "11", "12", "13", "14", "15", "16", "18", "20", "22", "24", "28", "32", "36", "48", "64", "72", NULL }; static const struct { int weight; const char *name; } fontWeights[] = { { FC_WEIGHT_THIN, "Thin" }, { FC_WEIGHT_EXTRALIGHT, "ExtraLight" }, { FC_WEIGHT_LIGHT, "Light" }, { FC_WEIGHT_NORMAL, "Normal" }, { FC_WEIGHT_MEDIUM, "" }, { FC_WEIGHT_DEMIBOLD, "DemiBold" }, { FC_WEIGHT_BOLD, "Bold" }, { FC_WEIGHT_EXTRABOLD, "ExtraBold" }, { FC_WEIGHT_BLACK, "Black" } }; static const struct { int slant; const char *name; } fontSlants[] = { { FC_SLANT_ROMAN, "" }, { FC_SLANT_ITALIC, "Italic" }, { FC_SLANT_OBLIQUE, "Oblique" } }; static const struct { int width; const char *name; } fontWidths[] = { { FC_WIDTH_ULTRACONDENSED, "UltraCondensed" }, { FC_WIDTH_EXTRACONDENSED, "ExtraCondensed" }, { FC_WIDTH_CONDENSED, "Condensed" }, { FC_WIDTH_SEMICONDENSED, "SemiCondensed" }, { FC_WIDTH_NORMAL, "" }, { FC_WIDTH_SEMIEXPANDED, "SemiExpanded" }, { FC_WIDTH_EXPANDED, "Expanded" }, { FC_WIDTH_EXTRAEXPANDED, "ExtraExpanded" }, { FC_WIDTH_ULTRAEXPANDED, "UltraExpanded" }, }; static int compare_family(const void *a, const void *b) { FontFamily *fa = (FontFamily *) a; FontFamily *fb = (FontFamily *) b; return strcmp(fa->name, fb->name); } static int compare_styles(const void *a, const void *b) { FontStyle *sa = (FontStyle *) a; FontStyle *sb = (FontStyle *) b; int compare; compare = sa->weight - sb->weight; if (compare != 0) return compare; compare = sa->slant - sb->slant; if (compare != 0) return compare; return (sa->width - sb->width); } static void lookup_available_fonts(_Panel * panel) { FcPattern *pat = FcPatternCreate(); FcObjectSet *os; FcFontSet *fonts; FontFamily *family; os = FcObjectSetBuild(FC_FAMILY, FC_WEIGHT, FC_WIDTH, FC_SLANT, NULL); fonts = FcFontList(0, pat, os); if (fonts) { int i; panel->fonts = wmalloc(sizeof(FontList)); panel->fonts->familyn = 0; panel->fonts->families = wmalloc(sizeof(FontFamily) * fonts->nfont); for (i = 0; i < fonts->nfont; i++) { char *name; int weight, slant, width; int j, found; if (FcPatternGetString(fonts->fonts[i], FC_FAMILY, 0, (FcChar8 **) & name) != FcResultMatch) continue; if (FcPatternGetInteger(fonts->fonts[i], FC_WEIGHT, 0, &weight) != FcResultMatch) weight = FC_WEIGHT_MEDIUM; if (FcPatternGetInteger(fonts->fonts[i], FC_WIDTH, 0, &width) != FcResultMatch) width = FC_WIDTH_NORMAL; if (FcPatternGetInteger(fonts->fonts[i], FC_SLANT, 0, &slant) != FcResultMatch) slant = FC_SLANT_ROMAN; found = -1; for (j = 0; j < panel->fonts->familyn && found < 0; j++) if (strcasecmp(panel->fonts->families[j].name, name) == 0) found = j; if (found < 0) { panel->fonts->families[panel->fonts->familyn++].name = wstrdup(name); family = panel->fonts->families + panel->fonts->familyn - 1; family->stylen = 0; family->styles = NULL; } else family = panel->fonts->families + found; family->stylen++; family->styles = wrealloc(family->styles, sizeof(FontStyle) * family->stylen); family->styles[family->stylen - 1].weight = weight; family->styles[family->stylen - 1].slant = slant; family->styles[family->stylen - 1].width = width; } qsort(panel->fonts->families, panel->fonts->familyn, sizeof(FontFamily), compare_family); for (i = 0; i < panel->fonts->familyn; i++) { qsort(panel->fonts->families[i].styles, panel->fonts->families[i].stylen, sizeof(FontStyle), compare_styles); } FcFontSetDestroy(fonts); } if (os) FcObjectSetDestroy(os); if (pat) FcPatternDestroy(pat); panel->fonts->families[panel->fonts->familyn++].name = wstrdup("sans serif"); family = panel->fonts->families + panel->fonts->familyn - 1; family->styles = wmalloc(sizeof(FontStyle) * 2); family->stylen = 2; family->styles[0].weight = FC_WEIGHT_MEDIUM; family->styles[0].slant = FC_SLANT_ROMAN; family->styles[0].width = FC_WIDTH_NORMAL; family->styles[1].weight = FC_WEIGHT_BOLD; family->styles[1].slant = FC_SLANT_ROMAN; family->styles[1].width = FC_WIDTH_NORMAL; panel->fonts->families[panel->fonts->familyn++].name = wstrdup("serif"); family = panel->fonts->families + panel->fonts->familyn - 1; family->styles = wmalloc(sizeof(FontStyle) * 2); family->stylen = 2; family->styles[0].weight = FC_WEIGHT_MEDIUM; family->styles[0].slant = FC_SLANT_ROMAN; family->styles[0].width = FC_WIDTH_NORMAL; family->styles[1].weight = FC_WEIGHT_BOLD; family->styles[1].slant = FC_SLANT_ROMAN; family->styles[1].width = FC_WIDTH_NORMAL; } static char *getSelectedFont(_Panel * panel, FcChar8 * curfont) { WMListItem *item; FcPattern *pat; char *name; if (curfont) pat = FcNameParse(curfont); else pat = FcPatternCreate(); item = WMGetListSelectedItem(panel->familyL); if (item) { FcPatternDel(pat, FC_FAMILY); FcPatternAddString(pat, FC_FAMILY, (FcChar8 *) item->text); } item = WMGetListSelectedItem(panel->styleL); if (item) { FontStyle *style = (FontStyle *) item->clientData; FcPatternDel(pat, FC_WEIGHT); FcPatternAddInteger(pat, FC_WEIGHT, style->weight); FcPatternDel(pat, FC_WIDTH); FcPatternAddInteger(pat, FC_WIDTH, style->width); FcPatternDel(pat, FC_SLANT); FcPatternAddInteger(pat, FC_SLANT, style->slant); } item = WMGetListSelectedItem(panel->sizeL); if (item) { FcPatternDel(pat, FC_PIXEL_SIZE); FcPatternAddDouble(pat, FC_PIXEL_SIZE, atoi(item->text)); } name = (char *)FcNameUnparse(pat); FcPatternDestroy(pat); return name; } static void updateSampleFont(_Panel * panel) { WMMenuItem *item = WMGetPopUpButtonMenuItem(panel->optionP, WMGetPopUpButtonSelectedItem(panel->optionP)); char *fn = WMGetMenuItemRepresentedObject(item); if (fn) { WMFont *font = WMCreateFont(WMWidgetScreen(panel->box), fn); if (font) { WMSetTextFieldFont(panel->sampleT, font); WMReleaseFont(font); } } } static void selectedFamily(WMWidget * w, void *data) { _Panel *panel = (_Panel *) data; WMListItem *item; FontStyle *oldStyle = NULL; char buffer[1024]; /* Parameter not used, but tell the compiler that it is ok */ (void) w; item = WMGetListSelectedItem(panel->styleL); if (item) oldStyle = (FontStyle *) item->clientData; item = WMGetListSelectedItem(panel->familyL); if (item) { FontFamily *family = (FontFamily *) item->clientData; int i, oldi = 0, oldscore = 0; WMClearList(panel->styleL); for (i = 0; i < family->stylen; i++) { int j; const char *weight = "", *slant = "", *width = ""; WMListItem *item; for (j = 0; j < wlengthof(fontWeights); j++) if (fontWeights[j].weight == family->styles[i].weight) { weight = fontWeights[j].name; break; } for (j = 0; j < wlengthof(fontWidths); j++) if (fontWidths[j].width == family->styles[i].width) { width = fontWidths[j].name; break; } for (j = 0; j < wlengthof(fontSlants); j++) if (fontSlants[j].slant == family->styles[i].slant) { slant = fontSlants[j].name; break; } sprintf(buffer, "%s%s%s%s%s", weight, *weight ? " " : "", slant, (*slant || *weight) ? " " : "", width); if (!buffer[0]) strcpy(buffer, "Roman"); item = WMAddListItem(panel->styleL, buffer); item->clientData = family->styles + i; if (oldStyle) { int score = 0; if (oldStyle->width == family->styles[i].width) score |= 1; if (oldStyle->weight == family->styles[i].weight) score |= 2; if (oldStyle->slant == family->styles[i].slant) score |= 4; if (score > oldscore) { oldi = i; oldscore = score; } } } WMSelectListItem(panel->styleL, oldi); { int index = WMGetPopUpButtonSelectedItem(panel->optionP); WMMenuItem *item = WMGetPopUpButtonMenuItem(panel->optionP, index); FcChar8 *ofont; char *nfont; ofont = (FcChar8 *) WMGetMenuItemRepresentedObject(item); nfont = getSelectedFont(panel, ofont); if (ofont) wfree(ofont); WMSetMenuItemRepresentedObject(item, nfont); } updateSampleFont(panel); } } static void selected(WMWidget * w, void *data) { _Panel *panel = (_Panel *) data; int index = WMGetPopUpButtonSelectedItem(panel->optionP); WMMenuItem *item = WMGetPopUpButtonMenuItem(panel->optionP, index); FcChar8 *ofont; char *nfont; /* Parameter not used, but tell the compiler that it is ok */ (void) w; ofont = (FcChar8 *) WMGetMenuItemRepresentedObject(item); nfont = getSelectedFont(panel, ofont); if (ofont) wfree(ofont); WMSetMenuItemRepresentedObject(item, nfont); updateSampleFont(panel); } static void selectedOption(WMWidget * w, void *data) { _Panel *panel = (_Panel *) data; int index = WMGetPopUpButtonSelectedItem(panel->optionP); WMMenuItem *item = WMGetPopUpButtonMenuItem(panel->optionP, index); char *font; /* Parameter not used, but tell the compiler that it is ok */ (void) w; font = (char *)WMGetMenuItemRepresentedObject(item); if (font) { FcPattern *pat; pat = FcNameParse((FcChar8 *) font); if (pat) { char *name; int weight, slant, width; double size; int distance, closest, found; int i; FcDefaultSubstitute(pat); if (FcPatternGetString(pat, FC_FAMILY, 0, (FcChar8 **) & name) != FcResultMatch) name = "sans serif"; found = 0; /* select family */ for (i = 0; i < WMGetListNumberOfRows(panel->familyL); i++) { WMListItem *item = WMGetListItem(panel->familyL, i); FontFamily *family = (FontFamily *) item->clientData; if (strcasecmp(family->name, name) == 0) { found = 1; WMSelectListItem(panel->familyL, i); WMSetListPosition(panel->familyL, i); break; } } if (!found) WMSelectListItem(panel->familyL, -1); selectedFamily(panel->familyL, panel); /* select style */ if (FcPatternGetInteger(pat, FC_WEIGHT, 0, &weight) != FcResultMatch) weight = FC_WEIGHT_NORMAL; if (FcPatternGetInteger(pat, FC_WIDTH, 0, &width) != FcResultMatch) width = FC_WIDTH_NORMAL; if (FcPatternGetInteger(pat, FC_SLANT, 0, &slant) != FcResultMatch) slant = FC_SLANT_ROMAN; if (FcPatternGetDouble(pat, FC_PIXEL_SIZE, 0, &size) != FcResultMatch) size = 10.0; for (i = 0, found = 0, closest = 0; i < WMGetListNumberOfRows(panel->styleL); i++) { WMListItem *item = WMGetListItem(panel->styleL, i); FontStyle *style = (FontStyle *) item->clientData; distance = ((abs(style->weight - weight) << 16) + (abs(style->slant - slant) << 8) + (abs(style->width - width))); if (i == 0 || distance < closest) { closest = distance; found = i; if (distance == 0) { break; /* perfect match */ } } } WMSelectListItem(panel->styleL, found); WMSetListPosition(panel->styleL, found); for (i = 0, found = 0, closest = 0; i < WMGetListNumberOfRows(panel->sizeL); i++) { WMListItem *item = WMGetListItem(panel->sizeL, i); int distance; - distance = abs(size - atoi(item->text)); + distance = fabs(size - atoi(item->text)); if (i == 0 || distance < closest) { closest = distance; found = i; if (distance == 0) { break; /* perfect match */ } } } WMSelectListItem(panel->sizeL, found); WMSetListPosition(panel->sizeL, found); selected(NULL, panel); } else wwarning("Can't parse font '%s'", font); } updateSampleFont(panel); } static WMLabel *createListLabel(WMScreen * scr, WMWidget * parent, const char *text) { WMLabel *label; WMColor *color; WMFont *boldFont = WMBoldSystemFontOfSize(scr, 12); label = WMCreateLabel(parent); WMSetLabelFont(label, boldFont); WMSetLabelText(label, text); WMSetLabelRelief(label, WRSunken); WMSetLabelTextAlignment(label, WACenter); color = WMDarkGrayColor(scr); WMSetWidgetBackgroundColor(label, color); WMReleaseColor(color); color = WMWhiteColor(scr); WMSetLabelTextColor(label, color); WMReleaseColor(color); WMReleaseFont(boldFont); return label; } static void showData(_Panel * panel) { int i; WMMenuItem *item; WMScreen *scr; scr = WMWidgetScreen(panel->parent); for (i = 0; i < WMGetPopUpButtonNumberOfItems(panel->optionP); i++) { char *ofont, *font; item = WMGetPopUpButtonMenuItem(panel->optionP, i); ofont = WMGetMenuItemRepresentedObject(item); if (ofont) wfree(ofont); if (strcmp(fontOptions[i].option, "SystemFont") == 0) font = WMGetFontName(WMDefaultSystemFont(scr)); else if (strcmp(fontOptions[i].option, "BoldSystemFont") == 0) font = WMGetFontName(WMDefaultBoldSystemFont(scr)); else font = GetStringForKey(fontOptions[i].option); if (font) font = wstrdup(font); WMSetMenuItemRepresentedObject(item, font); } WMSetPopUpButtonSelectedItem(panel->optionP, 0); selectedOption(panel->optionP, panel); } static void storeData(_Panel * panel) { int i; WMMenuItem *item; for (i = 0; i < WMGetPopUpButtonNumberOfItems(panel->optionP); i++) { char *font; item = WMGetPopUpButtonMenuItem(panel->optionP, i); font = WMGetMenuItemRepresentedObject(item); if (font && *font) { if (strcmp(fontOptions[i].option, "SystemFont") == 0 || strcmp(fontOptions[i].option, "BoldSystemFont") == 0) { char *path; WMUserDefaults *defaults; path = wdefaultspathfordomain("WMGLOBAL"); defaults = WMGetDefaultsFromPath(path); wfree(path); WMSetUDStringForKey(defaults, font, fontOptions[i].option); WMSaveUserDefaults(defaults); } else { SetStringForKey(font, fontOptions[i].option); } } } } static void createPanel(Panel * p) { _Panel *panel = (_Panel *) p; WMScreen *scr = WMWidgetScreen(panel->parent); WMLabel *label; WMBox *hbox, *vbox; int i; lookup_available_fonts(panel); panel->box = WMCreateBox(panel->parent); WMSetViewExpandsToParent(WMWidgetView(panel->box), 5, 2, 5, 5); WMSetBoxHorizontal(panel->box, False); WMSetBoxBorderWidth(panel->box, 8); WMMapWidget(panel->box); hbox = WMCreateBox(panel->box); WMSetBoxHorizontal(hbox, True); WMAddBoxSubview(panel->box, WMWidgetView(hbox), False, True, 40, 22, 8); vbox = WMCreateBox(hbox); WMAddBoxSubview(hbox, WMWidgetView(vbox), False, True, 130, 0, 10); WMSetBoxHorizontal(vbox, False); panel->optionP = WMCreatePopUpButton(vbox); WMAddBoxSubviewAtEnd(vbox, WMWidgetView(panel->optionP), False, True, 20, 0, 8); for (i = 0; i < wlengthof(fontOptions); i++) WMAddPopUpButtonItem(panel->optionP, _(fontOptions[i].label)); WMSetPopUpButtonAction(panel->optionP, selectedOption, panel); label = WMCreateLabel(hbox); WMSetLabelText(label, _("Sample Text")); WMSetLabelTextAlignment(label, WARight); WMAddBoxSubview(hbox, WMWidgetView(label), False, True, 80, 0, 2); panel->sampleT = WMCreateTextField(hbox); WMSetViewExpandsToParent(WMWidgetView(panel->sampleT), 10, 18, 10, 10); WMSetTextFieldText(panel->sampleT, SAMPLE_TEXT); WMAddBoxSubview(hbox, WMWidgetView(panel->sampleT), True, True, 60, 0, 0); hbox = WMCreateBox(panel->box); WMSetBoxHorizontal(hbox, True); WMAddBoxSubview(panel->box, WMWidgetView(hbox), True, True, 100, 0, 2); vbox = WMCreateBox(hbox); WMSetBoxHorizontal(vbox, False); WMAddBoxSubview(hbox, WMWidgetView(vbox), False, True, 240, 20, 4); label = createListLabel(scr, vbox, _("Family")); WMAddBoxSubview(vbox, WMWidgetView(label), False, True, 20, 0, 2); /* family */ panel->familyL = WMCreateList(vbox); WMAddBoxSubview(vbox, WMWidgetView(panel->familyL), True, True, 0, 0, 0); if (panel->fonts) { WMListItem *item; for (i = 0; i < panel->fonts->familyn; i++) { item = WMAddListItem(panel->familyL, panel->fonts->families[i].name); item->clientData = panel->fonts->families + i; } } else WMAddListItem(panel->familyL, "sans serif"); WMSetListAction(panel->familyL, selectedFamily, panel); vbox = WMCreateBox(hbox); WMSetBoxHorizontal(vbox, False); WMAddBoxSubview(hbox, WMWidgetView(vbox), True, True, 10, 0, 0); { WMBox *box = WMCreateBox(vbox); WMSetBoxHorizontal(box, True); WMAddBoxSubview(vbox, WMWidgetView(box), False, True, 20, 0, 2); label = createListLabel(scr, box, _("Style")); WMAddBoxSubview(box, WMWidgetView(label), True, True, 20, 0, 4); label = createListLabel(scr, box, _("Size")); WMAddBoxSubview(box, WMWidgetView(label), False, True, 60, 0, 0); box = WMCreateBox(vbox); WMSetBoxHorizontal(box, True); WMAddBoxSubview(vbox, WMWidgetView(box), True, True, 20, 0, 0); panel->styleL = WMCreateList(box); WMAddBoxSubview(box, WMWidgetView(panel->styleL), True, True, 0, 0, 4); WMSetListAction(panel->styleL, selected, panel); panel->sizeL = WMCreateList(box); WMAddBoxSubview(box, WMWidgetView(panel->sizeL), False, True, 60, 0, 0); for (i = 0; standardSizes[i]; i++) { WMAddListItem(panel->sizeL, standardSizes[i]); } WMSetListAction(panel->sizeL, selected, panel); } WMMapSubwidgets(panel->box); WMMapWidget(panel->box); WMRealizeWidget(panel->box); showData(panel); } Panel *InitFontSimple(WMWidget *parent) { _Panel *panel; panel = wmalloc(sizeof(_Panel)); panel->sectionName = _("Font Configuration"); panel->description = _("Configure fonts for Window Maker titlebars, menus etc."); panel->parent = parent; panel->callbacks.createWidgets = createPanel; panel->callbacks.updateDomain = storeData; AddSection(panel, ICON_FILE); return panel; } diff --git a/src/menu.c b/src/menu.c index 6164e28..ebdd2b4 100644 --- a/src/menu.c +++ b/src/menu.c @@ -927,1039 +927,1039 @@ static int keyboardMenu(WMenu * menu) break; case XK_Up: #ifdef XK_KP_Up case XK_KP_Up: #endif if (menu->selected_entry <= 0) selectEntry(menu, menu->entry_no - 1); else selectEntry(menu, menu->selected_entry - 1); makeVisible(menu); break; case XK_Down: #ifdef XK_KP_Down case XK_KP_Down: #endif if (menu->selected_entry < 0) selectEntry(menu, 0); else if (menu->selected_entry == menu->entry_no - 1) selectEntry(menu, 0); else if (menu->selected_entry < menu->entry_no - 1) selectEntry(menu, menu->selected_entry + 1); makeVisible(menu); break; case XK_Right: #ifdef XK_KP_Right case XK_KP_Right: #endif if (menu->selected_entry >= 0) { WMenuEntry *entry; entry = menu->entries[menu->selected_entry]; if (entry->cascade >= 0 && menu->cascades && menu->cascades[entry->cascade]->entry_no > 0) { XUngrabKeyboard(dpy, CurrentTime); selectEntry(menu->cascades[entry->cascade], 0); if (!keyboardMenu(menu->cascades[entry->cascade])) done = 1; XGrabKeyboard(dpy, menu->frame->core->window, True, GrabModeAsync, GrabModeAsync, CurrentTime); } } break; case XK_Left: #ifdef XK_KP_Left case XK_KP_Left: #endif if (menu->parent != NULL && menu->parent->selected_entry >= 0) { selectEntry(menu, -1); move_menus(menu, old_pos_x, old_pos_y); return True; } break; case XK_Return: #ifdef XK_KP_Enter case XK_KP_Enter: #endif done = 2; break; default: index = check_key(menu, &event.xkey); if (index >= 0) { selectEntry(menu, index); } } break; default: if (event.type == ButtonPress) done = 1; WMHandleEvent(&event); } } XUngrabKeyboard(dpy, CurrentTime); if (done == 2 && menu->selected_entry >= 0) { entry = menu->entries[menu->selected_entry]; } else { entry = NULL; } if (entry && entry->callback != NULL && entry->flags.enabled && entry->cascade < 0) { #if (MENU_BLINK_COUNT > 0) int sel = menu->selected_entry; int i; for (i = 0; i < MENU_BLINK_COUNT; i++) { paintEntry(menu, sel, False); XSync(dpy, 0); wusleep(MENU_BLINK_DELAY); paintEntry(menu, sel, True); XSync(dpy, 0); wusleep(MENU_BLINK_DELAY); } #endif selectEntry(menu, -1); if (!menu->flags.buttoned) { wMenuUnmap(menu); move_menus(menu, old_pos_x, old_pos_y); } closeCascade(menu); (*entry->callback) (menu, entry); } else { if (!menu->flags.buttoned) { wMenuUnmap(menu); move_menus(menu, old_pos_x, old_pos_y); } selectEntry(menu, -1); } /* returns True if returning from a submenu to a parent menu, * False if exiting from menu */ return False; } void wMenuMapAt(WMenu * menu, int x, int y, int keyboard) { if (!menu->flags.realized) { menu->flags.realized = 1; wMenuRealize(menu); } if (!menu->flags.mapped) { if (wPreferences.wrap_menus) { WScreen *scr = menu->frame->screen_ptr; WMRect rect = wGetRectForHead(scr, wGetHeadForPointerLocation(scr)); if (x < rect.pos.x) x = rect.pos.x; if (y < rect.pos.y) y = rect.pos.y; if (x + MENUW(menu) > rect.pos.x + rect.size.width) x = rect.pos.x + rect.size.width - MENUW(menu); if (y + MENUH(menu) > rect.pos.y + rect.size.height) y = rect.pos.y + rect.size.height - MENUH(menu); } XMoveWindow(dpy, menu->frame->core->window, x, y); menu->frame_x = x; menu->frame_y = y; XMapWindow(dpy, menu->frame->core->window); wRaiseFrame(menu->frame->core); menu->flags.mapped = 1; } else { selectEntry(menu, 0); } if (keyboard) keyboardMenu(menu); } void wMenuMap(WMenu * menu) { if (!menu->flags.realized) { menu->flags.realized = 1; wMenuRealize(menu); } if (menu->flags.app_menu && menu->parent == NULL) { menu->frame_x = menu->frame->screen_ptr->app_menu_x; menu->frame_y = menu->frame->screen_ptr->app_menu_y; XMoveWindow(dpy, menu->frame->core->window, menu->frame_x, menu->frame_y); } XMapWindow(dpy, menu->frame->core->window); wRaiseFrame(menu->frame->core); menu->flags.mapped = 1; } void wMenuUnmap(WMenu * menu) { int i; XUnmapWindow(dpy, menu->frame->core->window); if (menu->flags.titled && menu->flags.buttoned) { wFrameWindowHideButton(menu->frame, WFF_RIGHT_BUTTON); } menu->flags.buttoned = 0; menu->flags.mapped = 0; menu->flags.open_to_left = 0; if (menu->flags.shaded) { wFrameWindowResize(menu->frame, menu->frame->core->width, menu->frame->top_width + menu->entry_height*menu->entry_no + menu->frame->bottom_width - 1); menu->flags.shaded = 0; } for (i = 0; i < menu->cascade_no; i++) { if (menu->cascades[i] != NULL && menu->cascades[i]->flags.mapped && !menu->cascades[i]->flags.buttoned) { wMenuUnmap(menu->cascades[i]); } } menu->selected_entry = -1; } void wMenuPaint(WMenu * menu) { int i; if (!menu->flags.mapped) { return; } /* paint entries */ for (i = 0; i < menu->entry_no; i++) { paintEntry(menu, i, i == menu->selected_entry); } } void wMenuSetEnabled(WMenu * menu, int index, int enable) { if (index >= menu->entry_no) return; menu->entries[index]->flags.enabled = enable; paintEntry(menu, index, index == menu->selected_entry); paintEntry(menu->brother, index, index == menu->selected_entry); } static void selectEntry(WMenu * menu, int entry_no) { WMenuEntry *entry; WMenu *submenu; int old_entry; if (menu->entries == NULL) return; if (entry_no >= menu->entry_no) return; old_entry = menu->selected_entry; menu->selected_entry = entry_no; if (old_entry != entry_no) { /* unselect previous entry */ if (old_entry >= 0) { paintEntry(menu, old_entry, False); entry = menu->entries[old_entry]; /* unmap cascade */ if (entry->cascade >= 0 && menu->cascades) { if (!menu->cascades[entry->cascade]->flags.buttoned) { wMenuUnmap(menu->cascades[entry->cascade]); } } } if (entry_no < 0) { menu->selected_entry = -1; return; } entry = menu->entries[entry_no]; if (entry->cascade >= 0 && menu->cascades && entry->flags.enabled) { /* Callback for when the submenu is opened. */ submenu = menu->cascades[entry->cascade]; if (submenu && submenu->flags.brother) submenu = submenu->brother; if (entry->callback) { /* Only call the callback if the submenu is not yet mapped. */ if (menu->flags.brother) { if (!submenu || !submenu->flags.mapped) (*entry->callback) (menu->brother, entry); } else { if (!submenu || !submenu->flags.buttoned) (*entry->callback) (menu, entry); } } /* the submenu menu might have changed */ submenu = menu->cascades[entry->cascade]; /* map cascade */ if (!submenu->flags.mapped) { int x, y; if (!submenu->flags.realized) wMenuRealize(submenu); if (wPreferences.wrap_menus) { if (menu->flags.open_to_left) submenu->flags.open_to_left = 1; if (submenu->flags.open_to_left) { x = menu->frame_x - MENUW(submenu); if (x < 0) { x = 0; submenu->flags.open_to_left = 0; } } else { x = menu->frame_x + MENUW(menu); if (x + MENUW(submenu) >= menu->frame->screen_ptr->scr_width) { x = menu->frame_x - MENUW(submenu); submenu->flags.open_to_left = 1; } } } else { x = menu->frame_x + MENUW(menu); } if (wPreferences.align_menus) { y = menu->frame_y; } else { y = menu->frame_y + menu->entry_height * entry_no; if (menu->flags.titled) y += menu->frame->top_width; if (menu->cascades[entry->cascade]->flags.titled) y -= menu->cascades[entry->cascade]->frame->top_width; } wMenuMapAt(menu->cascades[entry->cascade], x, y, False); menu->cascades[entry->cascade]->parent = menu; } else { return; } } paintEntry(menu, entry_no, True); } } static WMenu *findMenu(WScreen * scr, int *x_ret, int *y_ret) { WMenu *menu; WObjDescriptor *desc; Window root_ret, win, junk_win; int x, y, wx, wy; unsigned int mask; XQueryPointer(dpy, scr->root_win, &root_ret, &win, &x, &y, &wx, &wy, &mask); if (win == None) return NULL; if (XFindContext(dpy, win, w_global.context.client_win, (XPointer *) & desc) == XCNOENT) return NULL; if (desc->parent_type == WCLASS_MENU) { menu = (WMenu *) desc->parent; XTranslateCoordinates(dpy, root_ret, menu->menu->window, wx, wy, x_ret, y_ret, &junk_win); return menu; } return NULL; } static void closeCascade(WMenu * menu) { WMenu *parent = menu->parent; if (menu->flags.brother || (!menu->flags.buttoned && (!menu->flags.app_menu || menu->parent != NULL))) { selectEntry(menu, -1); XSync(dpy, 0); #if (MENU_BLINK_DELAY > 2) wusleep(MENU_BLINK_DELAY / 2); #endif wMenuUnmap(menu); while (parent != NULL && (parent->parent != NULL || !parent->flags.app_menu || parent->flags.brother) && !parent->flags.buttoned) { selectEntry(parent, -1); wMenuUnmap(parent); parent = parent->parent; } if (parent) selectEntry(parent, -1); } } static void closeBrotherCascadesOf(WMenu * menu) { WMenu *tmp; int i; for (i = 0; i < menu->cascade_no; i++) { if (menu->cascades[i]->flags.brother) { tmp = menu->cascades[i]; } else { tmp = menu->cascades[i]->brother; } if (tmp->flags.mapped) { selectEntry(tmp->parent, -1); closeBrotherCascadesOf(tmp); break; } } } #define getEntryAt(menu, x, y) ((y)<0 ? -1 : (y)/(menu->entry_height)) static WMenu *parentMenu(WMenu * menu) { WMenu *parent; WMenuEntry *entry; if (menu->flags.buttoned) return menu; while (menu->parent && menu->parent->flags.mapped) { parent = menu->parent; if (parent->selected_entry < 0) break; entry = parent->entries[parent->selected_entry]; if (!entry->flags.enabled || entry->cascade < 0 || !parent->cascades || parent->cascades[entry->cascade] != menu) break; menu = parent; if (menu->flags.buttoned) break; } return menu; } /* * Will raise the passed menu, if submenu = 0 * If submenu > 0 will also raise all mapped submenus * until the first buttoned one * If submenu < 0 will also raise all mapped parent menus * until the first buttoned one */ static void raiseMenus(WMenu * menu, int submenus) { WMenu *submenu; int i; if (!menu) return; wRaiseFrame(menu->frame->core); if (submenus > 0 && menu->selected_entry >= 0) { i = menu->entries[menu->selected_entry]->cascade; if (i >= 0 && menu->cascades) { submenu = menu->cascades[i]; if (submenu->flags.mapped && !submenu->flags.buttoned) raiseMenus(submenu, submenus); } } if (submenus < 0 && !menu->flags.buttoned && menu->parent && menu->parent->flags.mapped) raiseMenus(menu->parent, submenus); } WMenu *wMenuUnderPointer(WScreen * screen) { WObjDescriptor *desc; Window root_ret, win; int dummy; unsigned int mask; XQueryPointer(dpy, screen->root_win, &root_ret, &win, &dummy, &dummy, &dummy, &dummy, &mask); if (win == None) return NULL; if (XFindContext(dpy, win, w_global.context.client_win, (XPointer *) & desc) == XCNOENT) return NULL; if (desc->parent_type == WCLASS_MENU) return (WMenu *) desc->parent; return NULL; } static void getPointerPosition(WScreen * scr, int *x, int *y) { Window root_ret, win; int wx, wy; unsigned int mask; XQueryPointer(dpy, scr->root_win, &root_ret, &win, x, y, &wx, &wy, &mask); } static void getScrollAmount(WMenu * menu, int *hamount, int *vamount) { WScreen *scr = menu->menu->screen_ptr; int menuX1 = menu->frame_x; int menuY1 = menu->frame_y; int menuX2 = menu->frame_x + MENUW(menu); int menuY2 = menu->frame_y + MENUH(menu); int xroot, yroot; WMRect rect = wGetRectForHead(scr, wGetHeadForPointerLocation(scr)); *hamount = 0; *vamount = 0; getPointerPosition(scr, &xroot, &yroot); if (xroot <= (rect.pos.x + 1) && menuX1 < rect.pos.x) { /* scroll to the right */ *hamount = WMIN(MENU_SCROLL_STEP, abs(menuX1)); } else if (xroot >= (rect.pos.x + rect.size.width - 2) && menuX2 > (rect.pos.x + rect.size.width - 1)) { /* scroll to the left */ - *hamount = WMIN(MENU_SCROLL_STEP, abs(menuX2 - rect.pos.x - rect.size.width - 1)); + *hamount = WMIN(MENU_SCROLL_STEP, abs(menuX2 - rect.pos.x - (int)rect.size.width - 1)); if (*hamount == 0) *hamount = 1; *hamount = -*hamount; } if (yroot <= (rect.pos.y + 1) && menuY1 < rect.pos.y) { /* scroll down */ *vamount = WMIN(MENU_SCROLL_STEP, abs(menuY1)); } else if (yroot >= (rect.pos.y + rect.size.height - 2) && menuY2 > (rect.pos.y + rect.size.height - 1)) { /* scroll up */ - *vamount = WMIN(MENU_SCROLL_STEP, abs(menuY2 - rect.pos.y - rect.size.height - 2)); + *vamount = WMIN(MENU_SCROLL_STEP, abs(menuY2 - rect.pos.y - (int)rect.size.height - 2)); *vamount = -*vamount; } } static void dragScrollMenuCallback(void *data) { WMenu *menu = (WMenu *) data; WScreen *scr = menu->menu->screen_ptr; WMenu *parent = parentMenu(menu); int hamount, vamount; int x, y; int newSelectedEntry; getScrollAmount(menu, &hamount, &vamount); if (hamount != 0 || vamount != 0) { wMenuMove(parent, parent->frame_x + hamount, parent->frame_y + vamount, True); if (findMenu(scr, &x, &y)) { newSelectedEntry = getEntryAt(menu, x, y); selectEntry(menu, newSelectedEntry); } else { /* Pointer fell outside of menu. If the selected entry is * not a submenu, unselect it */ if (menu->selected_entry >= 0 && menu->entries[menu->selected_entry]->cascade < 0) selectEntry(menu, -1); newSelectedEntry = 0; } /* paranoid check */ if (newSelectedEntry >= 0) { /* keep scrolling */ menu->timer = WMAddTimerHandler(MENU_SCROLL_DELAY, dragScrollMenuCallback, menu); } else { menu->timer = NULL; } } else { /* don't need to scroll anymore */ menu->timer = NULL; if (findMenu(scr, &x, &y)) { newSelectedEntry = getEntryAt(menu, x, y); selectEntry(menu, newSelectedEntry); } } } static void scrollMenuCallback(void *data) { WMenu *menu = (WMenu *) data; WMenu *parent = parentMenu(menu); int hamount = 0; /* amount to scroll */ int vamount = 0; getScrollAmount(menu, &hamount, &vamount); if (hamount != 0 || vamount != 0) { wMenuMove(parent, parent->frame_x + hamount, parent->frame_y + vamount, True); /* keep scrolling */ menu->timer = WMAddTimerHandler(MENU_SCROLL_DELAY, scrollMenuCallback, menu); } else { /* don't need to scroll anymore */ menu->timer = NULL; } } #define MENU_SCROLL_BORDER 5 static int isPointNearBorder(WMenu * menu, int x, int y) { int menuX1 = menu->frame_x; int menuY1 = menu->frame_y; int menuX2 = menu->frame_x + MENUW(menu); int menuY2 = menu->frame_y + MENUH(menu); int flag = 0; int head = wGetHeadForPoint(menu->frame->screen_ptr, wmkpoint(x, y)); WMRect rect = wGetRectForHead(menu->frame->screen_ptr, head); /* XXX: handle screen joins properly !! */ if (x >= menuX1 && x <= menuX2 && (y < rect.pos.y + MENU_SCROLL_BORDER || y >= rect.pos.y + rect.size.height - MENU_SCROLL_BORDER)) flag = 1; else if (y >= menuY1 && y <= menuY2 && (x < rect.pos.x + MENU_SCROLL_BORDER || x >= rect.pos.x + rect.size.width - MENU_SCROLL_BORDER)) flag = 1; return flag; } typedef struct _delay { WMenu *menu; int ox, oy; } _delay; static void callback_leaving(void *user_param) { _delay *dl = (_delay *) user_param; wMenuMove(dl->menu, dl->ox, dl->oy, True); dl->menu->jump_back = NULL; dl->menu->menu->screen_ptr->flags.jump_back_pending = 0; wfree(dl); } void wMenuScroll(WMenu *menu) { WMenu *smenu; WMenu *omenu = parentMenu(menu); WScreen *scr = menu->frame->screen_ptr; int done = 0; int jump_back = 0; int old_frame_x = omenu->frame_x; int old_frame_y = omenu->frame_y; XEvent ev; if (omenu->jump_back) WMDeleteTimerWithClientData(omenu->jump_back); if (( /*omenu->flags.buttoned && */ !wPreferences.wrap_menus) || omenu->flags.app_menu) { jump_back = 1; } if (!wPreferences.wrap_menus) raiseMenus(omenu, True); else raiseMenus(menu, False); if (!menu->timer) scrollMenuCallback(menu); while (!done) { int x, y, on_border, on_x_edge, on_y_edge, on_title; WMRect rect; WMNextEvent(dpy, &ev); switch (ev.type) { case EnterNotify: WMHandleEvent(&ev); /* Fall through. */ case MotionNotify: x = (ev.type == MotionNotify) ? ev.xmotion.x_root : ev.xcrossing.x_root; y = (ev.type == MotionNotify) ? ev.xmotion.y_root : ev.xcrossing.y_root; /* on_border is != 0 if the pointer is between the menu * and the screen border and is close enough to the border */ on_border = isPointNearBorder(menu, x, y); smenu = wMenuUnderPointer(scr); if ((smenu == NULL && !on_border) || (smenu && parentMenu(smenu) != omenu)) { done = 1; break; } rect = wGetRectForHead(scr, wGetHeadForPoint(scr, wmkpoint(x, y))); on_x_edge = x <= rect.pos.x + 1 || x >= rect.pos.x + rect.size.width - 2; on_y_edge = y <= rect.pos.y + 1 || y >= rect.pos.y + rect.size.height - 2; on_border = on_x_edge || on_y_edge; if (!on_border && !jump_back) { done = 1; break; } if (menu->timer && (smenu != menu || (!on_y_edge && !on_x_edge))) { WMDeleteTimerHandler(menu->timer); menu->timer = NULL; } if (smenu != NULL) menu = smenu; if (!menu->timer) scrollMenuCallback(menu); break; case ButtonPress: /* True if we push on title, or drag the omenu to other position */ on_title = ev.xbutton.x_root >= omenu->frame_x && ev.xbutton.x_root <= omenu->frame_x + MENUW(omenu) && ev.xbutton.y_root >= omenu->frame_y && ev.xbutton.y_root <= omenu->frame_y + omenu->frame->top_width; WMHandleEvent(&ev); smenu = wMenuUnderPointer(scr); if (smenu == NULL || (smenu && smenu->flags.buttoned && smenu != omenu)) done = 1; else if (smenu == omenu && on_title) { jump_back = 0; done = 1; } break; case KeyPress: done = 1; /* Fall through. */ default: WMHandleEvent(&ev); break; } } if (menu->timer) { WMDeleteTimerHandler(menu->timer); menu->timer = NULL; } if (jump_back) { _delay *delayer; if (!omenu->jump_back) { delayer = wmalloc(sizeof(_delay)); delayer->menu = omenu; delayer->ox = old_frame_x; delayer->oy = old_frame_y; omenu->jump_back = delayer; scr->flags.jump_back_pending = 1; } else delayer = omenu->jump_back; WMAddTimerHandler(MENU_JUMP_BACK_DELAY, callback_leaving, delayer); } } static void menuExpose(WObjDescriptor * desc, XEvent * event) { /* Parameter not used, but tell the compiler that it is ok */ (void) event; wMenuPaint(desc->parent); } typedef struct { int *delayed_select; WMenu *menu; WMHandlerID magic; } delay_data; static void delaySelection(void *data) { delay_data *d = (delay_data *) data; int x, y, entry_no; WMenu *menu; d->magic = NULL; menu = findMenu(d->menu->menu->screen_ptr, &x, &y); if (menu && (d->menu == menu || d->delayed_select)) { entry_no = getEntryAt(menu, x, y); selectEntry(menu, entry_no); } if (d->delayed_select) *(d->delayed_select) = 0; } static void menuMouseDown(WObjDescriptor * desc, XEvent * event) { WWindow *wwin; XButtonEvent *bev = &event->xbutton; WMenu *menu = desc->parent; WMenu *smenu; WScreen *scr = menu->frame->screen_ptr; WMenuEntry *entry = NULL; XEvent ev; int close_on_exit = 0; int done = 0; int delayed_select = 0; int entry_no; int x, y; int prevx, prevy; int old_frame_x = 0; int old_frame_y = 0; delay_data d_data = { NULL, NULL, NULL }; /* Doesn't seem to be needed anymore (if delayed selection handler is * added only if not present). there seem to be no other side effects * from removing this and it is also possible that it was only added * to avoid problems with adding the delayed selection timer handler * multiple times */ /*if (menu->flags.inside_handler) { return; } */ menu->flags.inside_handler = 1; if (!wPreferences.wrap_menus) { smenu = parentMenu(menu); old_frame_x = smenu->frame_x; old_frame_y = smenu->frame_y; } else if (event->xbutton.window == menu->frame->core->window) { /* This is true if the menu was launched with right click on root window */ if (!d_data.magic) { delayed_select = 1; d_data.delayed_select = &delayed_select; d_data.menu = menu; d_data.magic = WMAddTimerHandler(wPreferences.dblclick_time, delaySelection, &d_data); } } wRaiseFrame(menu->frame->core); close_on_exit = (bev->send_event || menu->flags.brother); smenu = findMenu(scr, &x, &y); if (!smenu) { x = -1; y = -1; } else { menu = smenu; } if (menu->flags.editing) { goto byebye; } entry_no = getEntryAt(menu, x, y); if (entry_no >= 0) { entry = menu->entries[entry_no]; if (!close_on_exit && (bev->state & ControlMask) && smenu && entry->flags.editable) { char buffer[128]; char *name; int number = entry_no - 3; /* Entries "New", "Destroy Last" and "Last Used" appear before workspaces */ name = wstrdup(scr->workspaces[number]->name); snprintf(buffer, sizeof(buffer), _("Type the name for workspace %i:"), number + 1); wMenuUnmap(scr->root_menu); if (wInputDialog(scr, _("Rename Workspace"), buffer, &name)) wWorkspaceRename(scr, number, name); if (name) wfree(name); goto byebye; } else if (bev->state & ControlMask) { goto byebye; } if (entry->flags.enabled && entry->cascade >= 0 && menu->cascades) { WMenu *submenu = menu->cascades[entry->cascade]; /* map cascade */ if (submenu->flags.mapped && !submenu->flags.buttoned && menu->selected_entry != entry_no) { wMenuUnmap(submenu); } if (!submenu->flags.mapped && !delayed_select) { selectEntry(menu, entry_no); } else if (!submenu->flags.buttoned) { selectEntry(menu, -1); } } else if (!delayed_select) { if (menu == scr->switch_menu && event->xbutton.button == Button3) { selectEntry(menu, entry_no); OpenWindowMenu2((WWindow *)entry->clientdata, event->xbutton.x_root, event->xbutton.y_root, False); wwin = (WWindow *)entry->clientdata; desc = &wwin->screen_ptr->window_menu->menu->descriptor; event->xany.send_event = True; (*desc->handle_mousedown)(desc, event); XUngrabPointer(dpy, CurrentTime); selectEntry(menu, -1); return; } else { selectEntry(menu, entry_no); } } if (!wPreferences.wrap_menus && !wPreferences.scrollable_menus) { if (!menu->timer) dragScrollMenuCallback(menu); } } prevx = bev->x_root; prevy = bev->y_root; while (!done) { int x, y; XAllowEvents(dpy, AsyncPointer | SyncPointer, CurrentTime); WMMaskEvent(dpy, ExposureMask | ButtonMotionMask | ButtonReleaseMask | ButtonPressMask, &ev); switch (ev.type) { case MotionNotify: smenu = findMenu(scr, &x, &y); if (smenu == NULL) { /* moved mouse out of menu */ if (!delayed_select && d_data.magic) { WMDeleteTimerHandler(d_data.magic); d_data.magic = NULL; } if (menu == NULL || (menu->selected_entry >= 0 && menu->entries[menu->selected_entry]->cascade >= 0)) { prevx = ev.xmotion.x_root; prevy = ev.xmotion.y_root; break; } selectEntry(menu, -1); menu = smenu; prevx = ev.xmotion.x_root; prevy = ev.xmotion.y_root; break; } else if (menu && menu != smenu && (menu->selected_entry < 0 || menu->entries[menu->selected_entry]->cascade < 0)) { selectEntry(menu, -1); if (!delayed_select && d_data.magic) { WMDeleteTimerHandler(d_data.magic); d_data.magic = NULL; } } else { /* hysteresis for item selection */ /* check if the motion was to the side, indicating that * the user may want to cross to a submenu */ if (!delayed_select && menu) { int dx; Bool moved_to_submenu; /* moved to direction of submenu */ dx = abs(prevx - ev.xmotion.x_root); moved_to_submenu = False; if (dx > 0 /* if moved enough to the side */ /* maybe a open submenu */ && menu->selected_entry >= 0 /* moving to the right direction */ && (wPreferences.align_menus || ev.xmotion.y_root >= prevy)) { int index; index = menu->entries[menu->selected_entry]->cascade; if (index >= 0) { if (menu->cascades[index]->frame_x > menu->frame_x) { if (prevx < ev.xmotion.x_root) moved_to_submenu = True; } else { if (prevx > ev.xmotion.x_root) moved_to_submenu = True; } } } if (menu != smenu) { if (d_data.magic) { WMDeleteTimerHandler(d_data.magic); d_data.magic = NULL; } } else if (moved_to_submenu) { /* while we are moving, postpone the selection */ if (d_data.magic) { WMDeleteTimerHandler(d_data.magic); } d_data.delayed_select = NULL; d_data.menu = menu; d_data.magic = WMAddTimerHandler(MENU_SELECT_DELAY, delaySelection, &d_data); prevx = ev.xmotion.x_root; prevy = ev.xmotion.y_root; break; } else { if (d_data.magic) { WMDeleteTimerHandler(d_data.magic); d_data.magic = NULL; } } } } prevx = ev.xmotion.x_root; prevy = ev.xmotion.y_root; if (menu != smenu) { /* pointer crossed menus */ if (menu && menu->timer) { WMDeleteTimerHandler(menu->timer); menu->timer = NULL; } if (smenu) dragScrollMenuCallback(smenu); } menu = smenu; if (!menu->timer) dragScrollMenuCallback(menu); if (!delayed_select) { entry_no = getEntryAt(menu, x, y); if (entry_no >= 0) { entry = menu->entries[entry_no]; if (entry->flags.enabled && entry->cascade >= 0 && menu->cascades) { WMenu *submenu = menu->cascades[entry->cascade]; if (submenu->flags.mapped && !submenu->flags.buttoned && menu->selected_entry != entry_no) { wMenuUnmap(submenu); } } } selectEntry(menu, entry_no); } break; case ButtonPress: break; case ButtonRelease: if (ev.xbutton.button == event->xbutton.button) done = 1; break; case Expose: diff --git a/src/moveres.c b/src/moveres.c index 9f7a91d..4e0d7de 100644 --- a/src/moveres.c +++ b/src/moveres.c @@ -1493,987 +1493,987 @@ int wKeyboardMoveResizeWindow(WWindow * wwin) #endif case XK_h: if (ctrlmode) { if (moment != LEFT) w = ww; w -= kspeed; if (w < 1) w = 1; moment = LEFT; } else off_x -= kspeed; break; case XK_Right: #ifdef XK_KP_Right case XK_KP_Right: #endif case XK_l: if (ctrlmode) { if (moment != RIGHT) w = ww; w += kspeed; moment = RIGHT; } else off_x += kspeed; break; } ww = w; wh = h; wh -= vert_border; wWindowConstrainSize(wwin, (unsigned int *)&ww, (unsigned int *)&wh); wh += vert_border; if (wPreferences.ws_cycle) { if (src_x + off_x + ww < 20) { if (!scr->current_workspace) wWorkspaceChange(scr, scr->workspace_count - 1); else wWorkspaceChange(scr, scr->current_workspace - 1); off_x += scr_width; } else if (src_x + off_x + 20 > scr_width) { if (scr->current_workspace == scr->workspace_count - 1) wWorkspaceChange(scr, 0); else wWorkspaceChange(scr, scr->current_workspace + 1); off_x -= scr_width; } } else { if (src_x + off_x + ww < 20) off_x = 20 - ww - src_x; else if (src_x + off_x + 20 > scr_width) off_x = scr_width - 20 - src_x; } if (src_y + off_y + wh < 20) { off_y = 20 - wh - src_y; } else if (src_y + off_y + 20 > scr_height) { off_y = scr_height - 20 - src_y; } } break; case ButtonPress: case ButtonRelease: done = 1; break; case Expose: WMHandleEvent(&event); while (XCheckTypedEvent(dpy, Expose, &event)) { WMHandleEvent(&event); } break; default: WMHandleEvent(&event); break; } XGrabServer(dpy); /*xxx */ if (wwin->flags.shaded && !scr->selected_windows) { moveGeometryDisplayCentered(scr, src_x + off_x + w / 2, src_y + off_y + h / 2); } else { if (ctrlmode) { WMUnmapWidget(scr->gview); mapGeometryDisplay(wwin, src_x + off_x, src_y + off_y, ww, wh); } else if (!scr->selected_windows) { WMUnmapWidget(scr->gview); mapPositionDisplay(wwin, src_x + off_x, src_y + off_y, ww, wh); } } if (!opaqueMoveResize) { if (wwin->flags.shaded || scr->selected_windows) { if (scr->selected_windows) drawFrames(wwin, scr->selected_windows, off_x, off_y); else drawTransparentFrame(wwin, src_x + off_x, src_y + off_y, w, h); } else { drawTransparentFrame(wwin, src_x + off_x, src_y + off_y, ww, wh); } } if (ctrlmode) { showGeometry(wwin, src_x + off_x, src_y + off_y, src_x + off_x + ww, src_y + off_y + wh, 0); } else if (!scr->selected_windows) showPosition(wwin, src_x + off_x, src_y + off_y); if (opaqueMoveResize) { XUngrabServer(dpy); wWindowConfigure(wwin, src_x + off_x, src_y + off_y, ww, wh - vert_border); }; if (done) { if (!opaqueMoveResize) { /* ctrlmode => resize */ if (wwin->flags.shaded || scr->selected_windows) { if (scr->selected_windows) drawFrames(wwin, scr->selected_windows, off_x, off_y); else drawTransparentFrame(wwin, src_x + off_x, src_y + off_y, w, h); } else { drawTransparentFrame(wwin, src_x + off_x, src_y + off_y, ww, wh); } } if (ctrlmode) { showGeometry(wwin, src_x + off_x, src_y + off_y, src_x + off_x + ww, src_y + off_y + wh, 0); WMUnmapWidget(scr->gview); } else WMUnmapWidget(scr->gview); XUngrabKeyboard(dpy, CurrentTime); XUngrabPointer(dpy, CurrentTime); XUngrabServer(dpy); if (done == 2) { if (wwin->flags.shaded || scr->selected_windows) { if (!scr->selected_windows) { wWindowMove(wwin, src_x + off_x, src_y + off_y); wWindowSynthConfigureNotify(wwin); } else { WMArrayIterator iter; WWindow *foo; doWindowMove(wwin, scr->selected_windows, off_x, off_y); WM_ITERATE_ARRAY(scr->selected_windows, foo, iter) { wWindowSynthConfigureNotify(foo); } } } else { if (ww != original_w) wwin->flags.maximized &= ~(MAX_HORIZONTAL | MAX_TOPHALF | MAX_BOTTOMHALF | MAX_MAXIMUS); if (wh != original_h) wwin->flags.maximized &= ~(MAX_VERTICAL | MAX_LEFTHALF | MAX_RIGHTHALF | MAX_MAXIMUS); wWindowConfigure(wwin, src_x + off_x, src_y + off_y, ww, wh - vert_border); wWindowSynthConfigureNotify(wwin); } wWindowChangeWorkspace(wwin, scr->current_workspace); wSetFocusTo(scr, wwin); } if (wPreferences.auto_arrange_icons && wXineramaHeads(scr) > 1 && head != wGetHeadForWindow(wwin)) { wArrangeIcons(scr, True); } update_saved_geometry(wwin); return 1; } } } /* *---------------------------------------------------------------------- * wMouseMoveWindow-- * Move the named window and the other selected ones (if any), * interactively. Also shows the position of the window, if only one * window is being moved. * If the window is not on the selected window list, the selected * windows are deselected. * If shift is pressed during the operation, the position display * is changed to another type. * * Returns: * True if the window was moved, False otherwise. * * Side effects: * The window(s) position is changed, and the client(s) are * notified about that. * The position display configuration may be changed. *---------------------------------------------------------------------- */ int wMouseMoveWindow(WWindow * wwin, XEvent * ev) { WScreen *scr = wwin->screen_ptr; XEvent event; Window root = scr->root_win; KeyCode shiftl, shiftr; Bool done = False; int started = 0; int warped = 0; /* This needs not to change while moving, else bad things can happen */ int opaqueMove = wPreferences.opaque_move; MoveData moveData; int head = ((wPreferences.auto_arrange_icons && wXineramaHeads(scr) > 1) ? wGetHeadForWindow(wwin) : scr->xine_info.primary_head); if (!IS_MOVABLE(wwin)) return False; if (wPreferences.opaque_move && !wPreferences.use_saveunders) { XSetWindowAttributes attr; attr.save_under = True; XChangeWindowAttributes(dpy, wwin->frame->core->window, CWSaveUnder, &attr); } initMoveData(wwin, &moveData); moveData.mouseX = ev->xmotion.x_root; moveData.mouseY = ev->xmotion.y_root; if (!wwin->flags.selected) { /* this window is not selected, unselect others and move only wwin */ wUnselectWindows(scr); } shiftl = XKeysymToKeycode(dpy, XK_Shift_L); shiftr = XKeysymToKeycode(dpy, XK_Shift_R); while (!done) { if (warped) { int junk; Window junkw; /* XWarpPointer() doesn't seem to generate Motion events, so * we've got to simulate them */ XQueryPointer(dpy, root, &junkw, &junkw, &event.xmotion.x_root, &event.xmotion.y_root, &junk, &junk, (unsigned *)&junk); } else { WMMaskEvent(dpy, KeyPressMask | ButtonMotionMask | PointerMotionHintMask | ButtonReleaseMask | ButtonPressMask | ExposureMask, &event); if (event.type == MotionNotify) { /* compress MotionNotify events */ while (XCheckMaskEvent(dpy, ButtonMotionMask, &event)) ; if (!checkMouseSamplingRate(&event)) continue; } } switch (event.type) { case KeyPress: if ((event.xkey.keycode == shiftl || event.xkey.keycode == shiftr) && started && !scr->selected_windows) { if (!opaqueMove) { drawFrames(wwin, scr->selected_windows, moveData.realX - wwin->frame_x, moveData.realY - wwin->frame_y); } if (wPreferences.move_display == WDIS_NEW && !scr->selected_windows) { showPosition(wwin, moveData.realX, moveData.realY); XUngrabServer(dpy); } cyclePositionDisplay(wwin, moveData.realX, moveData.realY, moveData.winWidth, moveData.winHeight); if (wPreferences.move_display == WDIS_NEW && !scr->selected_windows) { XGrabServer(dpy); showPosition(wwin, moveData.realX, moveData.realY); } if (!opaqueMove) { drawFrames(wwin, scr->selected_windows, moveData.realX - wwin->frame_x, moveData.realY - wwin->frame_y); } /*} else { WMHandleEvent(&event); this causes problems needs fixing */ } break; case MotionNotify: if (IS_RESIZABLE(wwin) && wPreferences.window_snapping) { int snap_direction; snap_direction = get_snap_direction(scr, moveData.mouseX, moveData.mouseY); if (!wPreferences.no_autowrap && snap_direction != SNAP_TOP && snap_direction != SNAP_BOTTOM) snap_direction = SNAP_NONE; if (moveData.snap != snap_direction) { /* erase old frame */ if (moveData.snap) draw_snap_frame(wwin, moveData.snap); /* draw new frame */ if (snap_direction) draw_snap_frame(wwin, snap_direction); moveData.snap = snap_direction; } } if (started) { /* erase snap frame */ if (moveData.snap) draw_snap_frame(wwin, moveData.snap); updateWindowPosition(wwin, &moveData, scr->selected_windows == NULL && wPreferences.edge_resistance > 0, opaqueMove, event.xmotion.x_root, event.xmotion.y_root); /* redraw snap frame */ if (moveData.snap) draw_snap_frame(wwin, moveData.snap); if (!warped && !wPreferences.no_autowrap) { int oldWorkspace = scr->current_workspace; if (wPreferences.move_display == WDIS_NEW && !scr->selected_windows) { showPosition(wwin, moveData.realX, moveData.realY); XUngrabServer(dpy); } if (!opaqueMove) { drawFrames(wwin, scr->selected_windows, moveData.realX - wwin->frame_x, moveData.realY - wwin->frame_y); } if (checkWorkspaceChange(wwin, &moveData, opaqueMove)) { if (scr->current_workspace != oldWorkspace && wPreferences.edge_resistance > 0 && scr->selected_windows == NULL) updateMoveData(wwin, &moveData); warped = 1; } if (!opaqueMove) { drawFrames(wwin, scr->selected_windows, moveData.realX - wwin->frame_x, moveData.realY - wwin->frame_y); } if (wPreferences.move_display == WDIS_NEW && !scr->selected_windows) { XSync(dpy, False); showPosition(wwin, moveData.realX, moveData.realY); XGrabServer(dpy); } } else { warped = 0; } } else if (abs(ev->xmotion.x_root - event.xmotion.x_root) >= MOVE_THRESHOLD || abs(ev->xmotion.y_root - event.xmotion.y_root) >= MOVE_THRESHOLD) { if (wwin->flags.maximized) { if (wPreferences.drag_maximized_window == DRAGMAX_RESTORE) { float titlebar_ratio; int new_x, new_y; titlebar_ratio = (moveData.mouseX - wwin->frame_x) / (float)wwin->frame->core->width; new_y = wwin->frame_y; wUnmaximizeWindow(wwin); new_x = moveData.mouseX - titlebar_ratio * wwin->frame->core->width; wWindowMove(wwin, new_x, new_y); moveData.realX = moveData.calcX = wwin->frame_x; moveData.realY = moveData.calcY = wwin->frame_y; } if (wPreferences.drag_maximized_window == DRAGMAX_UNMAXIMIZE) { wwin->flags.maximized = 0; wwin->flags.old_maximized = 0; } } XChangeActivePointerGrab(dpy, ButtonMotionMask | ButtonReleaseMask | ButtonPressMask, wPreferences.cursor[WCUR_MOVE], CurrentTime); started = 1; XGrabKeyboard(dpy, root, False, GrabModeAsync, GrabModeAsync, CurrentTime); if (!scr->selected_windows) mapPositionDisplay(wwin, moveData.realX, moveData.realY, moveData.winWidth, moveData.winHeight); if (started && !opaqueMove) drawFrames(wwin, scr->selected_windows, 0, 0); if (!opaqueMove || (wPreferences.move_display == WDIS_NEW && !scr->selected_windows)) { XGrabServer(dpy); if (wPreferences.move_display == WDIS_NEW) showPosition(wwin, moveData.realX, moveData.realY); } } break; case ButtonPress: break; case ButtonRelease: if (event.xbutton.button != ev->xbutton.button) break; if (started) { XEvent e; if (moveData.snap) do_snap(wwin, &moveData, opaqueMove); else if (!opaqueMove) { drawFrames(wwin, scr->selected_windows, moveData.realX - wwin->frame_x, moveData.realY - wwin->frame_y); XSync(dpy, 0); doWindowMove(wwin, scr->selected_windows, moveData.realX - wwin->frame_x, moveData.realY - wwin->frame_y); } #ifndef CONFIGURE_WINDOW_WHILE_MOVING wWindowSynthConfigureNotify(wwin); #endif XUngrabKeyboard(dpy, CurrentTime); XUngrabServer(dpy); if (!opaqueMove) { wWindowChangeWorkspace(wwin, scr->current_workspace); wSetFocusTo(scr, wwin); } if (wPreferences.move_display == WDIS_NEW) showPosition(wwin, moveData.realX, moveData.realY); /* discard all enter/leave events that happened until * the time the button was released */ while (XCheckTypedEvent(dpy, EnterNotify, &e)) { if (e.xcrossing.time > event.xbutton.time) { XPutBackEvent(dpy, &e); break; } } while (XCheckTypedEvent(dpy, LeaveNotify, &e)) { if (e.xcrossing.time > event.xbutton.time) { XPutBackEvent(dpy, &e); break; } } if (!scr->selected_windows) { /* get rid of the geometry window */ WMUnmapWidget(scr->gview); } } done = True; break; default: if (started && !opaqueMove) { drawFrames(wwin, scr->selected_windows, moveData.realX - wwin->frame_x, moveData.realY - wwin->frame_y); XUngrabServer(dpy); WMHandleEvent(&event); XSync(dpy, False); XGrabServer(dpy); drawFrames(wwin, scr->selected_windows, moveData.realX - wwin->frame_x, moveData.realY - wwin->frame_y); } else { WMHandleEvent(&event); } break; } } if (wPreferences.opaque_move && !wPreferences.use_saveunders) { XSetWindowAttributes attr; attr.save_under = False; XChangeWindowAttributes(dpy, wwin->frame->core->window, CWSaveUnder, &attr); } freeMoveData(&moveData); if (started && wPreferences.auto_arrange_icons && wXineramaHeads(scr) > 1 && head != wGetHeadForWindow(wwin)) { wArrangeIcons(scr, True); } if (started) update_saved_geometry(wwin); return started; } #define RESIZEBAR 1 #define HCONSTRAIN 2 static int getResizeDirection(WWindow * wwin, int x, int y, int dy, int flags) { int w = wwin->frame->core->width - 1; int cw = wwin->frame->resizebar_corner_width; int dir; /* if not resizing through the resizebar */ if (!(flags & RESIZEBAR)) { int xdir = (abs(x) < (wwin->client.width / 2)) ? LEFT : RIGHT; int ydir = (abs(y) < (wwin->client.height / 2)) ? UP : DOWN; /* How much resize space is allowed */ - int spacew = abs(wwin->client.width / 3); - int spaceh = abs(wwin->client.height / 3); + int spacew = wwin->client.width / 3; + int spaceh = wwin->client.height / 3; /* Determine where x fits */ if ((abs(x) > wwin->client.width/2 - spacew/2) && (abs(x) < wwin->client.width/2 + spacew/2)) { /* Resize vertically */ xdir = 0; } else if ((abs(y) > wwin->client.height/2 - spaceh/2) && (abs(y) < wwin->client.height/2 + spaceh/2)) { /* Resize horizontally */ ydir = 0; } return (xdir | ydir); } /* window is too narrow. allow diagonal resize */ if (cw * 2 >= w) { int ydir; if (flags & HCONSTRAIN) ydir = 0; else ydir = DOWN; if (x < cw) return (LEFT | ydir); else return (RIGHT | ydir); } /* vertical resize */ if ((x > cw) && (x < w - cw)) return DOWN; if (x < cw) dir = LEFT; else dir = RIGHT; if ((abs(dy) > 0) && !(flags & HCONSTRAIN)) dir |= DOWN; return dir; } void wMouseResizeWindow(WWindow * wwin, XEvent * ev) { XEvent event; WScreen *scr = wwin->screen_ptr; Window root = scr->root_win; int vert_border = wwin->frame->top_width + wwin->frame->bottom_width; int fw = wwin->frame->core->width; int fh = wwin->frame->core->height; int fx = wwin->frame_x; int fy = wwin->frame_y; int is_resizebar = (wwin->frame->resizebar && ev->xany.window == wwin->frame->resizebar->window); int orig_x, orig_y; int started; int dw, dh; int rw = fw, rh = fh; int rx1, ry1, rx2, ry2; int res = 0; KeyCode shiftl, shiftr; int orig_fx = fx; int orig_fy = fy; int orig_fw = fw; int orig_fh = fh; int original_fw = fw; int original_fh = fh; int head = ((wPreferences.auto_arrange_icons && wXineramaHeads(scr) > 1) ? wGetHeadForWindow(wwin) : scr->xine_info.primary_head); int opaqueResize = wPreferences.opaque_resize; if (!IS_RESIZABLE(wwin)) return; if (wwin->flags.shaded) { wwarning("internal error: tryein"); return; } orig_x = ev->xbutton.x_root; orig_y = ev->xbutton.y_root; started = 0; wUnselectWindows(scr); rx1 = fx; rx2 = fx + fw - 1; ry1 = fy; ry2 = fy + fh - 1; shiftl = XKeysymToKeycode(dpy, XK_Shift_L); shiftr = XKeysymToKeycode(dpy, XK_Shift_R); while (1) { WMMaskEvent(dpy, KeyPressMask | ButtonMotionMask | ButtonReleaseMask | PointerMotionHintMask | ButtonPressMask | ExposureMask, &event); if (!checkMouseSamplingRate(&event)) continue; switch (event.type) { case KeyPress: showGeometry(wwin, fx, fy, fx + fw, fy + fh, res); if (!opaqueResize) { if ((event.xkey.keycode == shiftl || event.xkey.keycode == shiftr) && started) { drawTransparentFrame(wwin, fx, fy, fw, fh); cycleGeometryDisplay(wwin, fx, fy, fw, fh, res); drawTransparentFrame(wwin, fx, fy, fw, fh); } }; showGeometry(wwin, fx, fy, fx + fw, fy + fh, res); break; case MotionNotify: if (started) { while (XCheckMaskEvent(dpy, ButtonMotionMask, &event)) ; dw = 0; dh = 0; orig_fx = fx; orig_fy = fy; orig_fw = fw; orig_fh = fh; if (res & LEFT) dw = orig_x - event.xmotion.x_root; else if (res & RIGHT) dw = event.xmotion.x_root - orig_x; if (res & UP) dh = orig_y - event.xmotion.y_root; else if (res & DOWN) dh = event.xmotion.y_root - orig_y; orig_x = event.xmotion.x_root; orig_y = event.xmotion.y_root; rw += dw; rh += dh; fw = rw; fh = rh - vert_border; wWindowConstrainSize(wwin, (unsigned int *)&fw, (unsigned int *)&fh); fh += vert_border; if (res & LEFT) fx = rx2 - fw + 1; else if (res & RIGHT) fx = rx1; if (res & UP) fy = ry2 - fh + 1; else if (res & DOWN) fy = ry1; } else if (abs(orig_x - event.xmotion.x_root) >= MOVE_THRESHOLD || abs(orig_y - event.xmotion.y_root) >= MOVE_THRESHOLD) { int tx, ty; Window junkw; int flags; XTranslateCoordinates(dpy, root, wwin->frame->core->window, orig_x, orig_y, &tx, &ty, &junkw); /* check if resizing through resizebar */ if (is_resizebar) flags = RESIZEBAR; else flags = 0; if (is_resizebar && ((ev->xbutton.state & ShiftMask) || abs(orig_y - event.xmotion.y_root) < HRESIZE_THRESHOLD)) flags |= HCONSTRAIN; res = getResizeDirection(wwin, tx, ty, orig_y - event.xmotion.y_root, flags); if (res == (UP | LEFT)) XChangeActivePointerGrab(dpy, ButtonMotionMask | ButtonReleaseMask | ButtonPressMask, wPreferences.cursor[WCUR_TOPLEFTRESIZE], CurrentTime); else if (res == (UP | RIGHT)) XChangeActivePointerGrab(dpy, ButtonMotionMask | ButtonReleaseMask | ButtonPressMask, wPreferences.cursor[WCUR_TOPRIGHTRESIZE], CurrentTime); else if (res == (DOWN | LEFT)) XChangeActivePointerGrab(dpy, ButtonMotionMask | ButtonReleaseMask | ButtonPressMask, wPreferences.cursor[WCUR_BOTTOMLEFTRESIZE], CurrentTime); else if (res == (DOWN | RIGHT)) XChangeActivePointerGrab(dpy, ButtonMotionMask | ButtonReleaseMask | ButtonPressMask, wPreferences.cursor[WCUR_BOTTOMRIGHTRESIZE], CurrentTime); else if (res == DOWN || res == UP) XChangeActivePointerGrab(dpy, ButtonMotionMask | ButtonReleaseMask | ButtonPressMask, wPreferences.cursor[WCUR_VERTICALRESIZE], CurrentTime); else if (res & (DOWN | UP)) XChangeActivePointerGrab(dpy, ButtonMotionMask | ButtonReleaseMask | ButtonPressMask, wPreferences.cursor[WCUR_VERTICALRESIZE], CurrentTime); else if (res & (LEFT | RIGHT)) XChangeActivePointerGrab(dpy, ButtonMotionMask | ButtonReleaseMask | ButtonPressMask, wPreferences.cursor[WCUR_HORIZONRESIZE], CurrentTime); XGrabKeyboard(dpy, root, False, GrabModeAsync, GrabModeAsync, CurrentTime); XGrabServer(dpy); /* Draw the resize frame for the first time. */ mapGeometryDisplay(wwin, fx, fy, fw, fh); if (!opaqueResize) drawTransparentFrame(wwin, fx, fy, fw, fh); showGeometry(wwin, fx, fy, fx + fw, fy + fh, res); started = 1; } if (started) { if (!opaqueResize) drawTransparentFrame(wwin, orig_fx, orig_fy, orig_fw, orig_fh); if (wPreferences.size_display == WDIS_FRAME_CENTER) moveGeometryDisplayCentered(scr, fx + fw / 2, fy + fh / 2); if (!opaqueResize) drawTransparentFrame(wwin, fx, fy, fw, fh); if (fh != orig_fh || fw != orig_fw) { if (wPreferences.size_display == WDIS_NEW) showGeometry(wwin, orig_fx, orig_fy, orig_fx + orig_fw, orig_fy + orig_fh, res); showGeometry(wwin, fx, fy, fx + fw, fy + fh, res); } if (opaqueResize) { /* Fist clean the geometry line */ showGeometry(wwin, fx, fy, fx + fw, fy + fh, res); /* Now, continue drawing */ XUngrabServer(dpy); moveGeometryDisplayCentered(scr, fx + fw / 2, fy + fh / 2); wWindowConfigure(wwin, fx, fy, fw, fh - vert_border); showGeometry(wwin, fx, fy, fx + fw, fy + fh, res); }; } break; case ButtonPress: break; case ButtonRelease: if (event.xbutton.button != ev->xbutton.button) break; if (started) { showGeometry(wwin, fx, fy, fx + fw, fy + fh, res); if (!opaqueResize) drawTransparentFrame(wwin, fx, fy, fw, fh); XUngrabKeyboard(dpy, CurrentTime); WMUnmapWidget(scr->gview); XUngrabServer(dpy); if (fw != original_fw) wwin->flags.maximized &= ~(MAX_HORIZONTAL | MAX_TOPHALF | MAX_BOTTOMHALF | MAX_MAXIMUS); if (fh != original_fh) wwin->flags.maximized &= ~(MAX_VERTICAL | MAX_LEFTHALF | MAX_RIGHTHALF | MAX_MAXIMUS); wWindowConfigure(wwin, fx, fy, fw, fh - vert_border); wWindowSynthConfigureNotify(wwin); } return; default: WMHandleEvent(&event); } } if (wPreferences.auto_arrange_icons && wXineramaHeads(scr) > 1 && head != wGetHeadForWindow(wwin)) wArrangeIcons(scr, True); } #undef LEFT #undef RIGHT #undef UP #undef DOWN #undef HCONSTRAIN #undef RESIZEBAR void wUnselectWindows(WScreen * scr) { WWindow *wwin; if (!scr->selected_windows) return; while (WMGetArrayItemCount(scr->selected_windows)) { wwin = WMGetFromArray(scr->selected_windows, 0); if (wwin->flags.miniaturized && wwin->icon && wwin->icon->selected) wIconSelect(wwin->icon); wSelectWindow(wwin, False); } WMFreeArray(scr->selected_windows); scr->selected_windows = NULL; } static void selectWindowsInside(WScreen * scr, int x1, int y1, int x2, int y2) { WWindow *tmpw; /* select the windows and put them in the selected window list */ tmpw = scr->focused_window; while (tmpw != NULL) { if (!(tmpw->flags.miniaturized || tmpw->flags.hidden)) { if ((tmpw->frame->workspace == scr->current_workspace || IS_OMNIPRESENT(tmpw)) && (tmpw->frame_x >= x1) && (tmpw->frame_y >= y1) && (tmpw->frame->core->width + tmpw->frame_x <= x2) && (tmpw->frame->core->height + tmpw->frame_y <= y2)) { wSelectWindow(tmpw, True); } } tmpw = tmpw->prev; } } void wSelectWindows(WScreen * scr, XEvent * ev) { XEvent event; Window root = scr->root_win; GC gc = scr->frame_gc; int xp = ev->xbutton.x_root; int yp = ev->xbutton.y_root; int w = 0, h = 0; int x = xp, y = yp; if (XGrabPointer(dpy, scr->root_win, False, ButtonMotionMask | ButtonReleaseMask | ButtonPressMask, GrabModeAsync, GrabModeAsync, None, wPreferences.cursor[WCUR_NORMAL], CurrentTime) != Success) { return; } XGrabServer(dpy); wUnselectWindows(scr); XDrawRectangle(dpy, root, gc, xp, yp, w, h); while (1) { WMMaskEvent(dpy, ButtonReleaseMask | PointerMotionMask | ButtonPressMask, &event); switch (event.type) { case MotionNotify: XDrawRectangle(dpy, root, gc, x, y, w, h); x = event.xmotion.x_root; if (x < xp) { w = xp - x; } else { w = x - xp; x = xp; } y = event.xmotion.y_root; if (y < yp) { h = yp - y; } else { h = y - yp; y = yp; } XDrawRectangle(dpy, root, gc, x, y, w, h); break; case ButtonPress: break; case ButtonRelease: if (event.xbutton.button != ev->xbutton.button) break; XDrawRectangle(dpy, root, gc, x, y, w, h); XUngrabServer(dpy); XUngrabPointer(dpy, CurrentTime); selectWindowsInside(scr, x, y, x + w, y + h); return; default: WMHandleEvent(&event); break; } } } void InteractivePlaceWindow(WWindow * wwin, int *x_ret, int *y_ret, unsigned width, unsigned height) { WScreen *scr = wwin->screen_ptr; Window root = scr->root_win; int x, y, h = 0; XEvent event; KeyCode shiftl, shiftr; Window junkw; int junk; if (XGrabPointer(dpy, root, True, PointerMotionMask | ButtonPressMask, GrabModeAsync, GrabModeAsync, None, wPreferences.cursor[WCUR_NORMAL], CurrentTime) != Success) { *x_ret = 0; *y_ret = 0; return; } if (HAS_TITLEBAR(wwin)) { h = WMFontHeight(scr->title_font) + (wPreferences.window_title_clearance + TITLEBAR_EXTEND_SPACE) * 2; if (h > wPreferences.window_title_max_height) h = wPreferences.window_title_max_height; if (h < wPreferences.window_title_min_height) h = wPreferences.window_title_min_height; height += h; } if (HAS_RESIZEBAR(wwin)) { height += RESIZEBAR_HEIGHT; } XGrabKeyboard(dpy, root, False, GrabModeAsync, GrabModeAsync, CurrentTime); XQueryPointer(dpy, root, &junkw, &junkw, &x, &y, &junk, &junk, (unsigned *)&junk); mapPositionDisplay(wwin, x - width / 2, y - h / 2, width, height); drawTransparentFrame(wwin, x - width / 2, y - h / 2, width, height); shiftl = XKeysymToKeycode(dpy, XK_Shift_L); shiftr = XKeysymToKeycode(dpy, XK_Shift_R); while (1) { WMMaskEvent(dpy, PointerMotionMask | ButtonPressMask | ExposureMask | KeyPressMask, &event); if (!checkMouseSamplingRate(&event)) continue; switch (event.type) { case KeyPress: if ((event.xkey.keycode == shiftl) || (event.xkey.keycode == shiftr)) { drawTransparentFrame(wwin, x - width / 2, y - h / 2, width, height); cyclePositionDisplay(wwin, x - width / 2, y - h / 2, width, height); drawTransparentFrame(wwin, x - width / 2, y - h / 2, width, height); } break; case MotionNotify: drawTransparentFrame(wwin, x - width / 2, y - h / 2, width, height); x = event.xmotion.x_root; y = event.xmotion.y_root; if (wPreferences.move_display == WDIS_FRAME_CENTER) moveGeometryDisplayCentered(scr, x, y + (height - h) / 2); showPosition(wwin, x - width / 2, y - h / 2); drawTransparentFrame(wwin, x - width / 2, y - h / 2, width, height); break; case ButtonPress: drawTransparentFrame(wwin, x - width / 2, y - h / 2, width, height); XSync(dpy, 0); *x_ret = x - width / 2; *y_ret = y - h / 2; XUngrabPointer(dpy, CurrentTime); XUngrabKeyboard(dpy, CurrentTime); /* get rid of the geometry window */ WMUnmapWidget(scr->gview); return; default: WMHandleEvent(&event); break; } } } diff --git a/src/window.c b/src/window.c index 195c3e6..a276f48 100644 --- a/src/window.c +++ b/src/window.c @@ -488,1027 +488,1027 @@ static void fixLeaderProperties(WWindow *wwin) classHint = XAllocClassHint(); clientHints = XGetWMHints(dpy, wwin->client_win); pid = wNETWMGetPidForWindow(wwin->client_win); if (pid > 0) haveCommand = GetCommandForPid(pid, &argv, &argc); else haveCommand = False; leaders[0] = wwin->client_leader; leaders[1] = wwin->group_id; if (haveCommand) { command = GetCommandForWindow(wwin->client_win); if (command) wfree(command); /* command already set. nothing to do. */ else XSetCommand(dpy, wwin->client_win, argv, argc); } for (i = 0; i < 2; i++) { window = leaders[i]; if (window) { if (XGetClassHint(dpy, window, classHint) == 0) { classHint->res_name = wwin->wm_instance; classHint->res_class = wwin->wm_class; XSetClassHint(dpy, window, classHint); } hints = XGetWMHints(dpy, window); if (hints) { XFree(hints); } else if (clientHints) { /* set window group leader to self */ clientHints->window_group = window; clientHints->flags |= WindowGroupHint; XSetWMHints(dpy, window, clientHints); } if (haveCommand) { command = GetCommandForWindow(window); if (command) wfree(command); /* command already set. nothing to do. */ else XSetCommand(dpy, window, argv, argc); } /* Make sure we get notification when this window is destroyed */ if (XGetWindowAttributes(dpy, window, &attr)) XSelectInput(dpy, window, attr.your_event_mask | StructureNotifyMask | PropertyChangeMask); } } XFree(classHint); if (clientHints) XFree(clientHints); if (haveCommand) wfree(argv); } static Window createFakeWindowGroupLeader(WScreen *scr, Window win, char *instance, char *class) { XClassHint *classHint; XWMHints *hints; Window leader; int argc; char **argv; leader = XCreateSimpleWindow(dpy, scr->root_win, 10, 10, 10, 10, 0, 0, 0); /* set class hint */ classHint = XAllocClassHint(); classHint->res_name = instance; classHint->res_class = class; XSetClassHint(dpy, leader, classHint); XFree(classHint); /* inherit these from the original leader if available */ hints = XGetWMHints(dpy, win); if (!hints) { hints = XAllocWMHints(); hints->flags = 0; } /* set window group leader to self */ hints->window_group = leader; hints->flags |= WindowGroupHint; XSetWMHints(dpy, leader, hints); XFree(hints); if (XGetCommand(dpy, win, &argv, &argc) != 0 && argc > 0) { XSetCommand(dpy, leader, argv, argc); XFreeStringList(argv); } return leader; } static int matchIdentifier(const void *item, const void *cdata) { return (strcmp(((WFakeGroupLeader *) item)->identifier, (char *)cdata) == 0); } /* *---------------------------------------------------------------- * wManageWindow-- * reparents the window and allocates a descriptor for it. * Window manager hints and other hints are fetched to configure * the window decoration attributes and others. User preferences * for the window are used if available, to configure window * decorations and some behaviour. * If in startup, windows that are override redirect, * unmapped and never were managed and are Withdrawn are not * managed. * * Returns: * the new window descriptor * * Side effects: * The window is reparented and appropriate notification * is done to the client. Input mask for the window is setup. * The window descriptor is also associated with various window * contexts and inserted in the head of the window list. * Event handler contexts are associated for some objects * (buttons, titlebar and resizebar) * *---------------------------------------------------------------- */ WWindow *wManageWindow(WScreen *scr, Window window) { WWindow *wwin; int x, y; unsigned width, height; XWindowAttributes wattribs; XSetWindowAttributes attribs; WWindowState *win_state; WWindow *transientOwner = NULL; int window_level; int wm_state; int foo; int workspace = -1; char *title; Bool withdraw = False; Bool raise = False; /* mutex. */ XGrabServer(dpy); XSync(dpy, False); /* make sure the window is still there */ if (!XGetWindowAttributes(dpy, window, &wattribs)) { XUngrabServer(dpy); return NULL; } /* if it's an override-redirect, ignore it */ if (wattribs.override_redirect) { XUngrabServer(dpy); return NULL; } wm_state = PropGetWindowState(window); /* if it's startup and the window is unmapped, don't manage it */ if (scr->flags.startup && wm_state < 0 && wattribs.map_state == IsUnmapped) { XUngrabServer(dpy); return NULL; } wwin = wWindowCreate(); title = wNETWMGetWindowName(window); if (title) wwin->flags.net_has_title = 1; else if (!wFetchName(dpy, window, &title)) title = NULL; XSaveContext(dpy, window, w_global.context.client_win, (XPointer) & wwin->client_descriptor); #ifdef USE_XSHAPE if (w_global.xext.shape.supported) { int junk; unsigned int ujunk; int b_shaped; XShapeSelectInput(dpy, window, ShapeNotifyMask); XShapeQueryExtents(dpy, window, &b_shaped, &junk, &junk, &ujunk, &ujunk, &junk, &junk, &junk, &ujunk, &ujunk); wwin->flags.shaped = b_shaped; } #endif /* Get hints and other information in properties */ PropGetWMClass(window, &wwin->wm_class, &wwin->wm_instance); /* setup descriptor */ wwin->client_win = window; wwin->screen_ptr = scr; wwin->old_border_width = wattribs.border_width; wwin->event_mask = CLIENT_EVENTS; attribs.event_mask = CLIENT_EVENTS; attribs.do_not_propagate_mask = ButtonPressMask | ButtonReleaseMask; attribs.save_under = False; XChangeWindowAttributes(dpy, window, CWEventMask | CWDontPropagate | CWSaveUnder, &attribs); XSetWindowBorderWidth(dpy, window, 0); /* get hints from GNUstep app */ if (wwin->wm_class != NULL && strcmp(wwin->wm_class, "GNUstep") == 0) wwin->flags.is_gnustep = 1; if (!PropGetGNUstepWMAttr(window, &wwin->wm_gnustep_attr)) wwin->wm_gnustep_attr = NULL; if (wwin->wm_class != NULL && strcmp(wwin->wm_class, "DockApp") == 0) { wwin->flags.is_dockapp = 1; withdraw = True; } wwin->client_leader = PropGetClientLeader(window); if (wwin->client_leader != None) wwin->main_window = wwin->client_leader; wwin->wm_hints = XGetWMHints(dpy, window); if (wwin->wm_hints) { if (wwin->wm_hints->flags & StateHint) { if (wwin->wm_hints->initial_state == IconicState) { wwin->flags.miniaturized = 1; } else if (wwin->wm_hints->initial_state == WithdrawnState) { wwin->flags.is_dockapp = 1; withdraw = True; } } if (wwin->wm_hints->flags & WindowGroupHint) { wwin->group_id = wwin->wm_hints->window_group; /* window_group has priority over CLIENT_LEADER */ wwin->main_window = wwin->group_id; } else { wwin->group_id = None; } if (wwin->wm_hints->flags & UrgencyHint) { wwin->flags.urgent = 1; wAppBounceWhileUrgent(wApplicationOf(wwin->main_window)); } } else { wwin->group_id = None; } PropGetProtocols(window, &wwin->protocols); if (!XGetTransientForHint(dpy, window, &wwin->transient_for)) { wwin->transient_for = None; } else { if (wwin->transient_for == None || wwin->transient_for == window) { wwin->transient_for = scr->root_win; } else { transientOwner = wWindowFor(wwin->transient_for); if (transientOwner && transientOwner->main_window != None) wwin->main_window = transientOwner->main_window; } } /* guess the focus mode */ wwin->focus_mode = getFocusMode(wwin); /* get geometry stuff */ wClientGetNormalHints(wwin, &wattribs, True, &x, &y, &width, &height); /* get colormap windows */ GetColormapWindows(wwin); /* * Setup the decoration/window attributes and * geometry */ wWindowSetupInitialAttributes(wwin, &window_level, &workspace); /* Make broken apps behave as a nice app. */ if (WFLAGP(wwin, emulate_appicon)) wwin->main_window = wwin->client_win; fixLeaderProperties(wwin); wwin->orig_main_window = wwin->main_window; if (wwin->flags.is_gnustep) wwin->client_flags.shared_appicon = 0; if (wwin->main_window) { XTextProperty text_prop; if (XGetTextProperty(dpy, wwin->main_window, &text_prop, w_global.atom.wmaker.menu)) wwin->client_flags.shared_appicon = 0; } if (wwin->flags.is_dockapp) wwin->client_flags.shared_appicon = 0; if (wwin->main_window) { WApplication *app = wApplicationOf(wwin->main_window); if (app && app->app_icon) wwin->client_flags.shared_appicon = 0; } if (!withdraw && wwin->main_window && WFLAGP(wwin, shared_appicon)) { char *buffer, *instance, *class; WFakeGroupLeader *fPtr; int index; #define ADEQUATE(x) ((x)!=None && (x)!=wwin->client_win && (x)!=fPtr->leader) /* // only enter here if PropGetWMClass() succeeds */ PropGetWMClass(wwin->main_window, &class, &instance); buffer = StrConcatDot(instance, class); index = WMFindInArray(scr->fakeGroupLeaders, matchIdentifier, (void *)buffer); if (index != WANotFound) { fPtr = WMGetFromArray(scr->fakeGroupLeaders, index); if (fPtr->retainCount == 0) fPtr->leader = createFakeWindowGroupLeader(scr, wwin->main_window, instance, class); fPtr->retainCount++; if (fPtr->origLeader == None) { if (ADEQUATE(wwin->main_window)) { fPtr->retainCount++; fPtr->origLeader = wwin->main_window; } } wwin->fake_group = fPtr; wwin->main_window = fPtr->leader; wfree(buffer); } else { fPtr = (WFakeGroupLeader *) wmalloc(sizeof(WFakeGroupLeader)); fPtr->identifier = buffer; fPtr->leader = createFakeWindowGroupLeader(scr, wwin->main_window, instance, class); fPtr->origLeader = None; fPtr->retainCount = 1; WMAddToArray(scr->fakeGroupLeaders, fPtr); if (ADEQUATE(wwin->main_window)) { fPtr->retainCount++; fPtr->origLeader = wwin->main_window; } wwin->fake_group = fPtr; wwin->main_window = fPtr->leader; } if (instance) free(instance); if (class) free(class); #undef ADEQUATE } /* * Setup the initial state of the window */ if (WFLAGP(wwin, start_miniaturized) && !WFLAGP(wwin, no_miniaturizable)) wwin->flags.miniaturized = 1; if (WFLAGP(wwin, start_maximized) && IS_RESIZABLE(wwin)) wwin->flags.maximized = MAX_VERTICAL | MAX_HORIZONTAL; wNETWMCheckInitialClientState(wwin); /* apply previous state if it exists and we're in startup */ if (scr->flags.startup && wm_state >= 0) { if (wm_state == IconicState) wwin->flags.miniaturized = 1; else if (wm_state == WithdrawnState) withdraw = True; } /* if there is a saved state (from file), restore it */ win_state = NULL; if (wwin->main_window != None) win_state = (WWindowState *) wWindowGetSavedState(wwin->main_window); else win_state = (WWindowState *) wWindowGetSavedState(window); if (win_state && !withdraw) { if (win_state->state->hidden > 0) wwin->flags.hidden = win_state->state->hidden; if (win_state->state->shaded > 0 && !WFLAGP(wwin, no_shadeable)) wwin->flags.shaded = win_state->state->shaded; if (win_state->state->miniaturized > 0 && !WFLAGP(wwin, no_miniaturizable)) wwin->flags.miniaturized = win_state->state->miniaturized; if (!IS_OMNIPRESENT(wwin)) { int w = wDefaultGetStartWorkspace(scr, wwin->wm_instance, wwin->wm_class); if (w < 0 || w >= scr->workspace_count) { workspace = win_state->state->workspace; if (workspace >= scr->workspace_count) workspace = scr->current_workspace; } else { workspace = w; } } else { workspace = scr->current_workspace; } } /* if we're restarting, restore saved state (from hints). * This will overwrite previous */ { WSavedState *wstate; if (getSavedState(window, &wstate)) { wwin->flags.shaded = wstate->shaded; wwin->flags.hidden = wstate->hidden; wwin->flags.miniaturized = wstate->miniaturized; wwin->flags.maximized = wstate->maximized; if (wwin->flags.maximized) { wwin->old_geometry.x = wstate->x; wwin->old_geometry.y = wstate->y; wwin->old_geometry.width = wstate->w; wwin->old_geometry.height = wstate->h; } workspace = wstate->workspace; } else { wstate = NULL; } /* restore window shortcut */ if (wstate != NULL || win_state != NULL) { unsigned mask = 0; if (win_state != NULL) mask = win_state->state->window_shortcuts; if (wstate != NULL && mask == 0) mask = wstate->window_shortcuts; if (mask > 0) { int i; for (i = 0; i < MAX_WINDOW_SHORTCUTS; i++) { if (mask & (1 << i)) { if (!scr->shortcutWindows[i]) scr->shortcutWindows[i] = WMCreateArray(4); WMAddToArray(scr->shortcutWindows[i], wwin); } } } } if (wstate != NULL) wfree(wstate); } /* don't let transients start miniaturized if their owners are not */ if (transientOwner && !transientOwner->flags.miniaturized && wwin->flags.miniaturized && !withdraw) { wwin->flags.miniaturized = 0; if (wwin->wm_hints) wwin->wm_hints->initial_state = NormalState; } /* set workspace on which the window starts */ if (workspace >= 0) { if (workspace > scr->workspace_count - 1) workspace = workspace % scr->workspace_count; } else { int w; w = wDefaultGetStartWorkspace(scr, wwin->wm_instance, wwin->wm_class); if (w >= 0 && w < scr->workspace_count && !(IS_OMNIPRESENT(wwin))) { workspace = w; } else { if (wPreferences.open_transients_with_parent && transientOwner) workspace = transientOwner->frame->workspace; else workspace = scr->current_workspace; } } /* setup window geometry */ if (win_state && win_state->state->w > 0) { width = win_state->state->w; height = win_state->state->h; } wWindowConstrainSize(wwin, &width, &height); /* do not ask for window placement if the window is * transient, during startup, or if the window wants * to start iconic. If geometry was saved, restore it. */ { Bool dontBring = False; if (win_state && win_state->state->w > 0) { x = win_state->state->x; y = win_state->state->y; } else if ((wwin->transient_for == None || wPreferences.window_placement != WPM_MANUAL) && !scr->flags.startup && !wwin->flags.miniaturized && !wwin->flags.maximized && !(wwin->normal_hints->flags & (USPosition | PPosition))) { if (transientOwner && transientOwner->flags.mapped) { int offs = WMAX(20, 2 * transientOwner->frame->top_width); WMRect rect; int head; x = transientOwner->frame_x + - abs((transientOwner->frame->core->width - width) / 2) + offs; + abs(((int)transientOwner->frame->core->width - (int)width) / 2) + offs; y = transientOwner->frame_y + - abs((transientOwner->frame->core->height - height) / 3) + offs; + abs(((int)transientOwner->frame->core->height - (int)height) / 3) + offs; /* limit transient windows to be inside their parent's head */ rect.pos.x = transientOwner->frame_x; rect.pos.y = transientOwner->frame_y; rect.size.width = transientOwner->frame->core->width; rect.size.height = transientOwner->frame->core->height; head = wGetHeadForRect(scr, rect); rect = wGetRectForHead(scr, head); if (x < rect.pos.x) x = rect.pos.x; else if (x + width > rect.pos.x + rect.size.width) x = rect.pos.x + rect.size.width - width; if (y < rect.pos.y) y = rect.pos.y; else if (y + height > rect.pos.y + rect.size.height) y = rect.pos.y + rect.size.height - height; } else { PlaceWindow(wwin, &x, &y, width, height); } if (wPreferences.window_placement == WPM_MANUAL) dontBring = True; } else if (scr->xine_info.count && (wwin->normal_hints->flags & PPosition)) { int head, flags; WMRect rect; int reposition = 0; /* Make spash screens come out in the center of a head * trouble is that most splashies never get here * they are managed trough atoms but god knows where. * Dan, do you know ? -peter * * Most of them are not managed, they have set * OverrideRedirect, which means we can't do anything about * them. -alfredo */ { /* xinerama checks for: across head and dead space */ rect.pos.x = x; rect.pos.y = y; rect.size.width = width; rect.size.height = height; head = wGetRectPlacementInfo(scr, rect, &flags); if (flags & XFLAG_DEAD) reposition = 1; if (flags & XFLAG_MULTIPLE) reposition = 2; } switch (reposition) { case 1: head = wGetHeadForPointerLocation(scr); rect = wGetRectForHead(scr, head); x = rect.pos.x + (x * rect.size.width) / scr->scr_width; y = rect.pos.y + (y * rect.size.height) / scr->scr_height; break; case 2: rect = wGetRectForHead(scr, head); if (x < rect.pos.x) x = rect.pos.x; else if (x + width > rect.pos.x + rect.size.width) x = rect.pos.x + rect.size.width - width; if (y < rect.pos.y) y = rect.pos.y; else if (y + height > rect.pos.y + rect.size.height) y = rect.pos.y + rect.size.height - height; break; default: break; } } if (WFLAGP(wwin, dont_move_off) && dontBring) wScreenBringInside(scr, &x, &y, width, height); } wNETWMPositionSplash(wwin, &x, &y, width, height); if (wwin->flags.urgent) { if (!IS_OMNIPRESENT(wwin)) wwin->flags.omnipresent ^= 1; } /* Create frame, borders and do reparenting */ foo = WFF_LEFT_BUTTON | WFF_RIGHT_BUTTON; #ifdef XKB_BUTTON_HINT if (wPreferences.modelock) foo |= WFF_LANGUAGE_BUTTON; #endif if (HAS_TITLEBAR(wwin)) foo |= WFF_TITLEBAR; if (HAS_RESIZEBAR(wwin)) foo |= WFF_RESIZEBAR; if (HAS_BORDER(wwin)) foo |= WFF_BORDER; wwin->frame = wFrameWindowCreate(scr, window_level, x, y, width, height, &wPreferences.window_title_clearance, &wPreferences.window_title_min_height, &wPreferences.window_title_max_height, foo, scr->window_title_texture, scr->resizebar_texture, scr->window_title_color, &scr->title_font, wattribs.depth, wattribs.visual, wattribs.colormap); wwin->frame->flags.is_client_window_frame = 1; wwin->frame->flags.justification = wPreferences.title_justification; wNETWMCheckInitialFrameState(wwin); /* setup button images */ wWindowUpdateButtonImages(wwin); /* hide unused buttons */ foo = 0; if (WFLAGP(wwin, no_close_button)) foo |= WFF_RIGHT_BUTTON; if (WFLAGP(wwin, no_miniaturize_button)) foo |= WFF_LEFT_BUTTON; #ifdef XKB_BUTTON_HINT if (WFLAGP(wwin, no_language_button) || WFLAGP(wwin, no_focusable)) foo |= WFF_LANGUAGE_BUTTON; #endif if (foo != 0) wFrameWindowHideButton(wwin->frame, foo); wwin->frame->child = wwin; wwin->frame->workspace = workspace; wwin->frame->on_click_left = windowIconifyClick; #ifdef XKB_BUTTON_HINT if (wPreferences.modelock) wwin->frame->on_click_language = windowLanguageClick; #endif wwin->frame->on_click_right = windowCloseClick; wwin->frame->on_dblclick_right = windowCloseDblClick; wwin->frame->on_mousedown_titlebar = titlebarMouseDown; wwin->frame->on_dblclick_titlebar = titlebarDblClick; wwin->frame->on_mousedown_resizebar = resizebarMouseDown; XSelectInput(dpy, wwin->client_win, wwin->event_mask & ~StructureNotifyMask); XReparentWindow(dpy, wwin->client_win, wwin->frame->core->window, 0, wwin->frame->top_width); XSelectInput(dpy, wwin->client_win, wwin->event_mask); { int gx, gy; wClientGetGravityOffsets(wwin, &gx, &gy); /* if gravity is to the south, account for the border sizes */ if (gy > 0) y -= wwin->frame->top_width + wwin->frame->bottom_width; } /* * wWindowConfigure() will init the client window's size * (wwin->client.{width,height}) and all other geometry * related variables (frame_x,frame_y) */ wWindowConfigure(wwin, x, y, width, height); /* to make sure the window receives it's new position after reparenting */ wWindowSynthConfigureNotify(wwin); /* Setup descriptors and save window to internal lists */ if (wwin->main_window != None) { WApplication *app; WWindow *leader; /* Leader windows do not necessary set themselves as leaders. * If this is the case, point the leader of this window to * itself */ leader = wWindowFor(wwin->main_window); if (leader && leader->main_window == None) leader->main_window = leader->client_win; app = wApplicationCreate(wwin); if (app) { app->last_workspace = workspace; /* Do application specific stuff, like setting application * wide attributes. */ if (wwin->flags.hidden) { /* if the window was set to hidden because it was hidden * in a previous incarnation and that state was restored */ app->flags.hidden = 1; } else if (app->flags.hidden) { if (WFLAGP(app->main_window_desc, start_hidden)) { wwin->flags.hidden = 1; } else { wUnhideApplication(app, False, False); raise = True; } } wAppBounce(app); } } /* setup the frame descriptor */ wwin->frame->core->descriptor.handle_mousedown = frameMouseDown; wwin->frame->core->descriptor.parent = wwin; wwin->frame->core->descriptor.parent_type = WCLASS_WINDOW; /* don't let windows go away if we die */ XAddToSaveSet(dpy, window); XLowerWindow(dpy, window); /* if window is in this workspace and should be mapped, then map it */ if (!wwin->flags.miniaturized && (workspace == scr->current_workspace || IS_OMNIPRESENT(wwin)) && !wwin->flags.hidden && !withdraw) { /* The following "if" is to avoid crashing of clients that expect * WM_STATE set before they get mapped. Else WM_STATE is set later, * after the return from this function. */ if (wwin->wm_hints && (wwin->wm_hints->flags & StateHint)) wClientSetState(wwin, wwin->wm_hints->initial_state, None); else wClientSetState(wwin, NormalState, None); if (wPreferences.superfluous && !wPreferences.no_animations && !scr->flags.startup && (wwin->transient_for == None || wwin->transient_for == scr->root_win) && /* * The brain damaged idiotic non-click to focus modes will * have trouble with this because: * * 1. window is created and mapped by the client * 2. window is mapped by wmaker in small size * 3. window is animated to grow to normal size * 4. this function returns to normal event loop * 5. eventually, the EnterNotify event that would trigger * the window focusing (if the mouse is over that window) * will be processed by wmaker. * But since this event will be rather delayed * (step 3 has a large delay) the time when the event occurred * and when it is processed, the client that owns that window * will reject the XSetInputFocus() for it. */ (wPreferences.focus_mode == WKF_CLICK || wPreferences.auto_focus)) DoWindowBirth(wwin); wWindowMap(wwin); } /* setup stacking descriptor */ if (transientOwner) wwin->frame->core->stacking->child_of = transientOwner->frame->core; else wwin->frame->core->stacking->child_of = NULL; if (!scr->focused_window) { /* first window on the list */ wwin->next = NULL; wwin->prev = NULL; scr->focused_window = wwin; } else { WWindow *tmp; /* add window at beginning of focus window list */ tmp = scr->focused_window; while (tmp->prev) tmp = tmp->prev; tmp->prev = wwin; wwin->next = tmp; wwin->prev = NULL; } /* raise is set to true if we un-hid the app when this window was born. * we raise, else old windows of this app will be above this new one. */ if (raise) wRaiseFrame(wwin->frame->core); /* Update name must come after WApplication stuff is done */ wWindowUpdateName(wwin, title); if (title) XFree(title); XUngrabServer(dpy); /* Final preparations before window is ready to go */ wFrameWindowChangeState(wwin->frame, WS_UNFOCUSED); if (!wwin->flags.miniaturized && workspace == scr->current_workspace && !wwin->flags.hidden) { if (((transientOwner && transientOwner->flags.focused) || wPreferences.auto_focus) && !WFLAGP(wwin, no_focusable)) { /* only auto_focus if on same screen as mouse * (and same head for xinerama mode) * TODO: make it an option */ /*TODO add checking the head of the window, is it available? */ short same_screen = 0, same_head = 1; int foo; unsigned int bar; Window dummy; if (XQueryPointer(dpy, scr->root_win, &dummy, &dummy, &foo, &foo, &foo, &foo, &bar) != False) same_screen = 1; if (same_screen == 1 && same_head == 1) wSetFocusTo(scr, wwin); } } wWindowResetMouseGrabs(wwin); if (!WFLAGP(wwin, no_bind_keys)) wWindowSetKeyGrabs(wwin); WMPostNotificationName(WMNManaged, wwin, NULL); wColormapInstallForWindow(scr, scr->cmap_window); /* Setup Notification Observers */ WMAddNotificationObserver(appearanceObserver, wwin, WNWindowAppearanceSettingsChanged, wwin); /* Cleanup temporary stuff */ if (win_state) wWindowDeleteSavedState(win_state); /* If the window must be withdrawed, then do it now. * Must do some optimization, 'though */ if (withdraw) { wwin->flags.mapped = 0; wClientSetState(wwin, WithdrawnState, None); wUnmanageWindow(wwin, True, False); wwin = NULL; } return wwin; } WWindow *wManageInternalWindow(WScreen *scr, Window window, Window owner, const char *title, int x, int y, int width, int height) { WWindow *wwin; int foo; wwin = wWindowCreate(); WMAddNotificationObserver(appearanceObserver, wwin, WNWindowAppearanceSettingsChanged, wwin); wwin->flags.internal_window = 1; wwin->client_flags.omnipresent = 1; wwin->client_flags.no_shadeable = 1; wwin->client_flags.no_resizable = 1; wwin->client_flags.no_miniaturizable = 1; wwin->focus_mode = WFM_PASSIVE; wwin->client_win = window; wwin->screen_ptr = scr; wwin->transient_for = owner; wwin->client.x = x; wwin->client.y = y; wwin->client.width = width; wwin->client.height = height; wwin->frame_x = wwin->client.x; wwin->frame_y = wwin->client.y; foo = WFF_RIGHT_BUTTON | WFF_BORDER; foo |= WFF_TITLEBAR; #ifdef XKB_BUTTON_HINT foo |= WFF_LANGUAGE_BUTTON; #endif wwin->frame = wFrameWindowCreate(scr, WMFloatingLevel, wwin->frame_x, wwin->frame_y, width, height, &wPreferences.window_title_clearance, &wPreferences.window_title_min_height, &wPreferences.window_title_max_height, foo, scr->window_title_texture, scr->resizebar_texture, scr->window_title_color, &scr->title_font, scr->w_depth, scr->w_visual, scr->w_colormap); XSaveContext(dpy, window, w_global.context.client_win, (XPointer) & wwin->client_descriptor); wwin->frame->flags.is_client_window_frame = 1; wwin->frame->flags.justification = wPreferences.title_justification; wFrameWindowChangeTitle(wwin->frame, title); /* setup button images */ wWindowUpdateButtonImages(wwin); /* hide buttons */ wFrameWindowHideButton(wwin->frame, WFF_RIGHT_BUTTON); wwin->frame->child = wwin; wwin->frame->workspace = wwin->screen_ptr->current_workspace; #ifdef XKB_BUTTON_HINT if (wPreferences.modelock) wwin->frame->on_click_language = windowLanguageClick; #endif wwin->frame->on_click_right = windowCloseClick; wwin->frame->on_mousedown_titlebar = titlebarMouseDown; wwin->frame->on_dblclick_titlebar = titlebarDblClick; wwin->frame->on_mousedown_resizebar = resizebarMouseDown; wwin->client.y += wwin->frame->top_width; XReparentWindow(dpy, wwin->client_win, wwin->frame->core->window, 0, wwin->frame->top_width); wWindowConfigure(wwin, wwin->frame_x, wwin->frame_y, wwin->client.width, wwin->client.height); /* setup the frame descriptor */ wwin->frame->core->descriptor.handle_mousedown = frameMouseDown; wwin->frame->core->descriptor.parent = wwin; wwin->frame->core->descriptor.parent_type = WCLASS_WINDOW; XLowerWindow(dpy, window); XMapSubwindows(dpy, wwin->frame->core->window); /* setup stacking descriptor */ if (wwin->transient_for != None && wwin->transient_for != scr->root_win) { WWindow *tmp; tmp = wWindowFor(wwin->transient_for); if (tmp) wwin->frame->core->stacking->child_of = tmp->frame->core; } else { wwin->frame->core->stacking->child_of = NULL; } if (!scr->focused_window) { /* first window on the list */ wwin->next = NULL; wwin->prev = NULL; scr->focused_window = wwin; } else { WWindow *tmp; /* add window at beginning of focus window list */ tmp = scr->focused_window; while (tmp->prev) tmp = tmp->prev; tmp->prev = wwin; wwin->next = tmp; wwin->prev = NULL; } if (wwin->flags.is_gnustep == 0) wFrameWindowChangeState(wwin->frame, WS_UNFOCUSED); /* if (wPreferences.auto_focus) */ wSetFocusTo(scr, wwin); wWindowResetMouseGrabs(wwin); wWindowSetKeyGrabs(wwin); return wwin; } /* *---------------------------------------------------------------------- * wUnmanageWindow-- * Removes the frame window from a window and destroys all data * related to it. The window will be reparented back to the root window * if restore is True. * * Side effects: * Everything related to the window is destroyed and the window * is removed from the window lists. Focus is set to the previous on the * window list. *---------------------------------------------------------------------- */ void wUnmanageWindow(WWindow *wwin, Bool restore, Bool destroyed) { WCoreWindow *frame = wwin->frame->core; WWindow *owner = NULL; WWindow *newFocusedWindow = NULL; int wasFocused; WScreen *scr = wwin->screen_ptr; /* First close attribute editor window if open */ if (wwin->flags.inspector_open) wCloseInspectorForWindow(wwin); /* Close window menu if it's open for this window */ if (wwin->flags.menu_open_for_me) CloseWindowMenu(scr); /* Don't restore focus to this window after a window exits * fullscreen mode */ if (scr->bfs_focused_window == wwin) scr->bfs_focused_window = NULL; if (!destroyed) { if (!wwin->flags.internal_window) XRemoveFromSaveSet(dpy, wwin->client_win); /* If this is a leader window, we still need to listen for diff --git a/src/xinerama.c b/src/xinerama.c index 483046c..4c0beb2 100644 --- a/src/xinerama.c +++ b/src/xinerama.c @@ -1,412 +1,412 @@ /* * Window Maker window manager * * Copyright (c) 1997-2003 Alfredo K. Kojima * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <stdlib.h> #include "wconfig.h" #include "xinerama.h" #include "screen.h" #include "window.h" #include "framewin.h" #include "placement.h" #include "dock.h" #ifdef USE_XINERAMA # ifdef SOLARIS_XINERAMA /* sucks */ # include <X11/extensions/xinerama.h> # else # include <X11/extensions/Xinerama.h> # endif #endif void wInitXinerama(WScreen * scr) { scr->xine_info.primary_head = 0; scr->xine_info.screens = NULL; scr->xine_info.count = 0; #ifdef USE_XINERAMA # ifdef SOLARIS_XINERAMA if (XineramaGetState(dpy, scr->screen)) { WXineramaInfo *info = &scr->xine_info; XRectangle head[MAXFRAMEBUFFERS]; unsigned char hints[MAXFRAMEBUFFERS]; int i; if (XineramaGetInfo(dpy, scr->screen, head, hints, &info->count)) { info->screens = wmalloc(sizeof(WMRect) * (info->count + 1)); for (i = 0; i < info->count; i++) { info->screens[i].pos.x = head[i].x; info->screens[i].pos.y = head[i].y; info->screens[i].size.width = head[i].width; info->screens[i].size.height = head[i].height; } } } # else /* !SOLARIS_XINERAMA */ if (XineramaIsActive(dpy)) { XineramaScreenInfo *xine_screens; WXineramaInfo *info = &scr->xine_info; int i; xine_screens = XineramaQueryScreens(dpy, &info->count); info->screens = wmalloc(sizeof(WMRect) * (info->count + 1)); for (i = 0; i < info->count; i++) { info->screens[i].pos.x = xine_screens[i].x_org; info->screens[i].pos.y = xine_screens[i].y_org; info->screens[i].size.width = xine_screens[i].width; info->screens[i].size.height = xine_screens[i].height; } XFree(xine_screens); } # endif /* !SOLARIS_XINERAMA */ #endif /* USE_XINERAMA */ } int wGetRectPlacementInfo(WScreen * scr, WMRect rect, int *flags) { int best; unsigned long area, totalArea; int i; int rx = rect.pos.x; int ry = rect.pos.y; int rw = rect.size.width; int rh = rect.size.height; wassertrv(flags != NULL, 0); best = -1; area = 0; totalArea = 0; *flags = XFLAG_NONE; if (scr->xine_info.count <= 1) { unsigned long a; a = calcIntersectionArea(rx, ry, rw, rh, 0, 0, scr->scr_width, scr->scr_height); if (a == 0) { *flags |= XFLAG_DEAD; } else if (a != rw * rh) { *flags |= XFLAG_PARTIAL; } return scr->xine_info.primary_head; } for (i = 0; i < wXineramaHeads(scr); i++) { unsigned long a; a = calcIntersectionArea(rx, ry, rw, rh, scr->xine_info.screens[i].pos.x, scr->xine_info.screens[i].pos.y, scr->xine_info.screens[i].size.width, scr->xine_info.screens[i].size.height); totalArea += a; if (a > area) { if (best != -1) *flags |= XFLAG_MULTIPLE; area = a; best = i; } } if (best == -1) { *flags |= XFLAG_DEAD; best = wGetHeadForPointerLocation(scr); } else if (totalArea != rw * rh) *flags |= XFLAG_PARTIAL; return best; } /* get the head that covers most of the rectangle */ int wGetHeadForRect(WScreen * scr, WMRect rect) { int best; unsigned long area; int i; int rx = rect.pos.x; int ry = rect.pos.y; int rw = rect.size.width; int rh = rect.size.height; if (!scr->xine_info.count) return scr->xine_info.primary_head; best = -1; area = 0; for (i = 0; i < wXineramaHeads(scr); i++) { unsigned long a; a = calcIntersectionArea(rx, ry, rw, rh, scr->xine_info.screens[i].pos.x, scr->xine_info.screens[i].pos.y, scr->xine_info.screens[i].size.width, scr->xine_info.screens[i].size.height); if (a > area) { area = a; best = i; } } /* * in case rect is in dead space, return valid head */ if (best == -1) best = wGetHeadForPointerLocation(scr); return best; } Bool wWindowTouchesHead(WWindow * wwin, int head) { WScreen *scr; WMRect rect; int a; if (!wwin || !wwin->frame) return False; scr = wwin->screen_ptr; rect = wGetRectForHead(scr, head); a = calcIntersectionArea(wwin->frame_x, wwin->frame_y, wwin->frame->core->width, wwin->frame->core->height, rect.pos.x, rect.pos.y, rect.size.width, rect.size.height); return (a != 0); } Bool wAppIconTouchesHead(WAppIcon * aicon, int head) { WScreen *scr; WMRect rect; int a; if (!aicon || !aicon->icon) return False; scr = aicon->icon->core->screen_ptr; rect = wGetRectForHead(scr, head); a = calcIntersectionArea(aicon->x_pos, aicon->y_pos, aicon->icon->core->width, aicon->icon->core->height, rect.pos.x, rect.pos.y, rect.size.width, rect.size.height); return (a != 0); } int wGetHeadForWindow(WWindow * wwin) { WMRect rect; if (wwin == NULL || wwin->frame == NULL) return 0; rect.pos.x = wwin->frame_x; rect.pos.y = wwin->frame_y; rect.size.width = wwin->frame->core->width; rect.size.height = wwin->frame->core->height; return wGetHeadForRect(wwin->screen_ptr, rect); } /* Find head on left, right, up or down direction relative to current head. If there is no screen available on pointed direction, -1 will be returned.*/ int wGetHeadRelativeToCurrentHead(WScreen *scr, int current_head, int direction) { short int found = 0; int i; int distance = 0; int smallest_distance = 0; int nearest_head = scr->xine_info.primary_head; WMRect crect = wGetRectForHead(scr, current_head); for (i = 0; i < scr->xine_info.count; i++) { if (i == current_head) continue; WMRect *rect = &scr->xine_info.screens[i]; /* calculate distance from the next screen to current one */ switch (direction) { case DIRECTION_LEFT: if (rect->pos.x < crect.pos.x) { found = 1; - distance = abs((rect->pos.x + rect->size.width) + distance = abs((rect->pos.x + (int)rect->size.width) - crect.pos.x) + abs(rect->pos.y + crect.pos.y); } break; case DIRECTION_RIGHT: if (rect->pos.x > crect.pos.x) { found = 1; - distance = abs((crect.pos.x + crect.size.width) + distance = abs((crect.pos.x + (int)crect.size.width) - rect->pos.x) + abs(rect->pos.y + crect.pos.y); } break; case DIRECTION_UP: if (rect->pos.y < crect.pos.y) { found = 1; - distance = abs((rect->pos.y + rect->size.height) + distance = abs((rect->pos.y + (int)rect->size.height) - crect.pos.y) + abs(rect->pos.x + crect.pos.x); } break; case DIRECTION_DOWN: if (rect->pos.y > crect.pos.y) { found = 1; - distance = abs((crect.pos.y + crect.size.height) + distance = abs((crect.pos.y + (int)crect.size.height) - rect->pos.y) + abs(rect->pos.x + crect.pos.x); } break; } if (found && distance == 0) return i; if (smallest_distance == 0) smallest_distance = distance; if (abs(distance) <= smallest_distance) { smallest_distance = distance; nearest_head = i; } } if (found && smallest_distance != 0 && nearest_head != current_head) return nearest_head; return -1; } int wGetHeadForPoint(WScreen * scr, WMPoint point) { int i; for (i = 0; i < scr->xine_info.count; i++) { WMRect *rect = &scr->xine_info.screens[i]; if ((unsigned)(point.x - rect->pos.x) < rect->size.width && (unsigned)(point.y - rect->pos.y) < rect->size.height) return i; } return scr->xine_info.primary_head; } int wGetHeadForPointerLocation(WScreen * scr) { WMPoint point; Window bla; int ble; unsigned int blo; if (!scr->xine_info.count) return scr->xine_info.primary_head; if (!XQueryPointer(dpy, scr->root_win, &bla, &bla, &point.x, &point.y, &ble, &ble, &blo)) return scr->xine_info.primary_head; return wGetHeadForPoint(scr, point); } /* get the dimensions of the head */ WMRect wGetRectForHead(WScreen * scr, int head) { WMRect rect; if (head < scr->xine_info.count) { rect.pos.x = scr->xine_info.screens[head].pos.x; rect.pos.y = scr->xine_info.screens[head].pos.y; rect.size.width = scr->xine_info.screens[head].size.width; rect.size.height = scr->xine_info.screens[head].size.height; } else { rect.pos.x = 0; rect.pos.y = 0; rect.size.width = scr->scr_width; rect.size.height = scr->scr_height; } return rect; } WArea wGetUsableAreaForHead(WScreen * scr, int head, WArea * totalAreaPtr, Bool noicons) { WArea totalArea, usableArea; WMRect rect = wGetRectForHead(scr, head); totalArea.x1 = rect.pos.x; totalArea.y1 = rect.pos.y; totalArea.x2 = totalArea.x1 + rect.size.width; totalArea.y2 = totalArea.y1 + rect.size.height; if (totalAreaPtr != NULL) *totalAreaPtr = totalArea; if (head < wXineramaHeads(scr)) { usableArea = noicons ? scr->totalUsableArea[head] : scr->usableArea[head]; } else usableArea = totalArea; if (noicons) { /* check if user wants dock covered */ if (scr->dock && wPreferences.no_window_over_dock && wAppIconTouchesHead(scr->dock->icon_array[0], head)) { int offset = wPreferences.icon_size + DOCK_EXTRA_SPACE; if (scr->dock->on_right_side) usableArea.x2 -= offset; else usableArea.x1 += offset; } /* check if icons are on the same side as dock, and adjust if not done already */ if (scr->dock && wPreferences.no_window_over_icons && !wPreferences.no_window_over_dock && (wPreferences.icon_yard & IY_VERT)) { int offset = wPreferences.icon_size + DOCK_EXTRA_SPACE; if (scr->dock->on_right_side && (wPreferences.icon_yard & IY_RIGHT)) usableArea.x2 -= offset; /* can't use IY_LEFT in if, it's 0 ... */ if (!scr->dock->on_right_side && !(wPreferences.icon_yard & IY_RIGHT)) usableArea.x1 += offset; } } return usableArea; } WMPoint wGetPointToCenterRectInHead(WScreen * scr, int head, int width, int height) { WMPoint p; WMRect rect = wGetRectForHead(scr, head); p.x = rect.pos.x + (rect.size.width - width) / 2; p.y = rect.pos.y + (rect.size.height - height) / 2; return p; }
roblillack/wmaker
dfa92906c0bd8cba4fa5d1ed4e31edc6cdc3ca00
wrlib: Compile with either ImageMagick 6 and 7
diff --git a/m4/wm_imgfmt_check.m4 b/m4/wm_imgfmt_check.m4 index b5adf6f..2236e6c 100644 --- a/m4/wm_imgfmt_check.m4 +++ b/m4/wm_imgfmt_check.m4 @@ -1,332 +1,336 @@ # wm_imgfmt_check.m4 - Macros to check for image file format support libraries # # Copyright (c) 2013 Christophe CURIS # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # WM_IMGFMT_CHECK_GIF # ------------------- # # Check for GIF file support through 'libgif', 'libungif' or 'giflib v5' # The check depends on variable 'enable_gif' being either: # yes - detect, fail if not found # no - do not detect, disable support # auto - detect, disable if not found # # When found, append appropriate stuff in GFXLIBS, and append info to # the variable 'supported_gfx' # When not found, append info to variable 'unsupported' AC_DEFUN_ONCE([WM_IMGFMT_CHECK_GIF], [AC_REQUIRE([_WM_LIB_CHECK_FUNCTS]) AS_IF([test "x$enable_gif" = "xno"], [unsupported="$unsupported GIF"], [AC_CACHE_CHECK([for GIF support library], [wm_cv_imgfmt_gif], [wm_cv_imgfmt_gif=no wm_save_LIBS="$LIBS" dnl dnl We check first if one of the known libraries is available for wm_arg in "-lgif" "-lungif" ; do AS_IF([wm_fn_lib_try_link "DGifOpenFileName" "$XLFLAGS $XLIBS $wm_arg"], [wm_cv_imgfmt_gif="$wm_arg" ; break]) done LIBS="$wm_save_LIBS" AS_IF([test "x$enable_gif$wm_cv_imgfmt_gif" = "xyesno"], [AC_MSG_ERROR([explicit GIF support requested but no library found])]) AS_IF([test "x$wm_cv_imgfmt_gif" != "xno"], [dnl dnl A library was found, now check for the appropriate header wm_save_CFLAGS="$CFLAGS" AS_IF([wm_fn_lib_try_compile "gif_lib.h" "" "return 0" ""], [], [AC_MSG_ERROR([found $wm_cv_imgfmt_gif but could not find appropriate header - are you missing libgif-dev package?])]) AS_IF([wm_fn_lib_try_compile "gif_lib.h" 'const char *filename = "dummy";' "DGifOpenFileName(filename)" ""], [wm_cv_imgfmt_gif="$wm_cv_imgfmt_gif version:4"], [AC_COMPILE_IFELSE( [AC_LANG_PROGRAM( [@%:@include <gif_lib.h> const char *filename = "dummy";], [ int error_code; DGifOpenFileName(filename, &error_code);] )], [wm_cv_imgfmt_gif="$wm_cv_imgfmt_gif version:5"], [AC_MSG_ERROR([found $wm_cv_imgfmt_gif and header, but cannot compile - unsupported version?])])dnl ] ) CFLAGS="$wm_save_CFLAGS"]) ]) AS_IF([test "x$wm_cv_imgfmt_gif" = "xno"], [unsupported="$unsupported GIF" enable_gif="no"], [supported_gfx="$supported_gfx GIF" WM_APPEND_ONCE([`echo "$wm_cv_imgfmt_gif" | sed -e 's, *version:.*,,' `], [GFXLIBS]) AC_DEFINE_UNQUOTED([USE_GIF], [`echo "$wm_cv_imgfmt_gif" | sed -e 's,.*version:,,' `], [defined when valid GIF library with header was found])]) ]) AM_CONDITIONAL([USE_GIF], [test "x$enable_gif" != "xno"])dnl ]) dnl AC_DEFUN # WM_IMGFMT_CHECK_JPEG # -------------------- # # Check for JPEG file support through 'libjpeg' # The check depends on variable 'enable_jpeg' being either: # yes - detect, fail if not found # no - do not detect, disable support # auto - detect, disable if not found # # When found, append appropriate stuff in GFXLIBS, and append info to # the variable 'supported_gfx' # When not found, append info to variable 'unsupported' AC_DEFUN_ONCE([WM_IMGFMT_CHECK_JPEG], [WM_LIB_CHECK([JPEG], [-ljpeg], [jpeg_destroy_compress], [$XLFLAGS $XLIBS], [AC_COMPILE_IFELSE( [AC_LANG_PROGRAM( [@%:@include <stdlib.h> @%:@include <stdio.h> @%:@include <jpeglib.h>], [ struct jpeg_decompress_struct cinfo; jpeg_destroy_decompress(&cinfo);])], [], [AS_ECHO([failed]) AS_ECHO(["$as_me: error: found $CACHEVAR but cannot compile header"]) AS_ECHO(["$as_me: error: - does header 'jpeglib.h' exists? (is package 'jpeg-dev' missing?)"]) AS_ECHO(["$as_me: error: - version of header is not supported? (report to dev team)"]) AC_MSG_ERROR([JPEG library is not usable, cannot continue])]) ], [supported_gfx], [GFXLIBS])dnl ]) dnl AC_DEFUN # WM_IMGFMT_CHECK_PNG # ------------------- # # Check for PNG file support through 'libpng' # The check depends on variable 'enable_png' being either: # yes - detect, fail if not found # no - do not detect, disable support # auto - detect, disable if not found # # When found, append appropriate stuff in GFXLIBS, and append info to # the variable 'supported_gfx' # When not found, append info to variable 'unsupported' AC_DEFUN_ONCE([WM_IMGFMT_CHECK_PNG], [WM_LIB_CHECK([PNG], ["-lpng" "-lpng -lz" "-lpng -lz -lm"], [png_get_valid], [$XLFLAGS $XLIBS], [wm_save_CFLAGS="$CFLAGS" AS_IF([wm_fn_lib_try_compile "png.h" "" "return 0" ""], [], [AC_MSG_ERROR([found $CACHEVAR but could not find appropriate header - are you missing libpng-dev package?])]) AS_IF([wm_fn_lib_try_compile "png.h" "" "png_get_valid(NULL, NULL, PNG_INFO_tRNS)" ""], [], [AC_MSG_ERROR([found $CACHEVAR and header, but cannot compile - unsupported version?])]) CFLAGS="$wm_save_CFLAGS"], [supported_gfx], [GFXLIBS])dnl ]) dnl AC_DEFUN # WM_IMGFMT_CHECK_TIFF # -------------------- # # Check for TIFF file support through 'libtiff' # The check depends on variable 'enable_tiff' being either: # yes - detect, fail if not found # no - do not detect, disable support # auto - detect, disable if not found # # When found, append appropriate stuff in GFXLIBS, and append info to # the variable 'supported_gfx' # When not found, append info to variable 'unsupported' AC_DEFUN_ONCE([WM_IMGFMT_CHECK_TIFF], [WM_LIB_CHECK([TIFF], ["-ltiff" \ dnl TIFF can have a dependancy over zlib "-ltiff -lz" "-ltiff -lz -lm" \ dnl It may also have a dependancy to jpeg_lib "-ltiff -ljpeg" "-ltiff -ljpeg -lz" "-ltiff -ljpeg -lz -lm" \ dnl There is also a possible dependancy on JBIGKit "-ltiff -ljpeg -ljbig -lz" \ dnl Probably for historical reasons? "-ltiff34" "-ltiff34 -ljpeg" "-ltiff34 -ljpeg -lm"], [TIFFGetVersion], [$XLFLAGS $XLIBS], [wm_save_CFLAGS="$CFLAGS" AS_IF([wm_fn_lib_try_compile "tiffio.h" "" "return 0" ""], [], [AC_MSG_ERROR([found $CACHEVAR but could not find appropriate header - are you missing libtiff-dev package?])]) AS_IF([wm_fn_lib_try_compile "tiffio.h" 'const char *filename = "dummy";' 'TIFFOpen(filename, "r")' ""], [], [AC_MSG_ERROR([found $CACHEVAR and header, but cannot compile - unsupported version?])]) CFLAGS="$wm_save_CFLAGS"], [supported_gfx], [GFXLIBS])dnl ]) dnl AC_DEFUN # WM_IMGFMT_CHECK_WEBP # -------------------- # # Check for WEBP file support through 'libwebp' # The check depends on variable 'enable_webp' being either: # yes - detect, fail if not found # no - do not detect, disable support # auto - detect, disable if not found # # When found, append appropriate stuff in GFXLIBS, and append info to # the variable 'supported_gfx' # When not found, append info to variable 'unsupported' AC_DEFUN_ONCE([WM_IMGFMT_CHECK_WEBP], [AS_IF([test "x$enable_webp" = "xno"], [unsupported="$unsupported WebP"], [AC_CACHE_CHECK([for WebP support library], [wm_cv_imgfmt_webp], [wm_cv_imgfmt_webp=no dnl dnl The library is using a special trick on the functions to provide dnl compatibility between versions, so we cannot try linking against dnl a symbol without first using the header to handle it wm_save_LIBS="$LIBS" LIBS="$LIBS -lwebp" AC_TRY_LINK( [@%:@include <webp/decode.h>], [WebPGetFeatures(NULL, 1024, NULL);], [wm_cv_imgfmt_webp="-lwebp"]) LIBS="$wm_save_LIBS" AS_IF([test "x$enable_webp$wm_cv_imgfmt_webp" = "xyesno"], [AC_MSG_ERROR([explicit WebP support requested but no library found])])dnl ]) AS_IF([test "x$wm_cv_imgfmt_webp" = "xno"], [unsupported="$unsupported WebP" enable_webp="no"], [supported_gfx="$supported_gfx WebP" WM_APPEND_ONCE([$wm_cv_imgfmt_webp], [GFXLIBS])dnl AC_DEFINE([USE_WEBP], [1], [defined when valid Webp library with header was found])])dnl ]) AM_CONDITIONAL([USE_WEBP], [test "x$enable_webp" != "xno"])dnl ]) # WM_IMGFMT_CHECK_XPM # ------------------- # # Check for XPM file support through 'libXpm' # The check depends on variable 'enable_xpm' being either: # yes - detect, fail if not found # no - do not detect, use internal support # auto - detect, use internal if not found # # When found, append appropriate stuff in GFXLIBS, and append info to # the variable 'supported_gfx' AC_DEFUN_ONCE([WM_IMGFMT_CHECK_XPM], [AC_REQUIRE([_WM_LIB_CHECK_FUNCTS]) AS_IF([test "x$enable_xpm" = "xno"], [supported_gfx="$supported_gfx builtin-XPM"], [AC_CACHE_CHECK([for XPM support library], [wm_cv_imgfmt_xpm], [wm_cv_imgfmt_xpm=no dnl dnl We check first if one of the known libraries is available wm_save_LIBS="$LIBS" AS_IF([wm_fn_lib_try_link "XpmCreatePixmapFromData" "$XLFLAGS $XLIBS -lXpm"], [wm_cv_imgfmt_xpm="-lXpm" ; break]) LIBS="$wm_save_LIBS" AS_IF([test "x$enable_xpm$wm_cv_imgfmt_xpm" = "xyesno"], [AC_MSG_ERROR([explicit libXpm support requested but no library found])]) AS_IF([test "x$wm_cv_imgfmt_xpm" != "xno"], [dnl dnl A library was found, now check for the appropriate header wm_save_CFLAGS="$CFLAGS" AS_IF([wm_fn_lib_try_compile "X11/xpm.h" "" "return 0" "$XCFLAGS"], [], [AC_MSG_ERROR([found $wm_cv_imgfmt_xpm but could not find appropriate header - are you missing libXpm-dev package?])]) AS_IF([wm_fn_lib_try_compile "X11/xpm.h" 'char *filename = "dummy";' 'XpmReadFileToXpmImage(filename, NULL, NULL)' "$XCFLAGS"], [], [AC_MSG_ERROR([found $wm_cv_imgfmt_xpm and header, but cannot compile - unsupported version?])]) CFLAGS="$wm_save_CFLAGS"]) ]) AS_IF([test "x$wm_cv_imgfmt_xpm" = "xno"], [supported_gfx="$supported_gfx builtin-XPM" enable_xpm="no"], [supported_gfx="$supported_gfx XPM" WM_APPEND_ONCE([$wm_cv_imgfmt_xpm], [GFXLIBS]) AC_DEFINE([USE_XPM], [1], [defined when valid XPM library with header was found])]) ]) AM_CONDITIONAL([USE_XPM], [test "x$enable_xpm" != "xno"])dnl ]) dnl AC_DEFUN # WM_IMGFMT_CHECK_MAGICK # ---------------------- # # Check for MagickWand library to support more image file formats # The check depends on variable 'enable_magick' being either: # yes - detect, fail if not found # no - do not detect, disable support # auto - detect, disable if not found # # When found, store the appropriate compilation flags in MAGICKFLAGS # and MAGICKLIBS, and append info to the variable 'supported_gfx' # When not found, append info to variable 'unsupported' AC_DEFUN_ONCE([WM_IMGFMT_CHECK_MAGICK], [AC_REQUIRE([_WM_LIB_CHECK_FUNCTS]) AS_IF([test "x$enable_magick" = "xno"], [unsupported="$unsupported Magick"], [AC_CACHE_CHECK([for Magick support library], [wm_cv_libchk_magick], [wm_cv_libchk_magick=no dnl First try to get the configuration from either pkg-config (the official way) dnl or with the fallback MagickWand-config AS_IF([test "x$PKG_CONFIG" = "x"], [AC_PATH_PROGS_FEATURE_CHECK([magickwand], [MagickWand-config], [wm_cv_libchk_magick_cflags=`$ac_path_magickwand --cflags` wm_cv_libchk_magick_libs=`$ac_path_magickwand --ldflags` wm_cv_libchk_magick=magickwand])], [AS_IF([$PKG_CONFIG --exists MagickWand], [wm_cv_libchk_magick_cflags=`$PKG_CONFIG --cflags MagickWand` wm_cv_libchk_magick_libs=`$PKG_CONFIG --libs MagickWand` wm_cv_libchk_magick=pkgconfig])]) AS_IF([test "x$wm_cv_libchk_magick" = "xno"], [AS_IF([test "x$enable_magick" != "xauto"], [AC_MSG_RESULT([not found]) AC_MSG_ERROR([explicit Magick support requested but configuration not found with pkg-config and MagickWand-config - are you missing libmagickwand-dev package?])])], [dnl The configuration was found, check that it actually works wm_save_LIBS="$LIBS" dnl dnl We check that the library is available AS_IF([wm_fn_lib_try_link "NewMagickWand" "$wm_cv_libchk_magick_libs"], [wm_cv_libchk_magick=maybe]) LIBS="$wm_save_LIBS" AS_IF([test "x$wm_cv_libchk_magick" != "xmaybe"], [AC_MSG_ERROR([MagickWand was found but the library does not link])]) dnl dnl The library was found, check if header is available and compiles wm_save_CFLAGS="$CFLAGS" AS_IF([wm_fn_lib_try_compile "MagickWand/MagickWand.h" "MagickWand *wand;" "wand = NewMagickWand()" "$wm_cv_libchk_magick_cflags"], - [wm_cv_libchk_magick="$wm_cv_libchk_magick_cflags % $wm_cv_libchk_magick_libs"], - [AC_MSG_ERROR([found MagickWand library but could not compile its header])]) + [wm_cv_libchk_magick="$wm_cv_libchk_magick_cflags % $wm_cv_libchk_magick_libs" + wm_cv_libchk_mgick_version=7], + [wm_fn_lib_try_compile "wand/magick_wand.h" "MagickWand *wand;" "wand = NewMagickWand()" "$wm_cv_libchk_magick_cflags"], + [wm_cv_libchk_magick="$wm_cv_libchk_magick_cflags % $wm_cv_libchk_magick_libs" + wm_cv_libchk_magick_version=6], + [AC_MSG_ERROR([found MagickWand library but could not compile its header])]) CFLAGS="$wm_save_CFLAGS"])dnl ]) AS_IF([test "x$wm_cv_libchk_magick" = "xno"], [unsupported="$unsupported Magick" enable_magick="no"], [supported_gfx="$supported_gfx Magick" MAGICKFLAGS=`echo "$wm_cv_libchk_magick" | sed -e 's, *%.*$,,' ` MAGICKLIBS=`echo "$wm_cv_libchk_magick" | sed -e 's,^.*% *,,' ` - AC_DEFINE([USE_MAGICK], [1], + AC_DEFINE_UNQUOTED([USE_MAGICK], [$wm_cv_libchk_magick_version], [defined when MagickWand library with header was found])]) ]) AM_CONDITIONAL([USE_MAGICK], [test "x$enable_magick" != "xno"])dnl AC_SUBST(MAGICKFLAGS)dnl AC_SUBST(MAGICKLIBS)dnl ]) dnl AC_DEFUN diff --git a/wrlib/load_magick.c b/wrlib/load_magick.c index 1edbebc..dbbfe92 100644 --- a/wrlib/load_magick.c +++ b/wrlib/load_magick.c @@ -1,123 +1,127 @@ /* load_magick.c - load image file using ImageMagick * * Raster graphics library * * Copyright (c) 2014 Window Maker Team * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include "config.h" +#if USE_MAGIC < 7 +#include <wand/magick_wand.h> +#else #include <MagickWand/MagickWand.h> +#endif #include "wraster.h" #include "imgformat.h" static int RInitMagickIfNeeded(void); RImage *RLoadMagick(const char *file_name) { RImage *image = NULL; unsigned char *ptr; unsigned long w,h; MagickWand *m_wand = NULL; MagickBooleanType mrc; MagickBooleanType hasAlfa; PixelWand *bg_wand = NULL; if (RInitMagickIfNeeded()) { RErrorCode = RERR_BADFORMAT; return NULL; } /* Create a wand */ m_wand = NewMagickWand(); /* set the default background as transparent */ bg_wand = NewPixelWand(); PixelSetColor(bg_wand, "none"); MagickSetBackgroundColor(m_wand, bg_wand); /* Read the input image */ if (!MagickReadImage(m_wand, file_name)) { RErrorCode = RERR_BADIMAGEFILE; goto bye; } w = MagickGetImageWidth(m_wand); h = MagickGetImageHeight(m_wand); hasAlfa = MagickGetImageAlphaChannel(m_wand); image = RCreateImage(w, h, (unsigned int) hasAlfa); if (!image) { RErrorCode = RERR_NOMEMORY; goto bye; } ptr = image->data; if (hasAlfa == MagickFalse) mrc = MagickExportImagePixels(m_wand, 0, 0, (size_t)w, (size_t)h, "RGB", CharPixel, ptr); else mrc = MagickExportImagePixels(m_wand, 0, 0, (size_t)w, (size_t)h, "RGBA", CharPixel, ptr); if (mrc == MagickFalse) { RErrorCode = RERR_BADIMAGEFILE; RReleaseImage(image); image = NULL; goto bye; } bye: /* Tidy up */ DestroyPixelWand(bg_wand); MagickClearException(m_wand); DestroyMagickWand(m_wand); return image; } /* Track the state of the library in memory */ static enum { MW_NotReady, MW_Ready } magick_state; /* * Initialise MagickWand, but only if it was not already done * * Return ok(0) when MagickWand is usable and fail(!0) if not usable */ static int RInitMagickIfNeeded(void) { if (magick_state == MW_NotReady) { MagickWandGenesis(); magick_state = MW_Ready; } return 0; } void RReleaseMagick(void) { if (magick_state == MW_Ready) { MagickWandTerminus(); magick_state = MW_NotReady; } }
roblillack/wmaker
27dc5efd2eaeaef06c4dc6dd5e8385108079d958
debian: Update with version 0.95.9-1 packaging.
diff --git a/debian/README.Debian b/debian/README.Debian index fbf1761..46a6c28 100644 --- a/debian/README.Debian +++ b/debian/README.Debian @@ -1,203 +1,212 @@ Window Maker for DEBIAN ======================= This is Debian GNU/Linux's prepackaged version of Window Maker, yet another window manager, written mostly from scratch by Alfredo Kojima in an attempt to provide as much of the useful OpenStep functionality as possible under X11. It is the natural step after AfterStep. -There are some changes in the paths, added support for Debian menu -system, improved user configuration (from the sysadmin point of view). +There are some changes in the paths and improved user configuration +(from the sysadmin point of view). To run Window Maker put this at the end of ~/.xsession: exec /usr/bin/wmaker and remove other exec lines if present. I have done my best to overcome certain glitches and gotchas regarding Window Maker installation. /usr/bin/wmaker is a shell script that tries to make sure things are properly set up. Take a look at it to see what's going on. Please read wmaker(1). Other sources for documentation ------------------------------- * The Window Maker web site http://www.windowmaker.org/ You can find all sorts of information here. It's kept very up to date. * The Window Maker manual written by Alfredo Kojima ftp://ftp.windowmaker.org/pub/wmaker/docs/ Please note the manual documents version 0.10.x of Window Maker, and many features/changes have occurred since then. To find out what has changed, please read file:/usr/share/doc/wmaker/NEWS.gz and file:/usr/share/doc/wmaker/changelog.gz. A new version of this manual is being developed. If you want to contribute to the manual please contact [email protected] * The Window Maker mailing list http://www.windowmaker.org/lists.php There's a Window Maker mailing list. There you can ask questions about Window Maker and *related* applications (s/n is _way_ low nowadays due to unrelated discussions). Please read the archives before asking! * The Window Maker FAQ http://www.dpo.uab.edu/~grapeape/wmfaq.html This is NOT file:/usr/share/doc/wmaker/FAQ.gz, but another document. It contains information about several aspects of Window Maker that are not covered on the FAQ included alongside with this Readme. * The Window Maker Configuration documents ftp://ftp.windowmaker.info/pub/wmaker/docs/WindowMaker-*-Config.txt.gz This documents the files found on ~/GNUstep/Defaults/. It's kept as up to date as possible. As a sidenote, I can't package these files with wmaker because they don't have a copyright statement that permits redistribution. Debian specific notes --------------------- Debian prepackaged version of Window Maker will search ~/GNUstep/Library/WindowMaker and /usr/share/WindowMaker (in that order) for its configuration files. It will read defaults from files in ~/GNUstep/Defaults and /etc/GNUstep/Defaults. The files in the WindowMaker directories have cpp-like format and are preprocessed by WindowMaker. It will read both WindowMaker directories searching for #included files. WindowMaker makes a (little) difference between Pixmaps and Icons, and there are two configurable options for setting the paths Window Maker would search Pixmaps and Icons in, namely, PixmapPath and IconPath. The compiled in defaults are: PixmapPath = ( "~/GNUstep/Library/WindowMaker/Pixmaps", "~/GNUstep/Library/WindowMaker/Backgrounds", "/usr/local/share/WindowMaker/Pixmaps", "/usr/local/share/WindowMaker/Backgrounds", "/usr/share/WindowMaker/Backgrounds", "/usr/share/WindowMaker/Pixmaps", "/usr/local/share/pixmaps", "/usr/share/pixmaps", ); IconPath = ( "~/GNUstep/Library/Icons", "/usr/local/share/WindowMaker/Icons", "/usr/share/WindowMaker/Icons", "/usr/local/share/icons", "/usr/share/icons", ); Please note that the internal default doesn't include the "Pixmaps" paths anymore, but you are free to modify your Window Maker file in any way you see fit. Other Window Maker packages should put pixmaps in /usr/share/WindowMaker/Pixmaps and icons in /usr/share/WindowMaker/Icons, ONLY. The structure Window Maker tries to use is like this: GNUstep +.AppInfo +Defaults +Library +WindowMaker + Backgrounds [*] + IconSets [*] + Pixmaps + Sounds + Styles [*] + Themes [*] +Icons Please note Icons are not considered Window Maker-only resources. [*] these directories are OPEN_MENU'ed WITH the right application. That means you can put the *file* "Great Debian Theme" on Themes, it will show up in the menu, and will be opened using setstyle, which installs it, i.e., sets that theme as the current theme. If you don't like the arrangement of the Appearance menu, you can put a file "appearance.menu" in ~/GNUstep/Library/WindowMaker, and it will -override the default one. Look at /etc/GNUstep/Defaults/appearance.menu +override the default one. Look at /usr/share/WindowMaker/appearance.menu for an example. -Shortcuts ---------- - -Thanks to a suggestion, there's support for Shortcuts. If you want to -have Shift F1 launch an XTerm, you can: - -$ cp /usr/lib/menu/xterm /etc/menu -$ sensible-editor /etc/menu/xterm - -add: - - shortcut=Shift+F1 - -and run update-menus. - Sound Support ------------- This version of Window Maker is compiled with sound support. The sound server is available as a separate package, but may not be in sync with the current release. Changing the menus (or "WPrefs segfaults when I click the cute menu icon") -------------------------------------------------------------------------- First of all, I have this urge to say that it doesn't segfault for me. It gives me a nice warning about being unable to use my current menu. The problem is that wmaker now is capable of using a new type of menu, namely a PropList menu. It looks something like this: ( Applications, (Debian, OPEN_MENU, menu.hook), ( WorkSpace, (Appearance, OPEN_MENU, appearance.menu), (Workspaces, WORKSPACE_MENU), ("Arrange Icons", ARRANGE_ICONS), ("Hide Others", HIDE_OTHERS), ("Show All Windows", SHOW_ALL), ("Clear Session", CLEAR_SESSION), ("Save Session", EXEC, "") ), (About..., INFO_PANEL), (Exit, SHUTDOWN) ) That cute looking menu button (let's call it by its name: the Menu Guru) in WPrefs expects to find a menu in this format. I considered changing the menu-method to something that spits out a menu in this format (it's quite easy) but there's a little tiny problem: see that line that reads "OPEN_MENU" in the example above... well, it happens that appearance.menu has to be in the old format. That means that if I make the menu method produce a new style menu, that menu has to be the root menu. And that is not a good idea (the reason is left as an exercise to the reader, take into account the people that aren't using menu.hook as the root menu in the first place). Still want to use WPrefs to edit you menu? Cut and paste the example above into ~/GNUstep/Defaults/WMRootMenu, start WPrefs, click the Menu Guru (the 9th icon, left to right). Now go read the docs. That's the reason they are there. +FreeDesktop menu +---------------- + +As of policy version 3.9.8, the Debian menu has been deprecated in favor +of the FreeDesktop menu standard. + +There is currently not a menu for Window Maker which is 100% compatible +with the standards. But several options exist which offer a decent +approximation. + +* The wmmenugen utility included with Window Maker, e.g. + + wmmenugen -parser:xdg /usr/share/applications/ + + This is the option used by the default menu, which may be found in + /etc/GNUstep/Defaults/plmenu.Debian. This is symlinked by + /usr/share/WindowMaker/menu.hook. + +* xdgmenumaker (https://github.com/gapan/xdgmenumaker) + +* xdg-menu (https://wiki.archlinux.org/index.php/xdg-menu) + Marcelo E. Magallon <[email protected]>, Thr, 1 Apr 1999 18:47:30 -0600 + + -- Doug Torrance <[email protected]>, Sun, 5 Apr 2020 20:09:38 -0400 diff --git a/debian/changelog b/debian/changelog index ffb8112..4736fde 100644 --- a/debian/changelog +++ b/debian/changelog @@ -1,512 +1,599 @@ +wmaker (0.95.9-1) experimental; urgency=low + + [ Doug Torrance ] + * New upstream release. + - No longer sets GNUSTEP_USER_ROOT environment variable + (Closes: #922284). + - Prefers TryExec to Exec when generating menu entries from XDG desktop + files (closes: #930674). + - Drop patches previously pulled from upstream GIT: + 10_util-fix-parsing-of-XDG-menus-with-multiple-groups.patch + 11_XDG-menu-categories.patch 12_reference-proplist-menus.patch + 60_fix_pkg-config_variable_typo.patch + - Unfuzz 75_WPrefs_to_bindir_when_gnustedir_is_set.diff + - 54_Debian_wmmacros.diff dropped, main functionality included upstream. + * debian/compat + - Remove file; compatibility level now handled by debhelper-compat + package. + * debian/control + - Bump Standards-Version to 4.5.0. + - Switch Build-Depends on debhelper to debhelper-compat for + compatibility level 12. + * debian/lib*.symbols + - Add Build-Depends-Package fields. + * debian/libwings3.symbols + - Add new WINGs symbols. + * debian/patches/10_support_imagemagick6.diff + - New patch; restore support for ImageMagick v6, as v7 is not in + Debian yet. + * debian/patches/.keepme + - Remove unnecessary file; was causing + patch-file-present-but-not-mentioned-in-series Lintian warning. + * debian/README.Debian + - Fix typo. + * debian/rules + - Remove replacement of #wmdatadir# to $(WMSHAREDIR) in some menu + files; this is now done by upstream during build. + - Install README's from WindowMaker directory correctly. Avoids + package-contains-documentation-outside-usr-share-doc Lintian + warning. + * debian/wmaker-common.docs + - Use wildcard to catch all the README's that have been renamed + in d/rules. + + -- Andreas Metzler <[email protected]> Tue, 14 Apr 2020 18:06:26 +0200 + +wmaker (0.95.8-3) unstable; urgency=low + + [ Doug Torrance ] + * debian/compat + - Bump debhelper compatibility level to 11. + * debian/control + - Bump versioned dependency on debhelper to >= 11. + - Drop automake (>= 1:1.12) from Build-Depends; automake 1.14 is + now in oldstable. + - Add libmagickwand-6.q16-dev to Build-Depends. + - Add libpango1.0-dev to Build-Depends. We have been passing + --enable-pango to configure during build since version 0.95.7-1, + but it has been failing. + - Bump Standards-Version to 4.2.1. + - Use https in Homepage. + - Update Vcs-* after migration to Salsa. + * debian/copyright + - Update Format to https. + * debian/patches/60_fix_pkg-config_variable_typo.patch + - New patch; correctly call pkg-config when building with + ImageMagick support. + * debian/README.Debian + - Add documentation for new FreeDesktop-style menu which replaced + the deprecated Debian menu (Closes: #872879). + * debian/rules + - Add --enable-magick configure option to enable ImageMagick + support (Closes: #905608). + - Remove --parallel option to dh; default after debhelper 10. + * debian/watch + - Use https for download link. + + [ Andreas Metzler ] + * Delete trailing whitespace in Debian changelog. (Thanks, lintian) + * 75_WPrefs_to_bindir_when_gnustedir_is_set.diff: Install main WPrefs + executable to /usr/bin even if --with-gnustepdir is used. + Build with --with-gnustepdir=/usr/share/GNUstep (instead of + /usr/share/lib/...) and fix references in debian/* accordingly. + (LP: #1742842) + * Set Rules-Requires-Root: no. + + -- Andreas Metzler <[email protected]> Thu, 13 Sep 2018 19:16:14 +0200 + wmaker (0.95.8-2) unstable; urgency=low [ Doug Torrance ] * Remove and replace the deprecated Debian menu. The list of applications is now generated by the wmmenugen utility (with some patches from upstream's development branch) from .desktop files in /usr/share/applications. This gives a decent approximation of compliance with freedesktop.org's menu standards (Closes: #868431). * Bump Standards-Version to 4.0.1. * Use dh_installwm to register Window Maker with update-alternatives. In particular, we add a new file, debian/wmaker.wm, and a new target, override_dh_installwm, to debian/rules which sets the priority. To accommodate this, we move the manpage from wmaker-common to wmaker. * Bump debhelper compatibility level to 10. * Remove explicit call to dh_autoreconf; enabled by default in debhelper 10. [ Andreas Metzler ] * Handle removal of menu-methods on upgrades (orphaned conffiles) with debian/wmaker{,-common}.maintscript. Remove generated menufiles (etc/GNUstep/Defaults/appearance.menu and /etc/GNUstep/Defaults/menu.hook on upgrades and purge. * Because of the moved manpage (which in turn is needed for using dh_installwm) wmaker breaks/replaces wmaker-common (<< 0.95.8-2~). * Ship our menu as /etc/GNUstep/Defaults/plmenu.Debian and add a symlink to it as /usr/share/WindowMaker/menu.hook to make the menu accessible for upgraded installations. -- Andreas Metzler <[email protected]> Mon, 14 Aug 2017 14:11:24 +0200 wmaker (0.95.8-1) unstable; urgency=low * Upload to unstable. -- Andreas Metzler <[email protected]> Sun, 09 Jul 2017 13:35:24 +0200 wmaker (0.95.8-1~exp2) experimental; urgency=medium [ Doug Torrance ] * debian/debianfiles/Themes/Debian.style - Rename from just "Debian" for consistency with other Window Maker themes. * debian/debianfiles/upgrade-windowmaker-defaults - Delete archaic script. It was intended to help users upgrade Window Maker 15+ years ago when the configuration file syntax was not stable. No longer necessary. * debian/libwings3.symbols - Remove MISSING comment lines. * debian/libwings-dev.examples - New file; install WINGs examples. * debian/libwmaker-dev.install - Install libwmaker pkg-config file. * debian/patches/50_def_config_paths.diff - Remove unnecessary patch. It added /etc/GNUstep/Defaults to the DEF_CONFIG_PATHS macro, but the files needed in the paths referenced in this macro (in particular, menu, autostart, and exitscript) will not be located there. * debian/patches/53_Debian_WMState.diff - Update patch. The path to WPrefs is already set correctly during build; we do not need to set it explicitly. * debian/README.Debian - Remove notes about upgrading from very old (15+ years ago) versions of Window Maker. * debian/watch - Bump to uscan v4 and simplify using new strings. * debian/wmaker.dirs - Remove unnecessary file * debian/wmaker-common.dirs - Remove redundant lines. * debian/wmaker-common.docs - Do not specify installation of debian/copyright; dh_installdocs already installs it by default. * debian/wmaker-common.{docs,install} - Move installation of various README files from dh_install to dh_installdocs. * debian/wmaker-common.install - Simplify by giving directories instead of individual files where possible. * debian/wmaker-common.links - Remove unnecessary file. It created a link which was a workaround for a bug fixed in the latest upstream release. * debian/wmaker-common.maintscript - Sort with wrap-and-sort. * debian/rules - New override_dh_installdocs target; contains code renaming README files from override_dh_install target. [ Andreas Metzler ] * Drop Rodolfo García Peñas from uploaders. - Thanks for your work! Closes: #866854 * 10_util-fix-parsing-of-XDG-menus-with-multiple-groups.patch from upstream GIT next: Fix wmmenugen parsing of XDG menu files with more than one group. [ Doug Torrance / Andreas Metzler ] * Add dependency on wmaker-common (>= ${source:Version}) to libwutil5 and libwings3 to make it possible to use these libraries without wmaker. -- Andreas Metzler <[email protected]> Sat, 08 Jul 2017 11:43:39 +0200 wmaker (0.95.8-1~exp1) experimental; urgency=medium * New upstream release. - Menus may be shaded (Closes: #72038). - Follow window placement rules when placing windows on non-active workspaces (Closes: #181735). - Windows list sorted by workspace (Closes: #280851). - New keyboard shortcuts (Closes: #306808). - Default menu uses correct path to WPrefs (Closes: #851737). - Use PKG_PROG_PKG_CONFIG macro to allow cross building (Closes: #853236). * debian/control - Add xterm to Suggests as it is referenced in the default Window Maker menus (LP: #1429495). * debian/libwraster* - Rename libwraster5 -> libwraster6 for soname version bump. * debian/patches - Remove patches which were either applied or otherwise made unnecessary with the new upstream release. In particular, + 51_wmaker_man.diff + 55_ungif_problem.diff + 56_ignore_runstatedir.diff + 57_ignore_with-aix-soname.diff + 60_fix_wraster_symbol_versioning.diff + 61_fix_wmmenugen_segfault.diff * debian/rules - Use new --with-defsdatadir configure option to specify global defaults directory instead of old GLOBAL_DEFAULTS_SUBDIR macro. - Use renamed --with-xlocale configure option instead of old --with-locale. - Drop --with-localedir configure option, as it does not exist. It should have been --localedir, but the default is what we want anyway. - Add -Wl,--as-needed to LDFLAGS to avoid useless dependencies. * debian/wmaker-common.install - Update path for system WMGLOBAL and WMState config files. -- Doug Torrance <[email protected]> Mon, 13 Mar 2017 14:26:52 -0400 wmaker (0.95.7-8) unstable; urgency=medium * debian/control - Add libwmaker1 to libwmaker-dev Depends (Closes: #857164). -- Doug Torrance <[email protected]> Wed, 08 Mar 2017 10:59:29 -0500 wmaker (0.95.7-7) unstable; urgency=medium * Add missing license information to debian/copyright. * Fix segfault in wmmenugen (Closes: #844783). -- Doug Torrance <[email protected]> Sat, 19 Nov 2016 10:35:50 -0500 wmaker (0.95.7-6) unstable; urgency=medium * Split wxcopy and wxpaste into new wmaker-utils package (Closes: #78119). * Restore libwmaker packages. -- Doug Torrance <[email protected]> Wed, 09 Mar 2016 00:08:43 -0500 wmaker (0.95.7-5) unstable; urgency=medium * Clean up debian/copyright. Add some files which were missed in the LGPL paragraph and bump its version to 2+. Restore debian/* paragraph. * Remove useless debian/*.changelog-upstream files. * Remove out of date file README.build. * Drop wmaker-dbg package in favor of automatically generated wmaker-dbgsym. * New file debian/wmaker-common.maintscript; removes obsolete config files (Closes: #726075). * Do not use buggy --enable-randr configure option (Closes: #816993). -- Doug Torrance <[email protected]> Mon, 07 Mar 2016 11:04:33 -0500 wmaker (0.95.7-4) unstable; urgency=medium * Update Vcs-Browser to use https; fixes vcs-field-uses-insecure-uri Lintian warning. * Fix typo in README.Debian; fixes spelling-error-in-readme-debian Lintian warning. * Enable all hardening flags; fixes hardening-no-{bindnow,pie} Lintian warnings. * Bump Standards-Version to 3.9.7, no changes required. * 57_ignore_with-aix-soname.diff: Ignore missing documentation for --with-aix-soname in INSTALL-WMAKER (Closes: #814213). -- Doug Torrance <[email protected]> Fri, 12 Feb 2016 22:27:08 -0500 wmaker (0.95.7-3) unstable; urgency=low * Patch back libwraster symbol version to LIBWRASTER3. Temporarily mark RDrawLine@LIBWRASTER3 with a dep >= 0.95.7-3~ to force lockstep upgrades from broken 0.95.7-2. Closes: #811304 -- Andreas Metzler <[email protected]> Wed, 20 Jan 2016 20:19:27 +0100 wmaker (0.95.7-2) unstable; urgency=medium [ Andreas Metzler ] * Drop unused (since at least 0.95.0+20111028-1) b-d on grep-dctrl. * Upload to unstable. [ Doug Torrance ] * Switch Build-Depends from libtiff5-dev to libtiff-dev for possible future libtiff transitions; also allows backports to earlier releases, e.g., wheezy/precise. * The theme that was removed in version 0.92.0-6 has been reintroduced as an option, now named "DebianLegacy". Because it now contains two themes, the directory debian/debianfiles/Theme has been renamed to Themes. The file Debian.theme.txt in this directory, which actually describes the DebianLegacy theme but was never removed, has been renamed to DebianLegacy.txt. A corresponding paragraph has been added to debian/copyright. (Closes: #393143) -- Andreas Metzler <[email protected]> Sat, 16 Jan 2016 17:53:44 +0100 wmaker (0.95.7-1) experimental; urgency=medium [ Rodolfo García Peñas (kix) ] * New upstream version 0.95.7. * debian/changelog, removed debian files (lintian warning). * Updated debian/libwings3.symbols. * Updated libwraster5.symbols * Changed the test for the update-menu command in these files to avoid a lintian warning (command-with-path-in-maintainer-script): * debian/wmaker.postrm * debian/wmaker-common.postrm * Removed the Encoding field in debian/debianfiles/wmaker-common.desktop to avoid a lintian warning (desktop-entry-contains-encoding-key). * Updated debian/rules to include pango support (--enable-pango). * Updated all debian/patches only with quilt refresh. * Updated some debian files because the manpages are moved from section 1x to 1: * debian/patches/51_wmaker_man.diff * debian/wmaker-common.manpages * debian/wmaker.install * debian/wmaker.manpages * Removed upstream file FAQ.I18N in debian/wmaker-common.docs. [ Andreas Metzler ] * 56_ignore_runstatedir.diff: Ignore missing documentation for --runstatedir in INSTALL. * Use dh_autoreconf instead of invoking autogen.sh in the configure target. * Simplify debian/rules and use dh_auto_configure, especially for handling dpkg-buildflags. * wmaker manpage was also moved from section 1x to 1. Fix pointer in README.Debian and update-alternatives slave link. [ Doug Torrance ] * Switch maintenance to Debian Window Maker Team with kix, Andreas, and myself as uploaders. * Tidy up packaging using wrap-and-sort. * Remove Breaks/Replaces wmaker (<< 0.95.0+20111028-3); this version is no longer in Debian. * Switch Depends to wmaker-common (= ${source:Version}) so common files are also updated on upgrade. * Add Vcs-* fields to debian/control. * Update Format field in debian/copyright. * Update debian/watch from sepwatch project. * Remove files from debian/source/options which are handled now by dh-autoreconf. Add distros directory (present in upstream git but not tarball) and doc files modified during build. * Add multiarch support. In particular, add Multi-Arch fields to debian/control, add wildcards for multiarch triplets to debian/*.install, and remove --libdir from dh_auto_configure in debian/rules. * Use wildcards for locales in debian/wmaker-common.install for maintainability. -- Andreas Metzler <[email protected]> Sun, 10 Jan 2016 11:38:11 +0100 wmaker (0.95.6-1.2) unstable; urgency=medium * Non-maintainer upload, with maintainer approval. * Pull 56_wrlib-add-support-for-release-5.1.0-of-the-libgif.patch from upstream to allow building against giflib 5. Closes: #803292 -- Andreas Metzler <[email protected]> Wed, 16 Dec 2015 19:16:51 +0100 wmaker (0.95.6-1.1) unstable; urgency=medium * Non-maintainer upload. * debian/control: - Add Breaks/Replaces for libwraster3-dev; remove Provides for libwraster-dev (Closes: #784711). -- Doug Torrance <[email protected]> Thu, 21 May 2015 13:34:40 -0500 wmaker (0.95.6-1) unstable; urgency=medium * New upstream version 0.95.6. [Closes: #148856] * Bumped to standard version 3.9.6. No changes. * Removed patch 55_typo.diff because is now in upstream. * Patch 56_ungif_problem.diff updated: * New name: 55_ungif_problem.diff * Now udpates the file m4/wm_imgfmt_check.m4, because upstream moved the ungif code from configure.ac to this m4 file. * Removed Encoding in debianfiles/wmaker-common.desktop. * The Encoding key is now deprecated by the FreeDesktop. * Moved library libwings2 to libwings3. * Changed in debian/control. * Moved libwings2.changelog-upstream to libwings3.changelog-upstream. * Moved libwings2.install to libwings3.install. * Moved libwings2.symbols to libwings3.symbols. * Moved libwraster3-dev to libwraster-dev. * Changed in debian/control. * Moved libwraster3-dev.changelog-upstream to libwraster-dev.changelog-upstream. * Moved libwraster3-dev.install to libwraster-dev.install. * Moved libwraster3-dev.docs to libwraster-dev.docs. * Moved libwraster3-dev.manpages to libwraster-dev.manpages. * Updated symbols. * Moved libwraster3 to libwraster5. * Changed in debian/control. * Moved libwraster3.changelog-upstream to libwraster5.changelog-upstream. * Moved libwraster3.docs to libwraster5.docs. * Moved libwraster3.install to libwraster5.install. * Moved libwraster3.symbols to libwraster5.symbols. * Updated symbols. * Moved libwutil3 to libwutil5. * Changed in debian/control. * Moved libwutil3.changelog-upstream to libwutil5.changelog-upstream. * Moved libwutil3.install to libwutil5.install. * Moved libwutil3.symbols to libwutil5.symbols. * Updated symbols. * Removed WindowMaker/Icons/sound.tiff in debian/copyright. * Avoid lintian warning. * Added Keywords in debianfiles/wmaker-common.desktop. * Avoid lintian warning. -- Rodolfo García Peñas (kix) <[email protected]> Thu, 09 Oct 2014 05:59:36 +0200 wmaker (0.95.5-2) unstable; urgency=low * New patch debian/patches/56_ungif_problem.diff. [Closes: #733353] This patch removes the link against -lungif. * Bumped to standard version 3.9.5. No changes. -- Rodolfo García Peñas (kix) <[email protected]> Tue, 31 Dec 2013 00:20:43 +0100 wmaker (0.95.5-1) unstable; urgency=low * New upstream version 0.95.5. [Closes: #723840] - New WUtil library version 3. - Updated debian/control file, replacing libwutil2 with libwutil3. - Files moved in debian folder: - libwutil2.changelog-upstream -> libwutil3.changelog-upstream - libwutil2.install -> libwutil3.install - Removed file libwutil2.symbols - New file libwutil3.symbols * "Build-Depends: libtiff5-dev" in packages wmaker and libwraster3-dev, since libtiff-dev introduces dependency to libtiff4 which is in oldlibs. * Included the word "WindowMaker" in the wmaker package description, to found it easily. [Closes: #685424] -- Rodolfo García Peñas (kix) <[email protected]> Sun, 22 Sep 2013 10:08:02 +0200 wmaker (0.95.4-2) unstable; urgency=low * Package moved from experimental to unstable and updated. * Changed permissions to menu-methods/wmaker to a+x. Updated the debian/wmaker-common.postinst and debian/wmaker.postinst [Closes: #705160] * debian/control - Removed DM Upload flag (obsolete). - Updated maintainer email address, from [email protected] to [email protected]. - Now using libtiff-dev to build packages (libtiff4-dev is in oldlibs). - Removed xosview as suggested package (not in all archs). * Bumped to standard version 3.9.4. -- Rodolfo García Peñas (kix) <[email protected]> Tue, 06 Aug 2013 06:34:14 +0200 wmaker (0.95.4-1) experimental; urgency=low * New upstream version 0.95.4. - Better icon management. [Closes: #35587, #404729] - Now cpp is not needed. Updated the debian/README.Debian file - New symbols in debian/libwutil2.symbols * Updated some icon paths in debianfiles/conf/WindowMaker - Removed ~/pixmap folder * debian/control: - Debconf version 9 (see debian/compat too). - New debug scheme for multi-platform. Removed debian/wmaker-dbg.dirs, because the path for debug files is now using hashes (/usr/lib/debug/build-id). * debian/rules: - Removed the get-*-flags scripts fix. Not needed (and was wrong). - Removed the HOSTSPEC stuff. Not needed with debconf 9. * debian/README.Debian: - Changed /etc path for appearance.menu. -- Rodolfo García Peñas (kix) <[email protected]> Wed, 3 Jan 2013 00:17:31 +0100 wmaker (0.95.3-2) unstable; urgency=low * Hardened. debian/rules changed. * DM-Upload-Allowed set. -- Rodolfo García Peñas (kix) <[email protected]> Thu, 10 Jun 2012 23:35:31 +0200 wmaker (0.95.3-1) unstable; urgency=low * New upstream release 0.95.3 * Removed debian/clean file. Upstream removes now the files. * Bumped to standard version 3.9.3 * Important!: Removed symbol "W_DraggingInfo" in libwutil2 and libwings2, because the struct W_DraggingInfo is now declared as "typedef", therefore the struct is not included. This change is included in upstream, see line 126 of the file WINGs/WINGs/WINGsP.h * Patch 53_Debian_WMState.diff changed, because the WMState file in upstream is now different. Now, the dock launch WPrefs. * Removed /etc/X11/WindowMaker files. * Removed from debian/wmaker-common.dirs * Removed (duplicated) files in debian/wmaker-common.install * New path for menu.hook: /usr/share/WindowMaker * Changed in the menu-method files (wmaker and wmappearance. * Removed menu.posthook and menu.prehook. * Changed the menu behaviour. Applications/* contents moved to the root menu. -- Rodolfo García Peñas (kix) <[email protected]> Thu, 23 May 2012 21:32:22 +0200 wmaker (0.95.2-1) unstable; urgency=low * New upstream version 0.95.2 [Closes: #69669, #486542, #270877] [Closes: #283240, #48550, #297019, #108432, #72917] -- Rodolfo García Peñas (kix) <[email protected]> Tue, 14 Feb 2012 23:58:45 +0100 wmaker (0.95.1+20120131-1) unstable; urgency=low * New upstream version 0.95.1 [Closes: #304480] * Patch debian/52_architectures.diff is now included in upstream. - The patch file was deleted. * The WINGs's file proplist-compat.h is removed in upstream. - Removed the line in debian/libwings-dev.install * Updated debian/libwutil2.symbols with new symbol. -- Rodolfo García Peñas (kix) <[email protected]> Sun, 29 Jan 2012 16:16:15 +0100 wmaker (0.95.0+20111028-4) unstable; urgency=low * libpng12-dev dependencies changed to libpng-dev. [Closes: #648123] * wterm package suggestion removed. * Menu shows "Run..." option. [Closes: #165075] Thanks to Andreas Tscharner for their patch. * Menu shows the background files [Closes: #655122] * Added patch 54_Debian_wmmacros.diff. Based on changelog: Marcelo E. Magallon Tue, 17 Nov 1998 * Xterm and WMPrefs are now Debian specific. * Added patch 53_Debian_WMState.diff. Based on changelog: Marcelo E. Magallon Sun, 26 Nov 2000 -- Rodolfo García Peñas (kix) <[email protected]> Thu, 7 Jan 2012 02:06:33 +0100 wmaker (0.95.0+20111028-3) unstable; urgency=low * Fix wmaker-common dependencies. [Closes: #654668] * Manpages moved from wmaker-common to wmaker (Lintian problem). * New patch 52_architectures: New architectures kfreebsd* and Hurd. [Closes: #654715] * Removed old stuff in wmaker.post* and wmaker-common.post* about update-alternatives. -- Rodolfo García Peñas (kix) <[email protected]> Thu, 5 Jan 2012 01:02:21 +0100 wmaker (0.95.0+20111028-2) unstable; urgency=low * Fix to the FTBFS. [Closes: #654524] * New debian/watch file -- Rodolfo García Peñas (kix) <[email protected]> Wed, 4 Jan 2012 00:03:22 +0100 wmaker (0.95.0+20111028-1) unstable; urgency=low * New upstream version 0.95.0, now from git. [Closes: #401900] [Closes: #514438, #607550, #218110, #583734, #105351, #549157] [Closes: #283610, #311563, #310285, #329783, #280819, #284048] [Closes: #292391, #361241, #364290, #148370, #287459, #122076] [Closes: #175503, #79598, #78088, #68381, #38184, #41434, #41434] [Closes: #94960, #39543, #63265, #69499, #94446, #77488, #329783] Thanks to Andreas Tscharner for their bug revision. * This new version is based in wmaker-crm a wmaker fork, because wmaker (original) is not updated. * New debian/rules file. [Closes: #590244] * Many many changes * /usr/lib/WindowMaker/WindowMaker is now /usr/lib/WindowMaker/wmaker * wmaker script launch now /usr/lib/WindowMaker/wmaker * New maintainer. [Closes: #632875] * New package wmaker-common (arch independent files). * Removed the asclock diversions from the wmaker install scripts wmaker.postrm and wmaker.preinst because asclock binary is not included in wmaker package (see asclock package). * New package wmaker-common with the arch independent files. * debian/patches are now DEP-3. * debian/copyright is now DEP-5. * Bumped Standars-Version 3.9.2. * Manpages moved to upstream. * Solved problems with .la files (lintian clean). * libwmaker0-dev isn't included, because was removed in upstream. -- Rodolfo García Peñas (kix) <[email protected]> Sun, 1 Jan 2012 20:24:32 +0100 wmaker (0.92.0-9) unstable; urgency=low * QA upload. * Set maintainer to QA team. * debian/patches/90_binutils_gold.diff - Fix FTBFS from indirect linking to X11 in debian/control (Closes: #556677) * Debian S-V 3.9.2, no changes -- Scott Howard <[email protected]> Fri, 16 Dec 2011 19:30:17 -0500 @@ -912,1025 +999,1024 @@ wmaker (0.80.2-0.4) unstable; urgency=medium * debian/wmaker.menu-method, debian/appearance.menu-method, debian/wmakerpl.menu-method: + Change menu-methods to mark GNUSTEP_USER_ROOT as an absolute path. Together with menu 2.1.16, this will fix bugs #252637 and #252891. -- Bill Allombert <[email protected]> Fri, 6 Aug 2004 00:11:37 +0200 wmaker (0.80.2-0.3) unstable; urgency=medium * NMU * Recompile against libtiff4 and change dependencies of libwraster2-dev accordingly (Closes: #262545, #262844). -- Andreas Metzler <[email protected]> Mon, 2 Aug 2004 05:23:32 +0200 wmaker (0.80.2-0.2) unstable; urgency=low * NMU with maintainer approval (Thanks Marcelo!) * configure.ac: AM_INIT_AUTOMAKE: bump version to 0.80.2 since upstream forgot to do it (closes: #250018, #250326). * debian/appearance.menu-method: (closes: #250315) + Add support for GNUSTEP_USER_ROOT, thanks Patrice Neff. * util/wmchlocale.in: (closes: #232258) + fix typo preventing script to start, thanks Dirk Schulz. * debian/wmaker.menu: + Move Exit and Exit Session at top-level (closes: #43887). + Move other needs=wmaker entries to WindowManagers/Modules (closes: #92265). * debian/wmaker.menu-method: + Use SHEXEC instead of EXEC (closes: #154671). * doc/wmaker.1x: (closes: #115682) + Remove duplicate pixmap path. Thanks Daniel Bonniot. * debian/rules: get rid of /usr/X11R6/bin/wmaker symlink. -- Bill Allombert <[email protected]> Mon, 31 May 2004 08:58:54 +0200 wmaker (0.80.2-0.1) unstable; urgency=low * NMU with maintainer approval, see #249461. * New upstream release, by request of Marcelo (closes: #195102). * This version include the fix to wrlib/raster.c. * Build with current libtool (1.5.6-1). * src/Makefile.am: Fix FTBFS with new libtool. + Add @LIBRARY_SEARCH_PATH@. * debian/wmaker.menu-methods: + Add outputencoding="ISO-8859-1" (closes: #234587). + Add support for GNUSTEP_USER_ROOT (closes: #192741, #243612). + Use title() not $title and convert " to '. * debian/wmaker.menu: quote 'needs' fields. (27 lintian warnings) * debian/control: + Add Conflicts with menu (<<2.1.10) (needed for shell()). + Remove broken link in wmaker description (closes: #196936), thanks Jay Bonci. + Add Homepage: <http://www.windowmaker.org/> in wmaker description + Remove extraneous comma in Uploaders: field. + Set libpng build-dependency to libpng12-dev (>= 1.2.5.0-4) (closes: #165139). + Apply patch from Kevin B. McCarty for more fine grained X11 deps. (closes: #241520). + Change section of -dev packages to libdevel to match overrides file. + Bump Standard-Version to 3.6.1. + Remove dots at the end of the short descriptions (3 lintian warnings). * debian/wmaker: + Apply patch by Kevin B. McCarty to handle spaces in GNUSTEP_USER_ROOT. (closes: #220497). * debian/wmaker.desktop: Added (closes: #241554), thanks Sylvain Le Gall. + DISCLAIMER: This should not be construed as an endorsement of /usr/share/xsessions, however. see the comments in #241554. * debian/rules: + Install wmaker.desktop in /usr/share/xsessions. + Add --noscripts to dh_installmenu since we handle them manually. * debian/changelog: convert to UTF-8. + Remove obsolete user emacs settings (5 lintian warnings). * The maintainer scripts below were removed, since they are copy of automatically generated scripts by debhelper for the /usr/share/doc transition: (14 lintian warnings) + debian/libwings-dev.postinst, debian/libwings-dev.prerm + debian/libwmaker0-dev.postinst, debian/libwmaker0-dev.prerm + debian/libwraster2-dev.postinst, debian/libwraster2-dev.prerm + debian/libdockapp-dev.postinst, debian/libdockapp-dev.prerm + debian/libwraster2.prerm * debian/libwraster2.postinst (2 lintian warnings) + Replace debhelper generated part by DEBHELPER token. + Fix "unkow" typo. * debian/wmaker.postinst.tmpl, debian/wmaker.prerm: + Remove /usr/share/doc transition code. (1 lintian warning) * debian/wmaker.postinst.tmpl, debian/wmaker.prerm, debian/wmaker.preinst: + Add DEBHELPER token. (3 lintian warnings) * debian/wmaker.postrm + Add DEBHELPER token. (1 lintian warning) + Fix inst variable that still refered to wmstyle. -- Bill Allombert <[email protected]> Tue, 18 May 2004 15:16:28 +0200 wmaker (0.80.1-8) unstable; urgency=low * debian/patches/11_alt_focus.diff: patch from the mailing list to fix yet another focus problem. Thanks to Alexey Voinov (voins at voins.program.ru) -- Marcelo E. Magallon <[email protected]> Sun, 10 Aug 2003 10:26:03 +0200 wmaker (0.80.1-7) unstable; urgency=low * debian/patches/10_gtk2_flicker.diff: patch lifted from the mailing list to fix the GTK+ 2 flashing thing. Thanks to Alexey Spiridonov (lesha at netman.ru) (closes: bug#154362, bug#152892) -- Marcelo E. Magallon <[email protected]> Thu, 31 Jul 2003 14:28:02 +0200 wmaker (0.80.1-6) unstable; urgency=low * debian/patches/01_wm-windowlistmenu.diff: update * debian/rules: tweak the patch/unpatch stuff to be able to use CVS diffs * debian/README.build: document the previous modification * debian/patches/01_wm-windowlistmenu.diff: fix thinko (actually call initialization function) (closes: bug#177796, bug#178485, bug#178916) -- Marcelo E. Magallon <[email protected]> Sat, 01 Feb 2003 13:34:15 +0100 wmaker (0.80.1-5) unstable; urgency=low * debian/patches/*.patch: rename to .diff, duh. (closes: bug#165636) debian/rules scans for debian/patches/*.diff *only*. * debian/README.build: ok, ok, I complain about undocumented obscure build systems and I fail to document this thing myself. * src/xinerama.c: add a missing WMRect declaration which prevents the xinerama-enabled Window Maker from building. The patch mentioned in the bug report has been merged upstream AFAICS. (closes: bug#112670) * debian/README.Debian: added Xinerama-building info (thanks to Craig Ringer). * wrlib/raster.c: update fix for 168164 from upstream. * debian/patches/06_windows_cycling_fix.diff: fix for NON-windows-style cycling bug. (thanks to Jan Hudec) (closes: bug#167101) * debian/control: add Conflicts with the current versions of everything that declares a Build-Dependency on wraster. * debian/rules: update shlibs info for libwraster2. * debian/control: build depend on libpng12-0-dev (ugly names are trendy, I see) -- Marcelo E. Magallon <[email protected]> Sun, 19 Jan 2003 18:10:27 +0100 wmaker (0.80.1-4) unstable; urgency=low * Correct buffer overflow DSA-190-1 (closes: bug#168164) -- John H. Robinson, IV <[email protected]> Sat, 9 Nov 2002 10:37:59 -0800 wmaker (0.80.1-3.1) unstable; urgency=low * debian/patches/*.patch renamed to .diff, duh * debian/patches/99_trance.diff: transparent menus. -- Marcelo E. Magallon <[email protected]> Mon, 14 Oct 2002 22:13:10 +0200 wmaker (0.80.1-3) unstable; urgency=low * debian/patches/00_window_levels.diff: Patch from Jeff Teunissen to fix some invalid pointer dereferences. * debian/control: add John and Martin to the Uploaders field. * (XXX: UNTESTED) debian/patches: new patches from Marc-Christian Petersen 01_wm-windowlistmenu.patch: accepted upstream 02_wm-WINGs-fix.patch: simple WINGs patch 03_wm_autoscale.patch: decide automatically if a background has to be scaled or tiled. 05_wm_multiscreen.patch: fixes some xinerama(?) bugs -- Marcelo E. Magallon <[email protected]> Sun, 06 Oct 2002 11:33:48 +0200 wmaker (0.80.1-2) unstable; urgency=low * debian/WMWindowAttributes: correct path for WPrefs.tiff, thanks to Lionel Elie Mamane (closes: bug#106737) * Scanned sources for other instances of /Apps; got to double check this * src/misc.c: rework MakeCPPArgs() * src/misc.c: add DefaultConfigPath(), I'm trying to get WindowMaker to use GNUSTEP_USER_ROOT more uniformly. * Replaced DEF_CONFIG_PATH with DefaultConfigPath() all over the place (closes: bug#154030) -- Marcelo E. Magallon <[email protected]> Sat, 27 Jul 2002 12:17:23 +0200 wmaker (0.80.1-1) unstable; urgency=low * New upstream, yay! * debian/patches/*, remove * debian/rules: filter out zh_TW.Big5, msgfmt barfs on it. -- Marcelo E. Magallon <[email protected]> Thu, 4 Jul 2002 10:17:29 +0200 wmaker (0.80.0-5) unstable; urgency=low * Ewww... there's a big mess with libpng2/libpng3 it seems. * debian/control: Build depend on libpng2-dev. Make libwraster2-dev depend on libpng2-dev. * debian/rules: make get-wraster-flags *not* include things other than -lwraster. Let the linker figure out the dependencies. * Change shlib.deps for libwraster2 to this version to make sure that newly compiled packages get the proper library. -- Marcelo E. Magallon <[email protected]> Mon, 20 May 2002 20:24:56 +0200 wmaker (0.80.0-4) unstable; urgency=high * debian/patches/01_buffer_overflow.diff: buffer overflow patch from upstream (apply after next patch!) * debian/patches/00_0.80.0.diff: update, fixes several crashes * WINGs/wapplication.c: use GNUstep/System and Applications, too. (closes: bug#141840) * doc/wcopy.1x: change description a little, apparently .SH doesn't work with multiple commands and descriptions. (closes: bug#135085) * src/defaults.c: fix braino when updating a patch, it's GNUstep/Defaults, not GNUstep/Defaults/WindowMaker. Thanks Torbjørn Andersson (and sorry about the long delay) (closes: bug#129466, bug#127718) * debian/rules: rm -f src/wconfig.h when configuring wmaker, I'm not sure I understand why this is suddenly a problem. * debian/control: s/libpng2-dev/libpng-dev/, please send a message with RED BLINKING TEXT to d-d-a when you do something like this. There's a bunch of stuff that depends on libpng-dev and another bunch which depends on libpng2-dev. This is not nice for users. SCREW UP THE AUTOBUILDERS. * Ack NMU (closes: bug#141607, bug#129960) -- Marcelo E. Magallon <[email protected]> Sun, 14 Apr 2002 11:51:36 +0200 wmaker (0.80.0-3.1) unstable; urgency=low * Change GNUstep directory to /usr/lib/GNUstep/System (closes: #129960). -- Matthias Klose <[email protected]> Sun, 7 Apr 2002 12:00:10 +0200 wmaker (0.80.0-3) unstable; urgency=low * debian/copyright: Add LGPL note (closes: bug#131775) -- Marcelo E. Magallon <[email protected]> Sun, 3 Feb 2002 18:02:56 +0100 wmaker (0.80.0-2) unstable; urgency=low * debian/patches/00_0.80.0.diff: 0.80.0 to current CVS, fixes some crashing bugs. -- Marcelo E. Magallon <[email protected]> Sat, 2 Feb 2002 17:17:43 +0100 wmaker (0.80.0-1) unstable; urgency=low * Damn. * New upstream version. -- Marcelo E. Magallon <[email protected]> Sun, 23 Dec 2001 23:38:49 +0100 wmaker (0.70.0-2) unstable; urgency=low * debian/rules: add patch and unpatch targets * debian/patches: contains patches that I don't want on my CVS tree for whatever reason * debian/patches/00_0.70.1.diff: pulled out of CVS, fixes a number of bugs in wmaker. * debian/rules: include -I/usr/X11R6/include in get-*-flags --cflags * debian/rules: add /usr/X11R6/bin/wmaker -> /usr/bin/wmaker symlink to accommodate people who hardcode paths. This will be removed in woody+1. (closes: bug#114746) * Patch from Les Schaffer to get the GNOME pager working again (closes: bug#115177) -- Marcelo E. Magallon <[email protected]> Sat, 24 Nov 2001 22:15:40 +0100 wmaker (0.70.0-1) unstable; urgency=low * New upstream version * debian/control: doesn't depend on libproplist anymore -- Marcelo E. Magallon <[email protected]> Fri, 5 Oct 2001 08:52:51 +0200 wmaker (0.65.1-3) unstable; urgency=high * debian/rules: really fix what the previous entry says I fixed. -- Marcelo E. Magallon <[email protected]> Thu, 4 Oct 2001 14:36:33 +0200 wmaker (0.65.1-2) unstable; urgency=high * debian/rules: woops, removed too much information from the get-* scripts -- Marcelo E. Magallon <[email protected]> Sun, 19 Aug 2001 19:27:52 +0200 wmaker (0.65.1-1) unstable; urgency=high * New upstream version. -- Marcelo E. Magallon <[email protected]> Tue, 24 Jul 2001 11:43:42 +0200 wmaker (0.65.0-5) unstable; urgency=high * debian/wmaker.menu-method: quote menu section names (thanks William) (closes: bug#105484) * debian/control: added dependencies on foo-dev to libwraster-dev (closes: bug#105623) * util/wsetfont: remove bashisms, sent upstream (closes: bug#106228) * src/switchmenu.c: patch from upstream to fix buffer overflow -- Marcelo E. Magallon <[email protected]> Tue, 24 Jul 2001 08:19:47 +0200 wmaker (0.65.0-4) unstable; urgency=low * debian/rules: fix assignment of W?FLAGS variables. (closes: bug#103412) * Replace sigaction() on SIGPIPE with SIG_DFL to a dummy empty signal handler to avoid passing SIG_DFL on SIGPIPEs to children. (thanks Phil) (closes: bug#104016) -- Marcelo E. Magallon <[email protected]> Wed, 4 Jul 2001 09:54:43 +0200 wmaker (0.65.0-3) unstable; urgency=low * Use upstream's patch for bug#99311 * Kill window instance numbers. This feature drives all the Window Maker users I know up the wall. * src/wconfig.h.in: cheat regarding the dissapearing WorkSpace name. Window Maker is compiled with I18N, which makes LargeDisplayFont -*-*-medium-r-normal--24-*, which, with some combination of font pakcages, selects some non 8859-1 font, which means nothing is displayed. Changing this to -*-*-bold-r-normal--24-* makes the Xserver (?) pick something else. Someone with a clue regarding MB please help. -- Marcelo E. Magallon <[email protected]> Sat, 16 Jun 2001 20:29:16 +0200 wmaker (0.65.0-2) unstable; urgency=low * We have moved. Please visit us at our new location in /usr. * src/actions.c: fix fullscreen maximization (this way it makes sense to me, but I'm not 100% sure this is what the developers intended) (thanks Joey) (closes: bug#99311) -- Marcelo E. Magallon <[email protected]> Sat, 2 Jun 2001 22:26:18 +0200 wmaker (0.65.0-1) unstable; urgency=low * New upstream version (AYBABTU) * This version fixes the speckles on PowerPC (closes bug#79272) * debian/rules: added versioned dependency for libwraster2. * debian/rules: undo filtering out of zh_TW.Big5 in LINGUAS (thanks Anthony!) (sent new file upstream) * po/zh_CH.po: remove -80 from charset, per Anthony's suggestion. Sent upstream. * debian/rules: add hermes1-dev to Build-Depends. -- Marcelo E. Magallon <[email protected]> Fri, 11 May 2001 09:49:18 +0200 wmaker (0.64.0-6) unstable; urgency=low * debian/wmaker.menu-method: Fixed reference to menu's documentation (closes: bug#90585) * debian/control: s/xlib6g-dev/xlibs-dev/ * debian/control: remove superfluous suggests * debian/rules: %s/TMPDIR/DEBTMPDIR/g (/me hides) (thanks zarq) * debian/rules: filter-out zh_TW.Big5 in LINGUAS. Want it back? Figure out what's wrong with it. I really can't see the problem. -- Marcelo E. Magallon <[email protected]> Sun, 6 May 2001 15:33:01 +0200 wmaker (0.64.0-5) unstable; urgency=low * Woops, typo in code that moves man from X11R6 to share (thanks for noticing, Jordi) * debian/manpages/WindowMaker.1x: change to '.so man1/wmaker.1x' (thanks to joeyh) -- Marcelo E. Magallon <[email protected]> Mon, 12 Mar 2001 23:03:38 +0100 wmaker (0.64.0-4) unstable; urgency=low * WindowMaker/Defaults/Makefile.am: added a missing $(srddir) (sent upstream) (thanks Gordon Sadler) * debian/rules: got rid of that silly RPATHTOXBINDIR thing. * debian/rules: some clean up. * debian/manpages/: added manpages for WPrefs and upgrade-wmaker-defaults. * debian/rules: use dh_installman to install manpages -- Marcelo E. Magallon <[email protected]> Sat, 10 Mar 2001 09:09:08 +0100 wmaker (0.64.0-3) unstable; urgency=low * debian/wmaker.prerm: remove 'upgrade' from the cases where the x-window-manager alternative is removed. (closes: bug#87333) -- Marcelo E. Magallon <[email protected]> Mon, 12 Feb 2001 22:53:43 +0100 wmaker (0.64.0-2) unstable; urgency=low * redo fix from 0.63.1-4 (partially) -- Marcelo E. Magallon <[email protected]> Mon, 12 Feb 2001 22:53:43 +0100 wmaker (0.64.0-1) unstable; urgency=low * *sigh* I finally upload a fixed get-foo-flags and the next day a new upstream comes out. * oh, new upstream, btw. -- Marcelo E. Magallon <[email protected]> Sun, 11 Feb 2001 23:36:55 +0100 wmaker (0.63.1-4) unstable; urgency=low * debian/rules: *sigh* fix /usr/X11R6/include/WINGs. This might change depending on what upstream does in the next version. For now no other debian package should be changed because of this. -- Marcelo E. Magallon <[email protected]> Sat, 10 Feb 2001 01:13:49 +0100 wmaker (0.63.1-3) unstable; urgency=low * debian/rules: remove wmsetup * debian/manpages/wmaker.1x: update * debian/WindowMaker, WindowMaker/Defaults/WMGLOBAL: MultiByteText set to AUTO -- Marcelo E. Magallon <[email protected]> Sun, 21 Jan 2001 14:39:05 +0100 wmaker (0.63.1-2) unstable; urgency=low * Install /etc/GNUstep/Defaults/WMRootMenu (closes: bug#82195) -- Marcelo E. Magallon <[email protected]> Sun, 14 Jan 2001 19:19:16 +0100 wmaker (0.63.1-1) unstable; urgency=low * New upstream version. Weee! -- Marcelo E. Magallon <[email protected]> Sun, 7 Jan 2001 13:33:39 +0100 wmaker (0.63.0-1) unstable; urgency=low * New upstream version. * debian/control: added dependencies on libwraster-dev and libproplist-dev for libwings-dev (closes: bug#49277, bug#74530) * debian/rules: put get-*-flags where they belong (sorry, missed this one for a long time) (closes: bug#49357) * debian/README.Debian: remove reference to second faq (thanks Stephane Bortzmeyer) (closes: bug#59822) -- Marcelo E. Magallon <[email protected]> Sat, 6 Jan 2001 13:24:15 +0100 wmaker (0.62.1-3) unstable; urgency=low * Thanks to Matthew Ashton <[email protected]> for taking a look and providing most of the fixes in this release. (You guys at Stormix are cool, did I say that before?) * WindowMaker/background.menu: add to submenus: Tiled and Scaled (closes: bug#62302) * debian/control: Removed hard coded dependency on libproplist0 (wtf is that doing there?!?) * Bumped standards version to 3.3.1 and added Build-Depends. * debian/WMWindowAttributes: added entries for NTerm, NXTerm and KTerm. * WindowMaker/Defaults/WMState.in: s/xterm/x-terminal-emulator/ (closes: bug#59268) * fixed icon for WPrefs.app on the default desktop (closes: #67787) * Recompiled using libungif4 (thanks to Jeff "Deek" Teunissen <[email protected]> for pointing this out) * debian/WindowMaker.default: KbdModeLock=No (does this fix the empty box on the window titles bug?) -- Marcelo E. Magallon <[email protected]> Sun, 26 Nov 2000 13:35:51 +0100 wmaker (0.62.1-2) unstable; urgency=low * debian/Debian.jpg.uu cropped to have a 4/3 aspect ratio * src/misc.c: removed code that inserts -I<path to current file> in the preprocessor arguments, it's not required as that is what '#include "foo"' does (closes: bug#76317) * debian/manpages/wmaker.1x: removed Debian options, there aren't any of them now. (closes: bug#76260) * debian/wmaker.menu: Added Preferences to WindowManagers (wmaker) menu (closes: bug#61284) * debian/wmaker.docs: add FAQ.I18N -- Marcelo E. Magallon <[email protected]> Sat, 18 Nov 2000 09:49:06 +0100 wmaker (0.62.1-1) unstable; urgency=low * New maintainer. * src/wconfig.h.in: s/I18N_MB/I18N/g (closes: 58089) -- Marcelo E. Magallon <[email protected]> Sun, 12 Nov 2000 14:04:06 +0100 wmaker (0.62.1-0.1) unstable; urgency=low * NMU. * New upstream version. * src/moveres.c: removed misplaced patch (somehow trying to fix an aspect bug, a patch got merged into the code that draws the resizing lines in technical style, sorry Chris, my fault probably) * docklib removed upstream... uh? * debian/rules: removed docklib references * debian/control: removed libdockapp package. * debian/rules: s/??.po/*.po/ (don't ignore zh_CN.po and friends) * debian/rules: install README.definable-cursor * debian/rules: libwraster's version is now 2. * debian/control: s/libwraster1/libwraster2/ -- Marcelo E. Magallon <[email protected]> Sun, 16 Jul 2000 21:07:12 +0200 wmaker (0.61.1-4) frozen unstable; urgency=low * Added x-window-manager to Provides: line in control. -- Chris McKillop <[email protected]> Sun, 6 Feb 2000 21:15:36 -0500 wmaker (0.61.1-3) frozen; urgency=low * Added --enable-modelock for different X input methods. * Added calls to x-terminal-emulator instead of xterm in default settings. * Cleaned up the control file. - * -- Chris McKillop <[email protected]> Tue, 1 Feb 2000 00:42:12 -0500 wmaker (0.61.1-2) frozen; urgency=low * Merged wmaker-[plain,kde,gnome] into the wmaker package. o This new single binary supports all forms of hinting. * Added the Debian theme as the default setup for new users. * Added support for the x-window-manager convention. -- Chris McKillop <[email protected]> Sun, 16 Jan 2000 20:06:12 -0500 wmaker (0.61.1-1) unstable; urgency=low * New upstream release * Added linking to /usr/doc in all packages. -- Chris McKillop <[email protected]> Sun, 17 Oct 1999 17:46:58 -0500 wmaker (0.61.0-1) unstable; urgency=low * New upstream version. * Skipped, never uploaded. * New maintainer -- Chris McKillop <[email protected]> Mon, 20 Sep 1999 18:33:03 -0600 wmaker (0.60.0.19990831-3) unstable; urgency=low * debian/control: shortened short descriptions for wmaker, wmaker-plain, wmaker-gnome and wmaker-kde (closes: bug#45542) -- Marcelo E. Magallon <[email protected]> Mon, 20 Sep 1999 10:14:13 -0600 wmaker (0.60.0.19990831-2) unstable; urgency=low * debian/rules: /usr/share/doc, /usr/share/man -- Marcelo E. Magallon <[email protected]> Tue, 14 Sep 1999 10:12:57 -0600 wmaker (0.60.0.19990831-1) unstable; urgency=low * "new" upstream version. -- Marcelo E. Magallon <[email protected]> Mon, 13 Sep 1999 11:55:18 -0600 wmaker (0.60.0-5) unstable; urgency=low * debian/wmaker.menu: removed "Window Maker (debian)" entry. It's confusing. (closes: bug#37994) * wrlib/xpm.c::RGetImageFromXPMData: handles all the defined xpm color specification formats. (sent upstream) (closes: bug#35502) * Splitted wmaker into wmaker and wmaker-plain. wmaker depends on each of wmaker-{plain,gnome,kde}; each of them depends on wmaker (= ${Source-Version}). This ensures upgrades will be performed smoothly. * debian/wmaker-gnome.prerm: s/debian/gnome/ * debian/wmaker.postinst.tmpl: removes WindowMaker-debian alternative upon installation. * debian/wmaker.prerm: removed code to remove alternative. * debian/wmaker-{gnome,kde}.menu: removed. Those are confusing people. * debian/control: modified wmaker's description. (s/afterstep//gi) * debian/wmaker.menu: fixed sort keys for several entries * WindowMaker/wmmacros, debian/wmaker: uses $GNUSTEP_USER_ROOT instead of $HOME/GNUstep. (closes: bug#43578) -- Marcelo E. Magallon <[email protected]> Sat, 4 Sep 1999 09:36:32 -0600 wmaker (0.60.0-4) unstable; urgency=low * debian/wmaker.menu-method, debian/appearance.menu-method: updated to make it compatible with new menu package. (closes: bug#39836, bug#37994) -- Marcelo E. Magallon <[email protected]> Thu, 1 Jul 1999 21:59:46 -0600 wmaker (0.60.0-3) unstable; urgency=low * WINGs/WINGs.h: changed #include <WUtil.h> to #include "WUtil.h" before Roman sends black choppers this way :) (closes: bug#39852) -- Marcelo E. Magallon <[email protected]> Tue, 29 Jun 1999 10:09:57 -0600 wmaker (0.60.0-2) unstable; urgency=low * debina/rules::build-wmaker-debian-stamp: removes leftovers that shouldn't be in the tarball in the first place. Since I'm using a VPATH build, make in checking in $(builddir)/WindowMaker/Defaults for WMWindowAttributes, WindowMaker and WMState, and _also_ in $(srcdir)/WindowMaker/Defaults. Since it finds that the $(srcdir) versions are newer than their `.in' dependencies, it doesn't regenerate the files in $(builddir), which is _bad_ because WindowMaker/IconSets/Makefile.am searches for WMWindowAttributes in ../Defaults (or something equivalent to that). (closes: bug#38572) * debian/wmaker.menu: modified placement of Exit, Exit Session and Restart commands. Added Info Panel and Legal Panel. (closes: bug#37634) -- Marcelo E. Magallon <[email protected]> Sun, 13 Jun 1999 13:02:46 -0600 wmaker (0.60.0-1) unstable; urgency=low * New upstream release * Oops... this is going to be problematic. I stupidly `corrected' libwraster's libtool version on the last release. That produced libwraster2. But upstream didn't made this change. Now the libtool version has been correctly changed wrt 0.53.0, but my fix wasn't incorporated. That means libtool version is now 3:0:2, instead of 3:0:1. That produces libwraster1, not libwraster2. This is technically wrong, but I'll stick to upstream's version. Guy's gonna kill me... I submitted a bug asking for the removal of libwraster1 from the archive. Now I'll have to ask for the removal of libwraster2 and have libwraster1 reincorporated into the archive. * debian/control: went back to libwraster1. * debian/wmaker.menu-method: added SHORTCUT support. (Thanks blue!) * debian/README: updated to reflect SHORTCUT support. * debian/rules: yet another try at shlibs info. This time I have finally got this right. -- Marcelo E. Magallon <[email protected]> Thu, 3 Jun 1999 23:19:53 -0600 wmaker (0.53.0-3) unstable; urgency=low * src/misc.c: added -undef to cpp call. Undefines non-standard macros. (closes: bug#28595) -- Marcelo E. Magallon <[email protected]> Sat, 29 May 1999 12:13:07 -0600 wmaker (0.53.0-2) unstable; urgency=low * debian/rules: removed --enable-lite for KDE. Looking at the diffs in README.KDE between 0.52.0 and 0.53.0 it seems --enable-lite is not such a good idea afterall. * debian/wmaker.postinst.tml: try to cope with a dangling symlink in the alternatives. * debian/wmaker-{gnome,kde}.prerm: added. Reread packaging manual. Alternatives are removed on prerm, NOT postrm. (closes: bug#34526, bug#34286) * debian/wmaker-{gnome,kde}.postrm: removed. Ditto. * debian/README.Debian: updated. -- Marcelo E. Magallon <[email protected]> Sat, 24 Apr 1999 11:20:06 -0600 wmaker (0.53.0-1) unstable; urgency=low * New upstream version. -- Marcelo E. Magallon <[email protected]> Wed, 21 Apr 1999 21:46:25 -0600 wmaker (0.52.0-2) unstable; urgency=low * Ok. One more try at fixing the dependency problems. -- Marcelo E. Magallon <[email protected]> Sat, 10 Apr 1999 22:27:22 -0600 wmaker (0.52.0-1) unstable; urgency=low * New upstream version * debian/rules: changed dependency of libwraster to (>= 0.52.0) * debian/wmaker-gnome.menu: menu entries specific to wmaker-gnome. (thanks squirk!) (closes: bug#35148) * debian/wmaker-kde.menu: menu entries especific to wmaker-kde. * debian/wmaker.menu: added entry for "Debian" wmaker. * debian/WMWindowAttributes: added gnome stuff. (thanks Crow!) (closes: bug#34557) * debian/README.Debian: Updated. * debian/wmaker: no longer creates ~/GNUstep/.AppInfo, wmaker itself will create the directory if needed. * deban/wmakerpl.menu-method: new file, experimental. It works, but I'm not really sure what I should do with it. Right now it builds /etc/X11/WindowMaker/plmenu.hook, but nothing else uses it. I was thinking about changing WPrefs.app to use it for it's ``template'' file but I'm not convinced that's a good idea. * debian/rules: new target to create debian/shlibs.local -- I keep forgetting to edit the file. The version information is now located at the top of debian/rules. clean target removes debian/shlibs.local * Still pondering splitting wmaker into wmaker and wmaker-debian. wmaker-debian, wmaker-gnome and wmaker-kde would provide `wmaker-binary' (better name anyone?) and wmaker would depend on that. This would make wmaker ~ 220 kB smaller. * debian/rules::install-wmaker-debian-stamp: Speaking of smaller, nuked /usr/lib/GNUstep/Apps/WPrefs.app/xpm. WTH do I want that for if I have WPrefs.app/tiff _and_ tiff support is compiled in? * debian/rules::install-wmaker-debian-stamp: nuked .xpm counterparts of .tiff icons. There are _too_ many of them and it's pure bloat. -- Marcelo E. Magallon <[email protected]> Thu, 1 Apr 1999 18:13:25 -0600 wmaker (0.51.2-2) unstable; urgency=low * Finally fixed this annoying "can't build bug". Tested. Tested again. Tested yet one more time. (closes: bug#33409, bug#34523, bug#34583, bug#34657) -- Marcelo E. Magallon <[email protected]> Tue, 16 Mar 1999 09:48:29 -0600 wmaker (0.51.2-1) unstable; urgency=low * New upstream version -- Marcelo E. Magallon <[email protected]> Fri, 12 Mar 1999 21:12:55 -0600 wmaker (0.51.1.2pre2-2) unstable; urgency=low * Fixed location of global defaults... again. -- Marcelo E. Magallon <[email protected]> Thu, 11 Mar 1999 06:57:11 -0600 wmaker (0.51.1.2pre2-1) unstable; urgency=low * New upstream pre release version. -- Marcelo E. Magallon <[email protected]> Tue, 9 Mar 1999 10:16:53 -0600 wmaker (0.51.1-1) unstable; urgency=low * New upstream version. * New package, libwraster2. * debian/rules, debian/control, debian/shlibs: changed because of previous point. * debian/rules: wmkdemenu, installed in wmaker-kde. * Icons copyright situation cleared: wmaker is GPL. The libraries are LGPL. The icons are OPL. * wrlib/Makefile.am: changed version info to 2:0:0, interface is different! * debian/rules: README.GNOME installed in wmaker-gnome * debian/rules: README.KDE installed in wmaker-kde * debian/rules: wkdemenu.pl installed in wmaker-kde * src/*.c, WINGs/*.c, WPrefs/*.c: global defaults are installed in /etc/GNUstep/Defaults! `sysconfdir' is `/etc', `sysconfdir/GNUstep' and `sysconfdir/X11/WindowMaker' used where required. * Added libdockapp-dev package. + debian/control: added libdockapp-dev entry. + debian/rules: added libdockapp-dev targets -- Marcelo E. Magallon <[email protected]> Sun, 7 Mar 1999 12:49:25 -0600 wmaker (0.51.0-5) unstable; urgency=low * debian/rules: added a couple of comments regarding KANJI and DEBUG. * debian/rules: Redid dependencies between configure, aclocal.m4, ltconfig, Makefile.in and Makefile.am. Straightened out a lot of bogus dependencies between these files. I think I can say I got them right now, but there's still room for improvement. This should clear "I-can't-build-it-why-can-you?" type of bugs. -- Marcelo E. Magallon <[email protected]> Sat, 6 Mar 1999 14:24:11 -0600 wmaker (0.51.0-4) unstable; urgency=low * src/actions.c: patch by Matt Armstrong <[email protected]> (closes: bug#33976) -- Marcelo E. Magallon <[email protected]> Thu, 4 Mar 1999 12:10:32 -0600 wmaker (0.51.0-3) unstable; urgency=low * debian/control: added wmaker-gnome (hey! we are back in the "build takes long because there are a gazillion different versions" times!) (closes: bug#32905) * debian/control: added wmaker-kde. Wait! Don't jump on me just yet! If this can make your soul rest easier, think of wmaker-kde as a window manager that implements a funky communications protocol. * debian/rules: changed a lot of stuff to handle the new package in a sane way. * WindowMaker/Defaults/Makefile.am: removed dependency of some files on ./Makfile (what the heck is that for?) (sent upstream) * WindowMaker/IconSets/Makefile.am: ditto. -- Marcelo E. Magallon <[email protected]> Mon, 8 Feb 1999 15:26:37 -0600 wmaker (0.51.0-2) unstable; urgency=low * Added changes from 0.20.3-5. * debian/control: Changed recommendation for asclock to suggestion. * debian/control: removed dependency of libwmaker-dev on libwmaker. (closes: bug#32707) * src/misc.c: Added -traditional to cpp call in MakeCPPArgs. -- Marcelo E. Magallon <[email protected]> Sat, 6 Feb 1999 21:18:14 -0600 wmaker (0.51.0-1) unstable; urgency=low * New upstream version * Removed many patches, most are incorporated upstream. With some others it's obvious they won't be incorporated and it doesn't make sense to keep pushing them in the Debian diff's (they are mostly cosmetic things related to how things are built) * debian/rules: removes wrlib/get-wraster-flags on clean * debian/control: removed libwmaker0 package; only a static library is built now. * src/main.c: fixed message for unknown options; actually prints help if requested * doc/wmaker.1x: updated to reflect new option syntax. * debian/manpages/wmaker.1x: ditto. * doc/*: updated manpages. * debian/rules: After looking at what exactly does --enable-kanji do, it is obvious that the MB patch is not up to date with the rest of the code; this means I'm removing --enable-kanji from the configure options until someone fixes and TESTS it with iso-8859-1 characteres. I can't do it because I understand zip about the way MB works. I _think_ the problem is in the lenght of the string and/or the way it's encoded, but I'm problably wrong. * Fixed wmsetbg PixmapPath thing. Now 'wmsetbg Image' works. -- Marcelo E. Magallon <[email protected]> Sat, 30 Jan 1999 15:06:05 -0600 wmaker (0.50.2-0.0.4) unstable; urgency=low * Really fixed the '%a(blah)' bug -- Marcelo E. Magallon <[email protected]> Mon, 11 Jan 1999 18:11:52 -0600 wmaker (0.50.2-0.0.3) unstable; urgency=low * src/misc.c: fixed bug in '%a(title,prompt)' constructs * util/wmsetbg.c: added quoted arround image name * util/getstyle.c: added check for NULL values when querying PixmapPath. -- Marcelo E. Magallon <[email protected]> Mon, 11 Jan 1999 16:12:30 -0600 wmaker (0.50.2-0.0.2) unstable; urgency=low * Added '-traditional' again (fixes some reported bugs, don't have the number handy) * debian/wmaker.menu-method: added escapes for '*' (closes: bug#30622) * src/rootmenu.c: removed call to wsyserror if the directory specified my OPEN_MENU doesn't exist. * po/Makefile.am: removed double $(DESTDIR) in NLSPATH. I patched it, upstream patched it somewhere else... :-( Funny error dpkg gives with this: "corrupted tarball" or something like that. * WPrefs.app/po: ditto * debian/control: added 'Recommends: wmaker-usersguide' * debian/manpages/wmaker.1x: synced with upstream * Some fiddling with debian/rules -- Marcelo E. Magallon <[email protected]> Mon, 11 Jan 1999 10:31:25 -0600 wmaker (0.50.2-0.0.1) unstable; urgency=low * New upstream version * Installed missing readmes * Removed '-traditional' from cpp call -- Marcelo E. Magallon <[email protected]> Sun, 10 Jan 1999 20:31:12 -0600 wmaker (0.50.1-0.0.2) unstable; urgency=low * Added '-traditional' to cpp call. -- Marcelo E. Magallon <[email protected]> Sat, 9 Jan 1999 21:10:06 -0600 wmaker (0.50.1-0.0.1) unstable; urgency=low * New upstream version -- Marcelo E. Magallon <[email protected]> Sat, 9 Jan 1999 20:25:21 -0600 wmaker (0.50.0-0.0.1) unstable; urgency=low * Woa! Big version leap... no, I didn't skip any <g> * Just a note: in the previous version it's not 'SSH', it's 'SHM'. * Redid a lot of patches * debian/rules: remove code that removes extensions. Handled by Window Maker now. * debian/wmaker.menu: added '-noext' to some OPEN_MENU's -- Marcelo E. Magallon <[email protected]> Thu, 7 Jan 1999 15:57:16 -0600 wmaker (0.20.3-5) frozen; urgency=low * debian/wmaker.preinst: really fixed the diversion problem. After reading the reports, I think I figured out what's going on. A legacy diversion of asclock's manpage seems to be in place. The diverted version is there and the real file is also there (the real file comes from asclock). The approach taken: save the `good' file, remove the diversion, put the `good' file back in place. How do I know which one the good file is? Simple: asclock conflicts with wmaker << 0.15.0 and afterstep <= 1.4-6; wmaker >= 0.15.0 didn't provide any of the diverted files, so if there's a diversion and there's no original file, the diversion is the `good' file. If the diversion and the original file are there, the `good' file is the original file. (Thanks Adam Di Carlo, Michael Babcock, Czako Krisztian, Kevin Dalley and `slapic') (closes: bug#31419, bug#32649) * debian/README: minor modifications (mostly aesthetics) -- Marcelo E. Magallon <[email protected]> Thu, 4 Feb 1999 21:19:04 -0600 wmaker (0.20.3-4) frozen; urgency=low * debian/wmaker.preinst: how the heck did it work on the machines I tested this, I have no idea. Adam Di Carlo provided enough information regarding this bug and I was able to reproduce the scenario where it triggers. Thanks Adam! (closes: bug#31419) -- Marcelo E. Magallon <[email protected]> Mon, 25 Jan 1999 16:04:22 -0600 wmaker (0.20.3-3) frozen; urgency=low * debian/wmaker.preinst: Arrrggghhh! I forgot to move the fix for bug#31419 from 0.50.2-0.0.4 into 0.20.3-2!!! I had installed a fixed version of 0.50.2-0.0.4 on my development machine and, of course, the diversion wasn't there anymore, so when I installed 0.20.3-2 on the same machine I didn't notice the fix wasn't there... I need another slink machine!!! (Hmmm... there's a victim at the other end of the room) (closes: bug#31419) * debian/control: Changed 'Recommends: wmaker-usersguide' to 'Suggests: wmaker-userguide'. First, someone files a bug because there's no documentation, and now someone doesn't like the fact that there's documentation. I don't understand you people... * debian/wmaker.postrm: fixed horrendous bug in abort-upgrade. This has been there for ages... funny how people catch more bugs during deep freeze stages. (closes: bug#32320) -- Marcelo E. Magallon <[email protected]> Sun, 24 Jan 1999 08:55:52 -0600 wmaker (0.20.3-2) frozen; urgency=low * src/wconfig.h.in: Added '-traditional' to cpp (closes: bug#30665) * debian/control: added 'Recommends: wmaker-usersguide' (closes: bug#20483) * po/Makefile.am: fixed $(DESTDIR) (closes... no, the bug isn't on the BTS, it was mailed to me directly) * WPrefs.app/po/Makefile.am: ditto. * debian/wmaker.menu-method: added escapes for '*' (closes: bug#30622, bug#30624, bug#30637, bug#30679) * debian/wmaker.preinst: fixed old diversion removal (closes: bug#31419) * debian/control: bumped Standards-Version to 2.5.0 * debian/control: Recommends: asclock (closes: bug#31132) -- Marcelo E. Magallon <[email protected]> Sat, 16 Jan 1999 11:53:47 -0600 wmaker (0.20.3-1) frozen unstable; urgency=low * New upstream version. Incorporates all the upstream patches in 0.20.2-1, 0.20.2-2 and 0.20.2-3. (Makes the diff.gz *much* smaller) and fixes some more bugs. * Fixes problems with SSH (namely bug#29505) (closes: bug#29505) * Also fixes problems with SSH over networks (closes: bug#30026) * Upstream removed some ${SHELL} hacks. (closes: bug#29658, bug#30298) * Fixes "migrating xv windows" (closes: bug#30381) * WindowMaker/appearance.menu, WindowMaker/background.menu: copied from my local /etc/X11/WindowMaker/ files; those are the files are menu generates them which is a good thing in case some is not running menu. -- Marcelo E. Magallon <[email protected]> Thu, 10 Dec 1998 13:07:56 -0600 wmaker (0.20.3-0.0.1) frozen unstable; urgency=low * New upstream version. Incorporates all the upstream patches in 0.20.2-1, 0.20.2-2 and 0.20.2-3. (Makes the diff.gz *much* smaller) and fixes some more bugs. -- Marcelo E. Magallon <[email protected]> Thu, 3 Dec 1998 11:44:40 -0600 wmaker (0.20.2-3) frozen unstable; urgency=low * Applied more upstream patches: grayscale and 8bit jpeg support; fixed client restoration in restart/exit in multiheads; fixed problem with docked programs that have names with spaces; updated WPrefs.app for iconificationstyle; added -static command line option; put redundant NoWindowOverDock; fixed overlapping clip icon bug; extended window level code; added KeepOnBottom hint; added iconification style to WPrefs.app; fixed crash with bad value in defaults file; changed icon stacking code; added primitive support for 5 button mouse (for switching workspaces); fixed BadAccess and crash on programs that do XGrabButton; fixed bug with rootmenu Exec not working when stty is called from ~/.tcshrc; fixed bug with Move menu and sloppy focus; temporarily removed SHELL support in apps menu. * Someone pointed out that due to a patch applied in 0.20.2-2, Window Maker thinks its version is "0.20.3" instead of "0.20.2". Since there's no 0.20.3 upstream source yet, I guess we can live with that. -- Marcelo E. Magallon <[email protected]> Sat, 28 Nov 1998 10:42:02 -0600 wmaker (0.20.2-2) frozen unstable; urgency=low * Rebuilt with new X packages (release -7 specifically) * New X packages ship X locales with xlib6g (closes: bug#28967) * Applied upstream patches that fixes several bugs. Cut-and-paste from the updated changelog: fixed bug in miniaturizing atribute panel, fixed bug for 64bit machines, fixed bug for apps that put strings with "." in WM_CLASS, added handling for reparented client windows, fixed bug with window positioning (this one is bug#24770 I think -- I need confirmation from the submitter), fixed cascade window placement to account for dock, fixed bug in window positioning by clients, fixed problem with random window placement. * configure.in: reverted patch to --with-appspath. debian/rules: modified to reflect this (closes: bug#28620, bug#28627, bug#28632, bug#28865) * debian/rules: dockit is gone but manpage is still installed * debian/wmaker.postinst.tmpl: removed the code to add Window Maker to /etc/X11/window-managers and replaced with register-window-manager (the interface provided by the xbase package). This fixes #28841 partially (that's two bugs in one, this is the not-so-important part) * debian/wmaker.postrm: ditto for removal from /etc/X11/window-managers * On my system bug #26682 doesn't show up with this build and the new set of X pacakges. I'm not closing it because I've seen this come and go rather randomly. * Release 0.20.1-2 fixed bug #27411, I should have noted this on the changelog (I actually did but I never mentioned the bug number). It also fixed bug #27433. * WindowMaker/wmmacros: added macros for LOCAL_THEMES_DIR, LOCAL_STYLES_DIR, LOCAL_ICON_SETS_DIR, LOCAL_SOUND_SETS_DIR, LOCAL_BACKGROUNDS_DIR, USER_THEMES_DIR, USER_STYLES_DIR, USER_ICON_SETS_DIR, USER_SOUND_SETS_DIR, USER_BACKGROUNDS_DIR * WindowMaker/appearance.menu, WindowMaker/background.menu: added LOCAL_* paths and changed ~/GNUstep/... to USER_* (closes: bug#29473) * wrlib/Makefile.am: oops. Actually change shared version to 1:0:0... hmmm... no wonder this made so much trouble. * debian/rules: fixed call to dh_shlibdeps... wrong dependencies were computed! diff --git a/debian/compat b/debian/compat deleted file mode 100644 index f599e28..0000000 --- a/debian/compat +++ /dev/null @@ -1 +0,0 @@ -10 diff --git a/debian/control b/debian/control index 7b7647b..e86ebe8 100644 --- a/debian/control +++ b/debian/control @@ -1,196 +1,198 @@ Source: wmaker Section: x11 Priority: optional Maintainer: Debian Window Maker Team <[email protected]> Uploaders: Andreas Metzler <[email protected]>, Doug Torrance <[email protected]> -Standards-Version: 4.0.1 -Build-Depends: automake (>= 1:1.12), - debhelper (>= 10), +Rules-Requires-Root: no +Standards-Version: 4.5.0 +Build-Depends: debhelper-compat (= 12), gettext, libfontconfig1-dev, libgif-dev, libjpeg-dev, + libmagickwand-6.q16-dev, + libpango1.0-dev, libpng-dev, libsm-dev, libtiff-dev, libtool, libx11-dev, libxext-dev, libxft-dev, libxinerama-dev, libxkbfile-dev, libxmu-dev, libxpm-dev, libxrandr-dev, libxrender-dev, libxt-dev, sharutils -Homepage: http://windowmaker.org/ -Vcs-Browser: https://anonscm.debian.org/git/pkg-wmaker/wmaker.git -Vcs-Git: https://anonscm.debian.org/git/pkg-wmaker/wmaker.git +Homepage: https://www.windowmaker.org/ +Vcs-Browser: https://salsa.debian.org/wmaker-team/wmaker +Vcs-Git: https://salsa.debian.org/wmaker-team/wmaker.git Package: wmaker Architecture: any Multi-Arch: foreign Depends: wmaker-common (= ${source:Version}), ${misc:Depends}, ${shlibs:Depends} Provides: x-window-manager Suggests: desktop-base, wmaker-data, wmaker-utils, x-terminal-emulator, x11-apps, xterm Breaks: wmaker-common (<< 0.95.8-2~) Replaces: wmaker-common (<< 0.95.8-2~) Description: NeXTSTEP-like window manager for X Written by Alfredo Kojima almost from scratch, resembles the NeXTStep look very closely, and it is now an official GNU project. Window Maker (originally named WindowMaker) is not overloaded with features, and it is easier to configure than most other window managers. Its final goal is to produce a window manager that doesn't require editing of configuration files. Window Maker is fast and doesn't require tons of memory to run. Package: wmaker-common Architecture: all Multi-Arch: foreign Depends: ${misc:Depends} Suggests: wmaker Description: Window Maker - Architecture independent files Written by Alfredo Kojima almost from scratch, resembles the NeXTStep look very closely, and it is now an official GNU project. Window Maker (originally named WindowMaker) is not overloaded with features, and it is easier to configure than most other window managers. Its final goal is to produce a window manager that doesn't require editing of configuration files. Window Maker is fast and doesn't require tons of memory to run. . This package contains the architecture independent files. Package: wmaker-utils Architecture: any Multi-Arch: foreign Depends: ${misc:Depends}, ${shlibs:Depends} Breaks: wmaker (<< 0.95.7-6) Replaces: wmaker (<< 0.95.7-6) Description: Window Maker - Utilities Written by Alfredo Kojima almost from scratch, resembles the NeXTStep look very closely, and it is now an official GNU project. Window Maker (originally named WindowMaker) is not overloaded with features, and it is easier to configure than most other window managers. Its final goal is to produce a window manager that doesn't require editing of configuration files. Window Maker is fast and doesn't require tons of memory to run. . This package contains wxcopy and wxpaste, two utilities ordinarily shipped with Window Maker but not depending on it or any of its libraries. These utilities allow users to interact with cut buffers on the command line. Package: libwraster-dev Architecture: any Multi-Arch: same Section: libdevel Depends: libc6-dev, libgif-dev, libjpeg-dev, libpng-dev, libtiff5-dev, libwraster6 (= ${binary:Version}), libx11-dev, libxext-dev, libxpm-dev, ${misc:Depends} Breaks: libwraster3-dev Replaces: libwraster3-dev Description: Static libraries and headers of Window Maker rasterizer This library is used to manipulate images and convert them to a format that can be displayed through the X window system. Read the wraster.h header for an idea of what is available . Contains libwraster and header files, for manipulating and rasterizing images. Package: libwraster6 Architecture: any Multi-Arch: same Section: libs Depends: ${misc:Depends}, ${shlibs:Depends} Description: Shared libraries of Window Maker rasterizer This library is used to manipulate images and convert them to a format that can be displayed through the X window system. Read the wraster.h header for an idea of what is available Package: libwings-dev Architecture: any Multi-Arch: same Section: libdevel Depends: libc6-dev, libfontconfig1-dev, libwings3 (= ${binary:Version}), libwraster-dev, libwutil5 (= ${binary:Version}), libx11-dev, libxext-dev, libxft-dev, ${misc:Depends} Description: Window Maker's own widget set WINGs Is Not GNUstep (WINGs) is a small widget set with the NeXTSTEP look and feel. Its API is inspired in OpenSTEP and its implementation borrows some ideas from Tk. It has a reasonable set of widgets, sufficient for building small applications like a CDPlayer or hacking something like rxvt. It is used for basic widgets in the WindowMaker window manager. Package: libwutil5 Architecture: any Multi-Arch: same Section: libs Depends: ${misc:Depends}, ${shlibs:Depends}, wmaker-common (>= ${source:Version}) Description: Window Maker's own widget set - utility library WINGs Is Not GNUstep (WINGs) is a small widget set with the NeXTSTEP look and feel. Its API is inspired in OpenSTEP and its implementation borrows some ideas from Tk. It has a reasonable set of widgets, sufficient for building small applications like a CDPlayer or hacking something like rxvt. It is used for basic widgets in the WindowMaker window manager. . This package contains the libWUtils runtime library. Package: libwings3 Architecture: any Multi-Arch: same Section: libs Depends: ${misc:Depends}, ${shlibs:Depends}, wmaker-common (>= ${source:Version}) Description: Window Maker's own widget set - runtime library WINGs Is Not GNUstep (WINGs) is a small widget set with the NeXTSTEP look and feel. Its API is inspired in OpenSTEP and its implementation borrows some ideas from Tk. It has a reasonable set of widgets, sufficient for building small applications like a CDPlayer or hacking something like rxvt. It is used for basic widgets in the WindowMaker window manager. . This package contains the libWINGs runtime library. Package: libwmaker-dev Architecture: any Multi-Arch: same Section: libdevel Depends: libwmaker1 (= ${binary:Version}), libx11-dev, ${misc:Depends} Description: Static libraries and headers for Window Maker applications Window Maker is a NeXTSTEP-like window manager for X. . This package contains libWMaker and header files, for building Window Maker aware applications. Package: libwmaker1 Architecture: any Multi-Arch: same Section: libs Depends: ${misc:Depends}, ${shlibs:Depends} Description: Runtime library for Window Maker applications Window Maker is a NeXTSTEP-like window manager for X. . This package contains the libWMaker runtime library for Window Maker aware applications. diff --git a/debian/copyright b/debian/copyright index 09607dd..9a41e38 100644 --- a/debian/copyright +++ b/debian/copyright @@ -1,211 +1,211 @@ -Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ +Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/ Upstream-Name: wmaker Upstream-Contact: Window Maker developers mailing list <[email protected]> Source: http://repo.or.cz/w/wmaker-crm.git Files: * Copyright: 1991-1995 Free Software Foundation, Inc. 1995 Spencer Kimball 1995 Peter Mattis 1995 Sun Microsystems, Inc. 1996 Ben Wing 1997 Shige Abe 1997-2004, 2006 Alfredo Kengi Kojima <[email protected]> 1998-2004, 2006 Dan Pascu 1998 scottc 1998 James Thompson 1999-2000 Nwanua Elumeze 2001-2016 Window Maker Team 2008 Norayr Chilingaryan <[email protected]> 2008 Guido U. Draheim <[email protected]> 2010-2011 Carlos R. Mafra <[email protected]> 2010 Tamas Tevesz <[email protected]> 2011 Camille d'Alméras <[email protected]> 2012-2015 Christophe Curis 2012 Daniel Déchelotte 2012 Leandro Vital <[email protected]> License: GPL-2+ Files: m4/ax_pthread.m4 Copyright: 2008 Steven G. Johnson <[email protected]> 2011 Daniel Richard G. <[email protected]> License: GPL-3+ Files: m4/ld-version-script.m4 Copyright: 2008-2015 Free Software Foundation, Inc. License: FSFULLR Files: util/common.h wmlib/* wrlib/* Copyright: 1997-2003 Alfredo Kengi Kojima <[email protected]> 1998-2004 Dan Pascu 2011 Carlos R. Mafra <[email protected]> License: LGPL-2+ Files: WindowMaker/Icons/BitchX.tiff WindowMaker/Icons/defaultAppIcon.tiff WindowMaker/Icons/GNUterm.tiff WindowMaker/Icons/defaultterm.tiff WindowMaker/Icons/draw.tiff WindowMaker/Icons/linuxterm.tiff WindowMaker/Icons/mixer.tiff WindowMaker/Icons/notepad.tiff WindowMaker/Icons/pdf.tiff WindowMaker/Icons/ps.tiff WindowMaker/Icons/real.tiff WindowMaker/Icons/sgiterm.tiff WindowMaker/Icons/staroffice2.tiff WindowMaker/Icons/timer.tiff WindowMaker/Icons/wilber.tiff WindowMaker/Icons/write.tiff WindowMaker/Icons/xdvi.tiff WindowMaker/Icons/xv.tiff Copyright: 1997, Marco van Hylckama Vlieg <[email protected]> License: attribution They may be distributed freely and/or modified as long as the original Author is mentioned! Files: WindowMaker/Icons/GNUstepGlow.tiff WindowMaker/Icons/GNUstepGlow.xpm WindowMaker/Icons/Magnify.tiff WindowMaker/Icons/Magnify.xpm WindowMaker/Icons/Terminal.tiff WindowMaker/Icons/Terminal.xpm WindowMaker/Icons/TerminalGNUstep.tiff WindowMaker/Icons/TerminalGNUstep.xpm WindowMaker/Icons/TerminalLinux.tiff WindowMaker/Icons/TerminalLinux.xpm WindowMaker/Icons/Ear.png WindowMaker/Icons/Ftp.png WindowMaker/Icons/ICQ.png WindowMaker/Icons/Jabber.png WindowMaker/Icons/Mozilla.png WindowMaker/Icons/Pen.png WindowMaker/Icons/Pencil.png WindowMaker/Icons/Shell.png WindowMaker/Icons/Speaker.png WindowMaker/Icons/XChat.png WPrefs.app/tiff/msty1.tiff WPrefs.app/tiff/msty2.tiff WPrefs.app/tiff/msty3.tiff WPrefs.app/xpm/msty1.xpm WPrefs.app/xpm/msty2.xpm WPrefs.app/xpm/msty3.xpm WPrefs.app/WPrefs.tiff WPrefs.app/WPrefs.xpm WPrefs.app/tiff/tdel.tiff WPrefs.app/tiff/tedit.tiff WPrefs.app/tiff/textr.tiff WPrefs.app/tiff/tnew.tiff WPrefs.app/xpm/tdel.xpm WPrefs.app/xpm/tedit.xpm WPrefs.app/xpm/textr.xpm WPrefs.app/xpm/tnew.xpm WINGs/Resources/defaultIcon.tiff WINGs/Resources/Images.tiff WINGs/Resources/Images.xpm WINGs/Resources/defaultIcon.xpm WINGs/Resources/Images.xcf Copyright: 2000, Banlu Kemiyatorn License: WTFPL-1 Files: debian/* Copyright: 1997, Neil A. Rubin <[email protected]> 1997, Marcelo E. Magallon <[email protected]> 2011, Rodolfo García Peñas (kix) <[email protected]> License: GPL-2+ Files: debian/debianfiles/Themes/DebianLegacy.style debian/debianfiles/Themes/DebianLegacy.txt debian/debianfiles/Themes/DebianSwirl.jpg Copyright: 1999 Gary Burke <[email protected]> License: GPL-1+ Files: WINGs/string.c Copyright: 1998 Todd C. Miller <[email protected]> License: Expat Files: wrlib/load_ppm.c Copyright: 1988 Jef Poskanzer 1997-2003 Alfredo K. Kojima 2014 Window Maker Team License: HPND and LGPL-2+ License: Expat Permission to use, copy, modify, and distribute this software for any purpose with or without fee is hereby granted, provided that the above copyright notice and this permission notice appear in all copies. . THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. License: FSFULLR This file is free software; the Free Software Foundation gives unlimited permission to copy and/or distribute it, with or without modifications, as long as this notice is preserved. License: GPL-1+ This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 1, or (at your option) any later version. . On Debian systems, the complete text of version 1 of the GNU General Public License can be found in `/usr/share/common-licenses/GPL-1'. License: GPL-2+ This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. . This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. . You should have received a copy of the GNU General Public License along with this package; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA . On Debian systems, the full text of the GNU General Public License version 2 can be found in the file `/usr/share/common-licenses/GPL-2'. License: GPL-3+ This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. . This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. . You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. . On Debian systems, the full text of the GNU General Public License version 3 can be found in the file `/usr/share/common-licenses/GPL-3'. License: HPND Permission to use, copy, modify, and distribute this software and its documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appear in all copies and that both that copyright notice and this permission notice appear in supporting documentation. This software is provided "as is" without express or implied warranty. License: LGPL-2+ This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. . This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. . You should have received a copy of the GNU Library General Public License along with this library; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA . On Debian systems, the full text of the GNU Library General Public License version 2 can be found in the file `/usr/share/common-licenses/LGPL-2'. License: WTFPL-1 do What The Fuck you want to Public License . Version 1.0, March 2000 Copyright (C) 2000 Banlu Kemiyatorn (]d). 136 Nives 7 Jangwattana 14 Laksi Bangkok Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. . Ok, the purpose of this license is simple and you just . DO WHAT THE FUCK YOU WANT TO. diff --git a/debian/debianfiles/conf/WMWindowAttributes b/debian/debianfiles/conf/WMWindowAttributes index f1388c1..78d2f75 100644 --- a/debian/debianfiles/conf/WMWindowAttributes +++ b/debian/debianfiles/conf/WMWindowAttributes @@ -1,56 +1,56 @@ { Logo.WMDock = {Icon = GNUstep.tiff;}; Logo.WMPanel = {Icon = GNUstep.tiff;}; Tile.WMClip = {Icon = clip.tiff;}; - WPrefs = {Icon = "/usr/share/lib/GNUstep/System/Applications/WPrefs.app/WPrefs.tiff";}; + WPrefs = {Icon = "/usr/share/GNUstep/System/Applications/WPrefs.app/WPrefs.tiff";}; Dockit = {Icon = GNUstep.tiff;}; WMSoundServer = {Icon = Sound.tiff;}; "*" = {Icon = defaultAppIcon.tiff;}; Rxvt = {Icon = GNUterm.tiff;}; KTerm = {Icon = GNUterm.tiff;}; NXTerm = {Icon = GNUterm.tiff;}; XTerm = {Icon = GNUterm.tiff;}; Netscape = {Icon = "wmaker-netscape.tif";}; "Mozilla-bin" = {Icon = "wmaker-nav.tif";}; emacs = {Icon = "wmaker-emacs.tif";}; Gimp = {AlwaysUserIcon = Yes;Icon = "wmaker-gimp2.tif";}; toolbox.Gimp = {NoAppIcon = Yes;Icon = "wmaker-gimp2.tif";}; gimp_startup.Gimp = { Icon = "wmaker-gimp2.tif"; AlwaysUserIcon = Yes; NoTitlebar = Yes; NoResizebar = Yes; NotClosable = Yes; NotMiniaturizable = Yes; }; tip_of_the_day.Gimp = { Icon = "wmaker-gimp2.tif"; AlwaysUserIcon = Yes; NoResizebar = Yes; NoCloseButton = Yes; NoMiniaturizeButton = Yes; KeepOnTop = Yes; }; image_window.Gimp = {Icon = "wmaker-gimp-work.tif";AlwaysUserIcon = Yes;}; brushselection.Gimp = {Icon = "wmaker-gimp-brushes.tif";AlwaysUserIcon = Yes;}; patternselection.Gimp = {Icon = "wmaker-gimp-patterns.tif";AlwaysUserIcon = Yes;}; color_palette.Gimp = { Icon = "wmaker-gimp-palette.tif"; AlwaysUserIcon = Yes; NoResizebar = Yes; }; gradient_editor.Gimp = {Icon = "wmaker-gimp-gradient.tif";AlwaysUserIcon = Yes;}; tool_options.Gimp = {Icon = "wmaker-gimp-tooloption.tif";AlwaysUserIcon = Yes;}; layers_and_channels.Gimp = {Icon = "wmaker-gimp-layers.tif";AlwaysUserIcon = Yes;}; indexed_color_palette.Gimp = { Icon = "wmaker-gimp-palette.tif"; AlwaysUserIcon = Yes; NoResizebar = Yes; }; "Script-fu" = {Icon = "wmaker-gimp-script-fu.tif";}; "script-fu.Script-fu" = {Icon = "wmaker-gimp-script-fu.tif";}; preferences.Gimp = {Icon = "wmaker-gimp-prefs.tif";AlwaysUserIcon = Yes;}; panel = {NoAppIcon = Yes;}; gmc = {NoAppIcon = Yes;Omnipresent = Yes;SkipWindowList = Yes;}; Logo.WMClip = {Icon = clip.tiff;}; } diff --git a/debian/libwings3.symbols b/debian/libwings3.symbols index 44ced64..9b705f2 100644 --- a/debian/libwings3.symbols +++ b/debian/libwings3.symbols @@ -1,600 +1,604 @@ libWINGs.so.3 libwings3 #MINVER# +* Build-Depends-Package: libwings-dev WINGsConfiguration@Base 0.95.0 WMAddBoxSubview@Base 0.95.0 WMAddBoxSubviewAtEnd@Base 0.95.0 WMAddBrowserColumn@Base 0.95.0 WMAddItemInTabView@Base 0.95.0 WMAddPopUpButtonItem@Base 0.95.0 WMAddSplitViewSubview@Base 0.95.0 WMAddTabViewItemWithView@Base 0.95.0 WMAdjustSplitViewSubviews@Base 0.95.0 WMAppendTextBlock@Base 0.95.0 WMAppendTextStream@Base 0.95.0 WMBlackColor@Base 0.95.0 WMBlueComponentOfColor@Base 0.95.0 WMBoldSystemFontOfSize@Base 0.95.0 WMBreakModalLoop@Base 0.95.0 WMBrowserAllowsEmptySelection@Base 0.95.0 WMBrowserAllowsMultipleSelection@Base 0.95.0 WMChangePanelOwner@Base 0.95.0 WMClearList@Base 0.95.0 WMCloseColorPanel@Base 0.95.0 WMCloseWindow@Base 0.95.0 WMColorGC@Base 0.95.0 WMColorPanelColorChangedNotification@Base 0.95.0 WMColorPixel@Base 0.95.0 WMColorWellDidChangeNotification@Base 0.95.0 WMCopyFontWithStyle@Base 0.95.0 WMCreateAlertPanel@Base 0.95.0 WMCreateApplicationIconBlendedPixmap@Base 0.95.0 WMCreateBlendedPixmapFromFile@Base 0.95.0 WMCreateBlendedPixmapFromRImage@Base 0.95.0 WMCreateBox@Base 0.95.0 WMCreateBrowser@Base 0.95.0 WMCreateButton@Base 0.95.0 WMCreateColorWell@Base 0.95.0 WMCreateCustomButton@Base 0.95.0 WMCreateDragHandler@Base 0.95.0 WMCreateDragOperationArray@Base 0.95.0 WMCreateDragOperationItem@Base 0.95.0 WMCreateEventHandler@Base 0.95.0 WMCreateFont@Base 0.95.0 WMCreateFrame@Base 0.95.0 WMCreateGenericPanel@Base 0.95.0 WMCreateInputPanel@Base 0.95.0 WMCreateLabel@Base 0.95.0 WMCreateList@Base 0.95.0 WMCreateMenuItem@Base 0.95.0 WMCreateNamedColor@Base 0.95.0 WMCreatePanelForWindow@Base 0.95.0 WMCreatePanelWithStyleForWindow@Base 0.95.0 WMCreatePixmap@Base 0.95.0 WMCreatePixmapFromFile@Base 0.95.0 WMCreatePixmapFromRImage@Base 0.95.0 WMCreatePixmapFromXPMData@Base 0.95.0 WMCreatePixmapFromXPixmaps@Base 0.95.0 WMCreatePopUpButton@Base 0.95.0 WMCreateProgressIndicator@Base 0.95.0 WMCreateRGBAColor@Base 0.95.0 WMCreateRGBColor@Base 0.95.0 WMCreateRuler@Base 0.95.0 + WMCreateScaledAlertPanel@Base 0.95.9 WMCreateScaledBlendedPixmapFromFile@Base 0.95.6 + WMCreateScaledInputPanel@Base 0.95.9 WMCreateScreen@Base 0.95.0 WMCreateScreenWithRContext@Base 0.95.0 WMCreateScrollView@Base 0.95.0 WMCreateScroller@Base 0.95.0 WMCreateSelectionHandler@Base 0.95.0 WMCreateSimpleApplicationScreen@Base 0.95.0 WMCreateSlider@Base 0.95.0 WMCreateSplitView@Base 0.95.0 WMCreateTabView@Base 0.95.0 WMCreateTabViewItem@Base 0.95.0 WMCreateTabViewItemWithIdentifier@Base 0.95.0 WMCreateTextBlockWithObject@Base 0.95.0 WMCreateTextBlockWithPixmap@Base 0.95.0 WMCreateTextBlockWithText@Base 0.95.0 WMCreateTextField@Base 0.95.0 WMCreateTextForDocumentType@Base 0.95.0 WMCreateWindow@Base 0.95.0 WMCreateWindowWithStyle@Base 0.95.0 WMDarkGrayColor@Base 0.95.0 WMDefaultBoldSystemFont@Base 0.95.0 WMDefaultSystemFont@Base 0.95.0 WMDeleteDragHandler@Base 0.95.0 WMDeleteEventHandler@Base 0.95.0 WMDeleteSelectionHandler@Base 0.95.0 WMDeleteTextFieldRange@Base 0.95.0 WMDestroyAlertPanel@Base 0.95.0 WMDestroyGenericPanel@Base 0.95.0 WMDestroyInputPanel@Base 0.95.0 WMDestroyMenuItem@Base 0.95.0 WMDestroyTabViewItem@Base 0.95.0 WMDestroyTextBlock@Base 0.95.0 WMDestroyWidget@Base 0.95.0 WMDragImageFromView@Base 0.95.0 WMDrawImageString@Base 0.95.0 WMDrawPixmap@Base 0.95.0 WMDrawString@Base 0.95.0 WMFindInTextStream@Base 0.95.0 WMFindRowOfListItemWithTitle@Base 0.95.0 WMFontHeight@Base 0.95.0 WMFontPanelFontChangedNotification@Base 0.95.0 WMFreeColorPanel@Base 0.95.0 WMFreeFilePanel@Base 0.95.0 WMFreeFontPanel@Base 0.95.0 WMFreezeText@Base 0.95.0 WMGetApplicationIconImage@Base 0.95.0 WMGetApplicationIconPixmap@Base 0.95.0 WMGetBrowserFirstVisibleColumn@Base 0.95.0 WMGetBrowserListInColumn@Base 0.95.0 WMGetBrowserMaxVisibleColumns@Base 0.95.0 WMGetBrowserNumberOfColumns@Base 0.95.0 WMGetBrowserPath@Base 0.95.0 WMGetBrowserPathToColumn@Base 0.95.0 WMGetBrowserPaths@Base 0.95.0 WMGetBrowserSelectedColumn@Base 0.95.0 WMGetBrowserSelectedItemInColumn@Base 0.95.0 WMGetBrowserSelectedRowInColumn@Base 0.95.0 WMGetButtonEnabled@Base 0.95.0 WMGetButtonSelected@Base 0.95.0 WMGetButtonText@Base 0.95.7 WMGetColorAlpha@Base 0.95.0 WMGetColorPanel@Base 0.95.0 WMGetColorPanelColor@Base 0.95.0 WMGetColorRGBDescription@Base 0.95.0 WMGetColorWellColor@Base 0.95.0 WMGetDragOperationItemText@Base 0.95.0 WMGetDragOperationItemType@Base 0.95.0 WMGetFilePanelAccessoryView@Base 0.95.0 WMGetFilePanelFileName@Base 0.95.0 WMGetFontName@Base 0.95.0 WMGetFontPanel@Base 0.95.0 WMGetFontPanelFont@Base 0.95.0 WMGetGrabbedRulerMargin@Base 0.95.0 WMGetHangedData@Base 0.95.0 WMGetLabelFont@Base 0.95.0 WMGetLabelImage@Base 0.95.0 WMGetLabelText@Base 0.95.0 WMGetListItem@Base 0.95.0 WMGetListItemHeight@Base 0.95.0 WMGetListItems@Base 0.95.0 WMGetListNumberOfRows@Base 0.95.0 WMGetListPosition@Base 0.95.0 WMGetListSelectedItem@Base 0.95.0 WMGetListSelectedItemRow@Base 0.95.0 WMGetListSelectedItems@Base 0.95.0 WMGetMenuItemAction@Base 0.95.0 WMGetMenuItemData@Base 0.95.0 WMGetMenuItemEnabled@Base 0.95.0 WMGetMenuItemMixedStatePixmap@Base 0.95.0 WMGetMenuItemOffStatePixmap@Base 0.95.0 WMGetMenuItemOnStatePixmap@Base 0.95.0 WMGetMenuItemPixmap@Base 0.95.0 WMGetMenuItemRepresentedObject@Base 0.95.0 WMGetMenuItemShortcut@Base 0.95.0 WMGetMenuItemShortcutModifierMask@Base 0.95.0 WMGetMenuItemState@Base 0.95.0 WMGetMenuItemTitle@Base 0.95.0 WMGetOpenPanel@Base 0.95.0 WMGetPixmapMaskXID@Base 0.95.0 WMGetPixmapSize@Base 0.95.0 WMGetPixmapXID@Base 0.95.0 WMGetPopUpButtonEnabled@Base 0.95.0 WMGetPopUpButtonItem@Base 0.95.0 WMGetPopUpButtonItemEnabled@Base 0.95.0 WMGetPopUpButtonMenuItem@Base 0.95.0 WMGetPopUpButtonNumberOfItems@Base 0.95.0 WMGetPopUpButtonSelectedItem@Base 0.95.0 WMGetProgressIndicatorMaxValue@Base 0.95.0 WMGetProgressIndicatorMinValue@Base 0.95.0 WMGetProgressIndicatorValue@Base 0.95.0 WMGetRColorFromColor@Base 0.95.0 WMGetReleasedRulerMargin@Base 0.95.0 WMGetRulerMargins@Base 0.95.0 WMGetRulerOffset@Base 0.95.0 WMGetSavePanel@Base 0.95.0 + WMGetScaleBaseFromSystemFont@Base 0.95.9 WMGetScrollViewHorizontalScroller@Base 0.95.0 WMGetScrollViewVerticalScroller@Base 0.95.0 WMGetScrollViewVisibleRect@Base 0.95.0 WMGetScrollerHitPart@Base 0.95.0 WMGetScrollerKnobProportion@Base 0.95.0 WMGetScrollerValue@Base 0.95.0 WMGetSelectedTabViewItem@Base 0.95.0 WMGetSeparatorMenuItem@Base 0.95.0 WMGetSliderMaxValue@Base 0.95.0 WMGetSliderMinValue@Base 0.95.0 WMGetSliderValue@Base 0.95.0 WMGetSplitViewDividerThickness@Base 0.95.0 WMGetSplitViewSubviewAt@Base 0.95.0 WMGetSplitViewSubviewsCount@Base 0.95.0 WMGetSplitViewVertical@Base 0.95.0 WMGetSystemPixmap@Base 0.95.0 WMGetTabViewItemIdentifier@Base 0.95.0 WMGetTabViewItemLabel@Base 0.95.0 WMGetTabViewItemView@Base 0.95.0 WMGetTextBlockProperties@Base 0.95.0 WMGetTextDefaultColor@Base 0.95.0 WMGetTextDefaultFont@Base 0.95.0 WMGetTextEditable@Base 0.95.0 WMGetTextFieldCursorPosition@Base 0.95.0 WMGetTextFieldDelegate@Base 0.95.0 WMGetTextFieldEditable@Base 0.95.0 WMGetTextFieldFont@Base 0.95.0 WMGetTextFieldText@Base 0.95.0 WMGetTextIgnoresNewline@Base 0.95.0 WMGetTextInsertType@Base 0.95.0 WMGetTextObjects@Base 0.95.0 WMGetTextRulerShown@Base 0.95.0 WMGetTextSelectedObjects@Base 0.95.0 WMGetTextSelectedStream@Base 0.95.0 WMGetTextSelectionColor@Base 0.95.0 WMGetTextSelectionFont@Base 0.95.0 WMGetTextSelectionUnderlined@Base 0.95.0 WMGetTextStream@Base 0.95.0 WMGetTextUsesMonoFont@Base 0.95.0 WMGetViewPosition@Base 0.95.0 WMGetViewScreenPosition@Base 0.95.0 WMGetViewSize@Base 0.95.0 WMGetWidgetBackgroundColor@Base 0.95.0 WMGetWidgetBackgroundPixmap@Base 0.95.7 WMGrayColor@Base 0.95.0 WMGreenComponentOfColor@Base 0.95.0 WMGroupButtons@Base 0.95.0 WMHandleEvent@Base 0.95.0 WMHangData@Base 0.95.0 WMHideFontPanel@Base 0.95.0 WMHookEventHandler@Base 0.95.0 WMInsertBrowserItem@Base 0.95.0 WMInsertItemInTabView@Base 0.95.0 WMInsertListItem@Base 0.95.0 WMInsertPopUpButtonItem@Base 0.95.0 WMInsertTextFieldText@Base 0.95.0 WMIsAntialiasingEnabled@Base 0.95.0 WMIsDoubleClick@Base 0.95.0 WMIsDraggingFromView@Base 0.95.0 WMIsMarginEqualToMargin@Base 0.95.0 WMListAllowsEmptySelection@Base 0.95.0 WMListAllowsMultipleSelection@Base 0.95.0 WMListDidScrollNotification@Base 0.95.0 WMListSelectionDidChangeNotification@Base 0.95.0 WMLoadBrowserColumnZero@Base 0.95.0 WMLowerWidget@Base 0.95.0 WMMapSubwidgets@Base 0.95.0 WMMapWidget@Base 0.95.0 WMMaskEvent@Base 0.95.0 WMMenuItemIsSeparator@Base 0.95.0 WMMoveWidget@Base 0.95.0 WMNextEvent@Base 0.95.0 WMOpenScreen@Base 0.95.0 WMPageText@Base 0.95.0 WMPaintColorSwatch@Base 0.95.0 WMPerformButtonClick@Base 0.95.0 WMPrependTextBlock@Base 0.95.0 WMPrependTextStream@Base 0.95.0 WMRaiseWidget@Base 0.95.0 WMRealizeWidget@Base 0.95.0 WMRedComponentOfColor@Base 0.95.0 WMRedisplayWidget@Base 0.95.0 WMRegisterViewForDraggedTypes@Base 0.95.0 WMRelayToNextResponder@Base 0.95.0 WMReleaseColor@Base 0.95.0 WMReleaseFont@Base 0.95.0 WMReleasePixmap@Base 0.95.0 WMReleaseViewDragImage@Base 0.95.0 WMRemoveBoxSubview@Base 0.95.0 WMRemoveBrowserItem@Base 0.95.0 WMRemoveListItem@Base 0.95.0 WMRemovePopUpButtonItem@Base 0.95.0 WMRemoveSplitViewSubview@Base 0.95.0 WMRemoveSplitViewSubviewAt@Base 0.95.0 WMRemoveTabViewItem@Base 0.95.0 WMRemoveTextBlock@Base 0.95.0 WMReparentWidget@Base 0.95.0 WMReplaceTextSelection@Base 0.95.0 WMRequestSelection@Base 0.95.0 WMResizeScrollViewContent@Base 0.95.0 WMResizeWidget@Base 0.95.0 WMRetainColor@Base 0.95.0 WMRetainFont@Base 0.95.0 WMRetainPixmap@Base 0.95.0 WMRunAlertPanel@Base 0.95.0 WMRunInputPanel@Base 0.95.0 WMRunModalFilePanelForDirectory@Base 0.95.0 WMRunModalLoop@Base 0.95.0 WMScreenDepth@Base 0.95.0 WMScreenDisplay@Base 0.95.0 WMScreenHeight@Base 0.95.0 WMScreenMainLoop@Base 0.95.0 WMScreenPending@Base 0.95.0 WMScreenRContext@Base 0.95.0 WMScreenWidth@Base 0.95.0 WMScrollText@Base 0.95.0 WMScrollViewScrollPoint@Base 0.95.0 WMScrollerDidScrollNotification@Base 0.95.0 WMSelectAllListItems@Base 0.95.0 WMSelectFirstTabViewItem@Base 0.95.0 WMSelectLastTabViewItem@Base 0.95.0 WMSelectListItem@Base 0.95.0 WMSelectListItemsInRange@Base 0.95.0 WMSelectNextTabViewItem@Base 0.95.0 WMSelectPreviousTabViewItem@Base 0.95.0 WMSelectTabViewItem@Base 0.95.0 WMSelectTabViewItemAtIndex@Base 0.95.0 WMSelectTextFieldRange@Base 0.95.0 WMSelectionOwnerDidChangeNotification@Base 0.95.0 WMSetApplicationHasAppIcon@Base 0.95.0 WMSetApplicationIconImage@Base 0.95.0 WMSetApplicationIconPixmap@Base 0.95.0 WMSetApplicationIconWindow@Base 0.95.0 WMSetBalloonDelay@Base 0.95.0 WMSetBalloonEnabled@Base 0.95.0 WMSetBalloonFont@Base 0.95.0 WMSetBalloonTextAlignment@Base 0.95.0 WMSetBalloonTextColor@Base 0.95.0 WMSetBalloonTextForView@Base 0.95.0 WMSetBoxBorderWidth@Base 0.95.0 WMSetBoxHorizontal@Base 0.95.0 WMSetBrowserAction@Base 0.95.0 WMSetBrowserAllowEmptySelection@Base 0.95.0 WMSetBrowserAllowMultipleSelection@Base 0.95.0 WMSetBrowserColumnTitle@Base 0.95.0 WMSetBrowserDelegate@Base 0.95.0 WMSetBrowserDoubleAction@Base 0.95.0 WMSetBrowserHasScroller@Base 0.95.0 WMSetBrowserMaxVisibleColumns@Base 0.95.0 WMSetBrowserPath@Base 0.95.0 WMSetBrowserPathSeparator@Base 0.95.0 WMSetBrowserTitled@Base 0.95.0 WMSetButtonAction@Base 0.95.0 WMSetButtonAltImage@Base 0.95.0 WMSetButtonAltText@Base 0.95.0 WMSetButtonAltTextColor@Base 0.95.0 WMSetButtonBordered@Base 0.95.0 WMSetButtonContinuous@Base 0.95.0 WMSetButtonDisabledTextColor@Base 0.95.0 WMSetButtonEnabled@Base 0.95.0 WMSetButtonFont@Base 0.95.0 WMSetButtonImage@Base 0.95.0 WMSetButtonImageDefault@Base 0.95.0 WMSetButtonImageDimsWhenDisabled@Base 0.95.0 WMSetButtonImagePosition@Base 0.95.0 WMSetButtonPeriodicDelay@Base 0.95.0 WMSetButtonSelected@Base 0.95.0 WMSetButtonTag@Base 0.95.0 WMSetButtonText@Base 0.95.0 WMSetButtonTextAlignment@Base 0.95.0 WMSetButtonTextColor@Base 0.95.0 WMSetColorAlpha@Base 0.95.0 WMSetColorInGC@Base 0.95.0 WMSetColorPanelAction@Base 0.95.0 WMSetColorPanelColor@Base 0.95.0 WMSetColorPanelPickerMode@Base 0.95.0 WMSetColorWellColor@Base 0.95.0 WMSetFilePanelAccessoryView@Base 0.95.0 WMSetFilePanelAutoCompletion@Base 0.95.0 WMSetFilePanelCanChooseDirectories@Base 0.95.0 WMSetFilePanelCanChooseFiles@Base 0.95.0 WMSetFilePanelDirectory@Base 0.95.0 WMSetFocusToWidget@Base 0.95.0 WMSetFontPanelAction@Base 0.95.0 WMSetFontPanelFont@Base 0.95.0 WMSetFrameRelief@Base 0.95.0 WMSetFrameTitle@Base 0.95.0 WMSetFrameTitleColor@Base 0.95.6 WMSetFrameTitlePosition@Base 0.95.0 WMSetLabelFont@Base 0.95.0 WMSetLabelImage@Base 0.95.0 WMSetLabelImagePosition@Base 0.95.0 WMSetLabelRelief@Base 0.95.0 WMSetLabelText@Base 0.95.0 WMSetLabelTextAlignment@Base 0.95.0 WMSetLabelTextColor@Base 0.95.0 WMSetLabelWraps@Base 0.95.0 WMSetListAction@Base 0.95.0 WMSetListAllowEmptySelection@Base 0.95.0 WMSetListAllowMultipleSelection@Base 0.95.0 WMSetListBottomPosition@Base 0.95.0 WMSetListDoubleAction@Base 0.95.0 WMSetListPosition@Base 0.95.0 WMSetListSelectionToRange@Base 0.95.0 WMSetListUserDrawItemHeight@Base 0.95.0 WMSetListUserDrawProc@Base 0.95.0 WMSetMenuItemAction@Base 0.95.0 WMSetMenuItemEnabled@Base 0.95.0 WMSetMenuItemMixedStatePixmap@Base 0.95.0 WMSetMenuItemOffStatePixmap@Base 0.95.0 WMSetMenuItemOnStatePixmap@Base 0.95.0 WMSetMenuItemPixmap@Base 0.95.0 WMSetMenuItemRepresentedObject@Base 0.95.0 WMSetMenuItemShortcut@Base 0.95.0 WMSetMenuItemShortcutModifierMask@Base 0.95.0 WMSetMenuItemState@Base 0.95.0 WMSetMenuItemTitle@Base 0.95.0 WMSetPopUpButtonAction@Base 0.95.0 WMSetPopUpButtonEnabled@Base 0.95.0 WMSetPopUpButtonItemEnabled@Base 0.95.0 WMSetPopUpButtonPullsDown@Base 0.95.0 WMSetPopUpButtonSelectedItem@Base 0.95.0 WMSetPopUpButtonText@Base 0.95.0 WMSetProgressIndicatorMaxValue@Base 0.95.0 WMSetProgressIndicatorMinValue@Base 0.95.0 WMSetProgressIndicatorValue@Base 0.95.0 WMSetRulerMargins@Base 0.95.0 WMSetRulerMoveAction@Base 0.95.0 WMSetRulerOffset@Base 0.95.0 WMSetRulerReleaseAction@Base 0.95.0 WMSetScrollViewContentView@Base 0.95.0 WMSetScrollViewHasHorizontalScroller@Base 0.95.0 WMSetScrollViewHasVerticalScroller@Base 0.95.0 WMSetScrollViewLineScroll@Base 0.95.0 WMSetScrollViewPageScroll@Base 0.95.0 WMSetScrollViewRelief@Base 0.95.0 WMSetScrollerAction@Base 0.95.0 WMSetScrollerArrowsPosition@Base 0.95.0 WMSetScrollerParameters@Base 0.95.0 WMSetSliderAction@Base 0.95.0 WMSetSliderContinuous@Base 0.95.0 WMSetSliderImage@Base 0.95.0 WMSetSliderKnobThickness@Base 0.95.0 WMSetSliderMaxValue@Base 0.95.0 WMSetSliderMinValue@Base 0.95.0 WMSetSliderValue@Base 0.95.0 WMSetSplitViewConstrainProc@Base 0.95.0 WMSetSplitViewVertical@Base 0.95.0 WMSetTabViewDelegate@Base 0.95.0 WMSetTabViewEnabled@Base 0.95.0 WMSetTabViewFont@Base 0.95.0 WMSetTabViewItemEnabled@Base 0.95.0 WMSetTabViewItemLabel@Base 0.95.0 WMSetTabViewItemView@Base 0.95.0 WMSetTabViewType@Base 0.95.0 WMSetTextAlignment@Base 0.95.0 WMSetTextBackgroundColor@Base 0.95.0 WMSetTextBackgroundPixmap@Base 0.95.0 WMSetTextBlockProperties@Base 0.95.0 WMSetTextDefaultColor@Base 0.95.0 WMSetTextDefaultFont@Base 0.95.0 WMSetTextDelegate@Base 0.95.0 WMSetTextEditable@Base 0.95.0 WMSetTextFieldAlignment@Base 0.95.0 WMSetTextFieldBeveled@Base 0.95.0 WMSetTextFieldBordered@Base 0.95.0 WMSetTextFieldCursorPosition@Base 0.95.0 WMSetTextFieldDelegate@Base 0.95.0 WMSetTextFieldEditable@Base 0.95.0 WMSetTextFieldFont@Base 0.95.0 WMSetTextFieldNextTextField@Base 0.95.0 WMSetTextFieldPrevTextField@Base 0.95.0 WMSetTextFieldSecure@Base 0.95.0 WMSetTextFieldText@Base 0.95.0 WMSetTextForegroundColor@Base 0.95.0 WMSetTextHasHorizontalScroller@Base 0.95.0 WMSetTextHasRuler@Base 0.95.0 WMSetTextHasVerticalScroller@Base 0.95.0 WMSetTextIgnoresNewline@Base 0.95.0 WMSetTextIndentNewLines@Base 0.95.0 WMSetTextRelief@Base 0.95.0 WMSetTextSelectionColor@Base 0.95.0 WMSetTextSelectionFont@Base 0.95.0 WMSetTextSelectionUnderlined@Base 0.95.0 WMSetTextUsesMonoFont@Base 0.95.0 WMSetViewDragDestinationProcs@Base 0.95.0 WMSetViewDragImage@Base 0.95.0 WMSetViewDragSourceProcs@Base 0.95.0 WMSetViewDraggable@Base 0.95.0 WMSetViewExpandsToParent@Base 0.95.0 WMSetViewNextResponder@Base 0.95.0 WMSetViewNotifySizeChanges@Base 0.95.0 WMSetWidgetBackgroundColor@Base 0.95.0 WMSetWidgetBackgroundPixmap@Base 0.95.7 WMSetWidgetDefaultBoldFont@Base 0.95.0 WMSetWidgetDefaultFont@Base 0.95.0 WMSetWindowAspectRatio@Base 0.95.0 WMSetWindowBaseSize@Base 0.95.0 WMSetWindowCloseAction@Base 0.95.0 WMSetWindowDocumentEdited@Base 0.95.0 WMSetWindowInitialPosition@Base 0.95.0 WMSetWindowLevel@Base 0.95.0 WMSetWindowMaxSize@Base 0.95.0 WMSetWindowMinSize@Base 0.95.0 WMSetWindowMiniwindowImage@Base 0.95.0 WMSetWindowMiniwindowPixmap@Base 0.95.0 WMSetWindowMiniwindowTitle@Base 0.95.0 WMSetWindowResizeIncrements@Base 0.95.0 WMSetWindowTitle@Base 0.95.0 WMSetWindowUserPosition@Base 0.95.0 WMShowColorPanel@Base 0.95.0 WMShowFontPanel@Base 0.95.0 WMShowTextRuler@Base 0.95.0 WMSortBrowserColumn@Base 0.95.0 WMSortBrowserColumnWithComparer@Base 0.95.0 WMSortListItems@Base 0.95.0 WMSortListItemsWithComparer@Base 0.95.0 WMSystemFontOfSize@Base 0.95.0 WMTabViewItemAtPoint@Base 0.95.0 WMTextDidBeginEditingNotification@Base 0.95.0 WMTextDidChangeNotification@Base 0.95.0 WMTextDidEndEditingNotification@Base 0.95.0 WMThawText@Base 0.95.0 WMUnmapSubwidgets@Base 0.95.0 WMUnmapWidget@Base 0.95.0 WMUnregisterViewDraggedTypes@Base 0.95.0 WMUnselectAllListItems@Base 0.95.0 WMUnselectListItem@Base 0.95.0 WMUnsetViewDraggable@Base 0.95.0 WMViewFocusDidChangeNotification@Base 0.95.0 WMViewRealizedNotification@Base 0.95.0 WMViewSizeDidChangeNotification@Base 0.95.0 WMViewXID@Base 0.95.0 WMWhiteColor@Base 0.95.0 WMWidgetHeight@Base 0.95.0 WMWidgetIsMapped@Base 0.95.0 WMWidgetOfView@Base 0.95.0 WMWidgetScreen@Base 0.95.0 WMWidgetWidth@Base 0.95.0 WMWidgetXID@Base 0.95.0 WMWidthOfString@Base 0.95.0 WSetColorWellBordered@Base 0.95.0 W_ActionToOperation@Base 0.95.0 W_BalloonHandleEnterView@Base 0.95.0 W_BalloonHandleLeaveView@Base 0.95.0 W_BroadcastMessage@Base 0.95.0 W_CallDestroyHandlers@Base 0.95.0 W_CreateBalloon@Base 0.95.0 W_CreateIC@Base 0.95.0 W_CreateRootView@Base 0.95.0 W_CreateTopView@Base 0.95.0 W_CreateUnmanagedTopView@Base 0.95.0 W_CreateView@Base 0.95.0 W_DestroyIC@Base 0.95.0 W_DestroyView@Base 0.95.0 W_DispatchMessage@Base 0.95.0 W_DragDestinationCancelDropOnEnter@Base 0.95.0 W_DragDestinationInfoClear@Base 0.95.0 W_DragDestinationStartTimer@Base 0.95.0 W_DragDestinationStateHandler@Base 0.95.0 W_DragDestinationStopTimer@Base 0.95.0 W_DragDestinationStoreEnterMsgInfo@Base 0.95.0 W_DragDestinationStorePositionMsgInfo@Base 0.95.0 W_DragSourceStartTimer@Base 0.95.0 W_DragSourceStateHandler@Base 0.95.0 W_DragSourceStopTimer@Base 0.95.0 W_DrawRelief@Base 0.95.0 W_DrawReliefWithGC@Base 0.95.0 W_FocusIC@Base 0.95.0 W_FocusedViewOfToplevel@Base 0.95.0 W_FreeViewXdndPart@Base 0.95.0 W_GetTextHeight@Base 0.95.0 W_GetViewForXWindow@Base 0.95.0 W_HandleDNDClientMessage@Base 0.95.0 W_HandleSelectionEvent@Base 0.95.0 W_InitApplication@Base 0.95.0 W_InitIM@Base 0.95.0 W_LookupString@Base 0.95.0 W_LowerView@Base 0.95.0 W_MapSubviews@Base 0.95.0 W_MapView@Base 0.95.0 W_MoveView@Base 0.95.0 W_OperationToAction@Base 0.95.0 W_PaintText@Base 0.95.0 W_PaintTextAndImage@Base 0.95.0 W_RaiseView@Base 0.95.0 W_ReadConfigurations@Base 0.95.0 W_RealizeView@Base 0.95.0 W_RedisplayView@Base 0.95.0 W_RegisterUserWidget@Base 0.95.0 W_ReleaseView@Base 0.95.0 W_ReparentView@Base 0.95.0 W_ResizeView@Base 0.95.0 W_RetainView@Base 0.95.0 W_SendDnDClientMessage@Base 0.95.0 W_SetFocusOfTopLevel@Base 0.95.0 W_SetPreeditPositon@Base 0.95.0 W_SetViewBackgroundColor@Base 0.95.0 W_SetViewBackgroundPixmap@Base 0.95.7 W_SetViewCursor@Base 0.95.0 W_TopLevelOfView@Base 0.95.0 W_UnFocusIC@Base 0.95.0 W_UnmapSubviews@Base 0.95.0 W_UnmapView@Base 0.95.0 W_getconf_mouseWheelDown@Base 0.95.5 W_getconf_mouseWheelUp@Base 0.95.5 W_setconf_doubleClickDelay@Base 0.95.5 _BrowserViewDelegate@Base 0.95.0 _ColorWellViewDelegate@Base 0.95.0 _ProgressIndicatorDelegate@Base 0.95.0 _RulerViewDelegate@Base 0.95.0 _ScrollViewViewDelegate@Base 0.95.0 _ScrollerViewDelegate@Base 0.95.0 _SliderViewDelegate@Base 0.95.0 _TextFieldViewDelegate@Base 0.95.0 _TextViewDelegate@Base 0.95.0 _WindowViewDelegate@Base 0.95.0 colorListMenuItem@Base 0.95.0 customPaletteMenuItem@Base 0.95.0 rgbCharToInt@Base 0.95.6 rgbColors@Base 0.95.0 rgbIntToChar@Base 0.95.6 wmkpoint@Base 0.95.0 wmkrect@Base 0.95.0 wmksize@Base 0.95.0 diff --git a/debian/libwmaker1.symbols b/debian/libwmaker1.symbols index 2d9f007..80d81df 100644 --- a/debian/libwmaker1.symbols +++ b/debian/libwmaker1.symbols @@ -1,12 +1,13 @@ libWMaker.so.1 libwmaker1 #MINVER# +* Build-Depends-Package: libwmaker-dev WMAppAddWindow@Base 0.95.7 WMAppCreateWithMain@Base 0.95.7 WMAppSetMainMenu@Base 0.95.7 WMHideApplication@Base 0.95.7 WMHideOthers@Base 0.95.7 WMMenuAddItem@Base 0.95.7 WMMenuAddSubmenu@Base 0.95.7 WMMenuCreate@Base 0.95.7 WMProcessEvent@Base 0.95.7 WMRealizeMenus@Base 0.95.7 WMSetWindowAttributes@Base 0.95.7 diff --git a/debian/libwraster6.symbols b/debian/libwraster6.symbols index 9cbb558..a82f08c 100644 --- a/debian/libwraster6.symbols +++ b/debian/libwraster6.symbols @@ -1,61 +1,62 @@ libwraster.so.6 libwraster6 #MINVER# +* Build-Depends-Package: libwraster-dev LIBWRASTER6@LIBWRASTER6 0.95.8 RBevelImage@LIBWRASTER6 0.95.8 RBlurImage@LIBWRASTER6 0.95.8 RClearImage@LIBWRASTER6 0.95.8 RCloneImage@LIBWRASTER6 0.95.8 RCombineAlpha@LIBWRASTER6 0.95.8 RCombineArea@LIBWRASTER6 0.95.8 RCombineAreaWithOpaqueness@LIBWRASTER6 0.95.8 RCombineImageWithColor@LIBWRASTER6 0.95.8 RCombineImages@LIBWRASTER6 0.95.8 RCombineImagesWithOpaqueness@LIBWRASTER6 0.95.8 RConvertImage@LIBWRASTER6 0.95.8 RConvertImageMask@LIBWRASTER6 0.95.8 RCopyArea@LIBWRASTER6 0.95.8 RCreateContext@LIBWRASTER6 0.95.8 RCreateImage@LIBWRASTER6 0.95.8 RCreateImageFromDrawable@LIBWRASTER6 0.95.8 RCreateImageFromXImage@LIBWRASTER6 0.95.8 RCreateXImage@LIBWRASTER6 0.95.8 RDestroyContext@LIBWRASTER6 0.95.8 RDestroyXImage@LIBWRASTER6 0.95.8 RDrawLine@LIBWRASTER6 0.95.8 RDrawLines@LIBWRASTER6 0.95.8 RDrawSegments@LIBWRASTER6 0.95.8 RErrorCode@LIBWRASTER6 0.95.8 RFillImage@LIBWRASTER6 0.95.8 RFlipImage@LIBWRASTER6 0.95.8 RGetClosestXColor@LIBWRASTER6 0.95.8 RGetImageFileFormat@LIBWRASTER6 0.95.8 RGetImageFromXPMData@LIBWRASTER6 0.95.8 RGetPixel@LIBWRASTER6 0.95.8 RGetSubImage@LIBWRASTER6 0.95.8 RGetXImage@LIBWRASTER6 0.95.8 RHSVtoRGB@LIBWRASTER6 0.95.8 RLightImage@LIBWRASTER6 0.95.8 RLoadImage@LIBWRASTER6 0.95.8 RMakeCenteredImage@LIBWRASTER6 0.95.8 RMakeTiledImage@LIBWRASTER6 0.95.8 RMessageForError@LIBWRASTER6 0.95.8 ROperateLine@LIBWRASTER6 0.95.8 ROperateLines@LIBWRASTER6 0.95.8 ROperatePixel@LIBWRASTER6 0.95.8 ROperatePixels@LIBWRASTER6 0.95.8 ROperateRectangle@LIBWRASTER6 0.95.8 ROperateSegments@LIBWRASTER6 0.95.8 RPutPixel@LIBWRASTER6 0.95.8 RPutPixels@LIBWRASTER6 0.95.8 RPutXImage@LIBWRASTER6 0.95.8 RRGBtoHSV@LIBWRASTER6 0.95.8 RReleaseImage@LIBWRASTER6 0.95.8 RRenderGradient@LIBWRASTER6 0.95.8 RRenderInterwovenGradient@LIBWRASTER6 0.95.8 RRenderMultiGradient@LIBWRASTER6 0.95.8 RRetainImage@LIBWRASTER6 0.95.8 RRotateImage@LIBWRASTER6 0.95.8 RSaveImage@LIBWRASTER6 0.95.8 RScaleImage@LIBWRASTER6 0.95.8 RShutdown@LIBWRASTER6 0.95.8 RSmoothScaleImage@LIBWRASTER6 0.95.8 RSupportedFileFormats@LIBWRASTER6 0.95.8 diff --git a/debian/libwutil5.symbols b/debian/libwutil5.symbols index 631090e..552c34f 100644 --- a/debian/libwutil5.symbols +++ b/debian/libwutil5.symbols @@ -1,248 +1,249 @@ libWUtil.so.5 libwutil5 #MINVER# +* Build-Depends-Package: libwings-dev WHandleEvents@Base 0.95.5 WMAddIdleHandler@Base 0.95.5 WMAddInputHandler@Base 0.95.5 WMAddNotificationObserver@Base 0.95.5 WMAddPersistentTimerHandler@Base 0.95.5 WMAddTimerHandler@Base 0.95.5 WMAddToArray@Base 0.95.5 WMAddToPLArray@Base 0.95.5 WMAppendArray@Base 0.95.5 WMAppendBag@Base 0.95.5 WMAppendData@Base 0.95.5 WMAppendDataBytes@Base 0.95.5 WMApplication@Base 0.95.5 WMArrayFirst@Base 0.95.5 WMArrayLast@Base 0.95.5 WMArrayNext@Base 0.95.5 WMArrayPrevious@Base 0.95.5 WMBagFirst@Base 0.95.5 WMBagIndexForIterator@Base 0.95.5 WMBagIteratorAtIndex@Base 0.95.5 WMBagLast@Base 0.95.5 WMBagNext@Base 0.95.5 WMBagPrevious@Base 0.95.5 WMCountHashTable@Base 0.95.5 WMCountInArray@Base 0.95.5 WMCountInBag@Base 0.95.5 WMCreateArray@Base 0.95.5 WMCreateArrayWithArray@Base 0.95.5 WMCreateArrayWithDestructor@Base 0.95.5 WMCreateDataWithBytes@Base 0.95.5 WMCreateDataWithBytesNoCopy@Base 0.95.5 WMCreateDataWithCapacity@Base 0.95.5 WMCreateDataWithData@Base 0.95.5 WMCreateDataWithLength@Base 0.95.5 WMCreateHashTable@Base 0.95.5 WMCreateNotification@Base 0.95.5 WMCreateNotificationQueue@Base 0.95.5 WMCreatePLArray@Base 0.95.5 WMCreatePLData@Base 0.95.5 WMCreatePLDataWithBytes@Base 0.95.5 WMCreatePLDataWithBytesNoCopy@Base 0.95.5 WMCreatePLDictionary@Base 0.95.5 WMCreatePLString@Base 0.95.5 WMCreatePropListFromDescription@Base 0.95.5 WMCreateTreeBag@Base 0.95.5 WMCreateTreeBagWithDestructor@Base 0.95.5 WMCreateTreeNode@Base 0.95.5 WMCreateTreeNodeWithDestructor@Base 0.95.5 WMDataBytes@Base 0.95.5 WMDeepCopyPropList@Base 0.95.5 WMDeleteFromArray@Base 0.95.5 WMDeleteFromBag@Base 0.95.5 WMDeleteFromPLArray@Base 0.95.5 WMDeleteIdleHandler@Base 0.95.5 WMDeleteInputHandler@Base 0.95.5 WMDeleteLeafForTreeNode@Base 0.95.5 WMDeleteTimerHandler@Base 0.95.5 WMDeleteTimerWithClientData@Base 0.95.5 WMDequeueNotificationMatching@Base 0.95.5 WMDestroyTreeNode@Base 0.95.5 WMEmptyArray@Base 0.95.5 WMEmptyBag@Base 0.95.5 WMEnableUDPeriodicSynchronization@Base 0.95.5 WMEnqueueCoalesceNotification@Base 0.95.5 WMEnqueueNotification@Base 0.95.5 WMEnumerateHashTable@Base 0.95.5 WMEraseFromBag@Base 0.95.5 WMFindInArray@Base 0.95.5 WMFindInBag@Base 0.95.5 WMFindInTree@Base 0.95.5 WMFindInTreeWithDepthLimit@Base 0.95.5 WMFreeArray@Base 0.95.5 WMFreeBag@Base 0.95.5 WMFreeHashTable@Base 0.95.5 WMGetApplicationName@Base 0.95.5 WMGetArrayItemCount@Base 0.95.5 WMGetBagItemCount@Base 0.95.5 WMGetDataBytes@Base 0.95.5 WMGetDataBytesWithLength@Base 0.95.5 WMGetDataBytesWithRange@Base 0.95.5 WMGetDataForTreeNode@Base 0.95.5 WMGetDataFormat@Base 0.95.5 WMGetDataLength@Base 0.95.5 WMGetDefaultNotificationQueue@Base 0.95.5 WMGetDefaultsFromPath@Base 0.95.5 WMGetFirstInBag@Base 0.95.5 WMGetFromArray@Base 0.95.5 WMGetFromBag@Base 0.95.5 WMGetFromPLArray@Base 0.95.5 WMGetFromPLData@Base 0.95.5 WMGetFromPLDictionary@Base 0.95.5 WMGetFromPLString@Base 0.95.5 WMGetNotificationClientData@Base 0.95.5 WMGetNotificationName@Base 0.95.5 WMGetNotificationObject@Base 0.95.5 WMGetPLDataBytes@Base 0.95.5 WMGetPLDataLength@Base 0.95.5 WMGetPLDictionaryKeys@Base 0.95.5 WMGetParentForTreeNode@Base 0.95.5 WMGetPropListDescription@Base 0.95.5 WMGetPropListItemCount@Base 0.95.5 WMGetStandardUserDefaults@Base 0.95.5 WMGetSubarrayWithRange@Base 0.95.5 WMGetSubdataWithRange@Base 0.95.5 WMGetTreeNodeDepth@Base 0.95.5 WMGetUDBoolForKey@Base 0.95.5 WMGetUDFloatForKey@Base 0.95.5 WMGetUDIntegerForKey@Base 0.95.5 WMGetUDKeys@Base 0.95.5 WMGetUDObjectForKey@Base 0.95.5 WMGetUDSearchList@Base 0.95.5 WMGetUDStringForKey@Base 0.95.5 WMHashGet@Base 0.95.5 WMHashGetItemAndKey@Base 0.95.5 WMHashInsert@Base 0.95.5 WMHashRemove@Base 0.95.5 WMIncreaseDataLengthBy@Base 0.95.5 WMInitializeApplication@Base 0.95.5 WMInsertInArray@Base 0.95.5 WMInsertInBag@Base 0.95.5 WMInsertInPLArray@Base 0.95.5 WMInsertItemInTree@Base 0.95.5 WMInsertNodeInTree@Base 0.95.5 WMIntHashCallbacks@Base 0.95.5 WMIsDataEqualToData@Base 0.95.5 WMIsPLArray@Base 0.95.5 WMIsPLData@Base 0.95.5 WMIsPLDictionary@Base 0.95.5 WMIsPLString@Base 0.95.5 WMIsPropListEqualTo@Base 0.95.5 WMMapArray@Base 0.95.5 WMMapBag@Base 0.95.5 WMMergePLDictionaries@Base 0.95.5 WMNextHashEnumeratorItem@Base 0.95.5 WMNextHashEnumeratorItemAndKey@Base 0.95.5 WMNextHashEnumeratorKey@Base 0.95.5 WMPLSetCaseSensitive@Base 0.95.5 WMPathForResourceOfType@Base 0.95.5 WMPopFromArray@Base 0.95.5 WMPostNotification@Base 0.95.5 WMPostNotificationName@Base 0.95.5 WMPutInBag@Base 0.95.5 WMPutInPLDictionary@Base 0.95.5 WMReadPropListFromFile@Base 0.95.5 WMReadPropListFromPipe@Base 0.95.5 WMReleaseApplication@Base 0.95.6 WMReleaseData@Base 0.95.5 WMReleaseNotification@Base 0.95.5 WMReleasePropList@Base 0.95.5 WMRemoveFromArrayMatching@Base 0.95.5 WMRemoveFromBag@Base 0.95.5 WMRemoveFromPLArray@Base 0.95.5 WMRemoveFromPLDictionary@Base 0.95.5 WMRemoveLeafForTreeNode@Base 0.95.5 WMRemoveNotificationObserver@Base 0.95.5 WMRemoveNotificationObserverWithName@Base 0.95.5 WMRemoveUDObjectForKey@Base 0.95.5 WMReplaceDataBytesInRange@Base 0.95.5 WMReplaceDataForTreeNode@Base 0.95.5 WMReplaceInArray@Base 0.95.5 WMReplaceInBag@Base 0.95.5 WMResetDataBytesInRange@Base 0.95.5 WMResetHashTable@Base 0.95.5 WMRetainData@Base 0.95.5 WMRetainNotification@Base 0.95.5 WMRetainPropList@Base 0.95.5 WMSaveUserDefaults@Base 0.95.5 WMSetData@Base 0.95.5 WMSetDataCapacity@Base 0.95.5 WMSetDataFormat@Base 0.95.5 WMSetDataLength@Base 0.95.5 WMSetResourcePath@Base 0.95.5 WMSetUDBoolForKey@Base 0.95.5 WMSetUDFloatForKey@Base 0.95.5 WMSetUDIntegerForKey@Base 0.95.5 WMSetUDObjectForKey@Base 0.95.5 WMSetUDSearchList@Base 0.95.5 WMSetUDStringForKey@Base 0.95.5 WMShallowCopyPropList@Base 0.95.5 WMSortArray@Base 0.95.5 WMSortBag@Base 0.95.5 WMSortLeavesForTreeNode@Base 0.95.5 WMSortTree@Base 0.95.5 WMStringHashCallbacks@Base 0.95.5 WMStringPointerHashCallbacks@Base 0.95.5 WMSubtractPLDictionaries@Base 0.95.5 WMSynchronizeUserDefaults@Base 0.95.5 WMTreeWalk@Base 0.95.5 WMUserDefaultsDidChangeNotification@Base 0.95.5 WMWritePropListToFile@Base 0.95.5 WMenuParserCreate@Base 0.95.5 WMenuParserDelete@Base 0.95.5 WMenuParserError@Base 0.95.5 WMenuParserGetFilename@Base 0.95.5 WMenuParserGetLine@Base 0.95.5 WMenuParserRegisterSimpleMacro@Base 0.95.5 W_ApplicationInitialized@Base 0.95.5 W_CheckIdleHandlers@Base 0.95.5 W_CheckTimerHandlers@Base 0.95.5 W_FlushASAPNotificationQueue@Base 0.95.5 W_FlushIdleNotificationQueue@Base 0.95.5 W_HandleInputEvents@Base 0.95.5 W_InitNotificationCenter@Base 0.95.5 W_ReleaseNotificationCenter@Base 0.95.6 _WINGS_progname@Base 0.95.5 __wmessage@Base 0.95.5 isnamechr@Base 0.95.5 menu_parser_define_macro@Base 0.95.5 menu_parser_expand_macro@Base 0.95.5 menu_parser_find_macro@Base 0.95.5 menu_parser_free_macros@Base 0.95.5 menu_parser_register_preset_macros@Base 0.95.5 menu_parser_skip_spaces_and_comments@Base 0.95.5 w_save_defaults_changes@Base 0.95.6 w_syslog_close@Base 0.95.6 wcopy_file@Base 0.95.5 wdefaultspathfordomain@Base 0.95.5 wexpandpath@Base 0.95.5 wfindfile@Base 0.95.5 wfindfileinarray@Base 0.95.5 wfindfileinlist@Base 0.95.5 wfree@Base 0.95.5 wgethomedir@Base 0.95.5 wglobaldefaultspathfordomain@Base 0.95.5 wmalloc@Base 0.95.5 wmkdirhier@Base 0.95.5 wmkrange@Base 0.95.5 wrealloc@Base 0.95.5 wrelease@Base 0.95.5 wretain@Base 0.95.5 wrmdirhier@Base 0.95.5 wsetabort@Base 0.95.5 wshellquote@Base 0.95.5 wstrappend@Base 0.95.5 wstrconcat@Base 0.95.5 wstrdup@Base 0.95.5 wstrlcat@Base 0.95.5 wstrlcpy@Base 0.95.5 wstrndup@Base 0.95.5 wtokenfree@Base 0.95.5 wtokenjoin@Base 0.95.5 wtokennext@Base 0.95.5 wtokensplit@Base 0.95.5 wtrimspace@Base 0.95.5 wusergnusteppath@Base 0.95.5 wusleep@Base 0.95.5 wutil_shutdown@Base 0.95.6 diff --git a/debian/patches/.keepme b/debian/patches/.keepme deleted file mode 100644 index da63666..0000000 --- a/debian/patches/.keepme +++ /dev/null @@ -1 +0,0 @@ -Don't remove this directory diff --git a/debian/patches/10_support_imagemagick6.diff b/debian/patches/10_support_imagemagick6.diff new file mode 100644 index 0000000..014b070 --- /dev/null +++ b/debian/patches/10_support_imagemagick6.diff @@ -0,0 +1,27 @@ +Description: Restore support for ImageMagick v6, as v7 not in Debian. +Origin: https://repo.or.cz/wmaker-crm.git/commitdiff/1dace56 (reversed) +Bug-Debian: https://bugs.debian.org/929825 +Last-Update: 2020-04-05 + +--- a/m4/wm_imgfmt_check.m4 ++++ b/m4/wm_imgfmt_check.m4 +@@ -312,7 +312,7 @@ + dnl + dnl The library was found, check if header is available and compiles + wm_save_CFLAGS="$CFLAGS" +- AS_IF([wm_fn_lib_try_compile "MagickWand/MagickWand.h" "MagickWand *wand;" "wand = NewMagickWand()" "$wm_cv_libchk_magick_cflags"], ++ AS_IF([wm_fn_lib_try_compile "wand/magick_wand.h" "MagickWand *wand;" "wand = NewMagickWand()" "$wm_cv_libchk_magick_cflags"], + [wm_cv_libchk_magick="$wm_cv_libchk_magick_cflags % $wm_cv_libchk_magick_libs"], + [AC_MSG_ERROR([found MagickWand library but could not compile its header])]) + CFLAGS="$wm_save_CFLAGS"])dnl +--- a/wrlib/load_magick.c ++++ b/wrlib/load_magick.c +@@ -22,7 +22,7 @@ + + #include "config.h" + +-#include <MagickWand/MagickWand.h> ++#include <wand/MagickWand.h> + + #include "wraster.h" + #include "imgformat.h" diff --git a/debian/patches/75_WPrefs_to_bindir_when_gnustedir_is_set.diff b/debian/patches/75_WPrefs_to_bindir_when_gnustedir_is_set.diff new file mode 100644 index 0000000..f7559cf --- /dev/null +++ b/debian/patches/75_WPrefs_to_bindir_when_gnustedir_is_set.diff @@ -0,0 +1,19 @@ +Description: Always install WPrefs binary to bindir + Even when setting --with-gnustepdir install the main WPrefs executable + to bindir (/usr/bin) for FHS compliancy. +Author: Andreas Metzler <[email protected]> +Origin: vendor +Forwarded: no +Last-Update: 2018-09-02 + +--- a/configure.ac ++++ b/configure.ac +@@ -853,7 +853,7 @@ + [dnl User specified base path + wprefs_base_dir="$with_gnustepdir/Applications" + wprefs_datadir="$wprefs_base_dir/WPrefs.app" +- wprefs_bindir="$wprefs_base_dir/WPrefs.app"]) ++ wprefs_bindir="${bindir}"]) + AC_SUBST([wprefs_datadir])dnl + AC_SUBST([wprefs_bindir])dnl + diff --git a/debian/patches/series b/debian/patches/series index 451a939..2c16510 100644 --- a/debian/patches/series +++ b/debian/patches/series @@ -1 +1,3 @@ +10_support_imagemagick6.diff 53_Debian_WMState.diff +75_WPrefs_to_bindir_when_gnustedir_is_set.diff diff --git a/debian/rules b/debian/rules index cf725f8..448f6c0 100755 --- a/debian/rules +++ b/debian/rules @@ -1,63 +1,61 @@ #!/usr/bin/make -f # export DH_VERBOSE=1 export DEB_BUILD_MAINT_OPTIONS = hardening=+all export DEB_CFLAGS_MAINT_APPEND += -Wall export DEB_LDFLAGS_MAINT_APPEND = -Wl,--as-needed LINGUAS := $(patsubst po/%.po, %, $(wildcard po/*.po)) -WMAKER_OPTIONS := --disable-xlocale --enable-modelock --enable-pango --enable-xinerama +WMAKER_OPTIONS := --disable-xlocale --enable-modelock --enable-pango \ + --enable-xinerama --enable-magick #not-enabled --enable-usermenu --disable-shape --disable-shm --enable-randr #not-enabled --disable-xpm --disable-png --disable-jpeg --disable-gif --disable-tiff # Debian packages destination folder DEBIAN_TMP := debian/tmp # Be careful with the leading / because some of these values are going # to be hardcoded into the executables BASEDIR := /usr INCLUDEDIR := $(BASEDIR)/include SHAREDIR := $(BASEDIR)/share -GNUSTEPDIR := $(SHAREDIR)/lib/GNUstep/System +GNUSTEPDIR := $(SHAREDIR)/GNUstep/System WMSHAREDIR := $(SHAREDIR)/WindowMaker PIXMAPDIR := $(INCLUDEDIR)/X11/pixmaps DEFSDATADIR := /etc/GNUstep/Defaults COMMON_OPTIONS := --datadir=$(SHAREDIR) \ --with-pixmapdir=$(PIXMAPDIR) \ --with-gnustepdir=$(GNUSTEPDIR) \ --with-defsdatadir=$(DEFSDATADIR) %: - dh $@ --parallel + dh $@ override_dh_auto_configure: env LINGUAS="$(LINGUAS)" dh_auto_configure --verbose -- \ $(COMMON_OPTIONS) $(WMAKER_OPTIONS) override_dh_installdocs: # Readmes - Copy+rename before install # We use the root of the temporal directory debian/tmp cp po/README $(DEBIAN_TMP)/README.po cp README.definable-cursor $(DEBIAN_TMP)/README.definable-cursor + cp WindowMaker/Icons/README $(DEBIAN_TMP)/README.Icons + cp WindowMaker/README $(DEBIAN_TMP)/README.menu + cp WindowMaker/README.themes $(DEBIAN_TMP)/README.themes cp WPrefs.app/README $(DEBIAN_TMP)/README.WPrefs cp WPrefs.app/po/README $(DEBIAN_TMP)/README.WPrefs.po dh_installdocs override_dh_install: # Fix perms for /usr/share/WindowMaker/*sh before install them chmod +x $(DEBIAN_TMP)$(WMSHAREDIR)/autostart.sh chmod +x $(DEBIAN_TMP)$(WMSHAREDIR)/exitscript.sh - - # Now, change the #wmdatadir# string to $(WMSHAREDIR) - perl -pi -e 's:#wmdatadir#:$(WMSHAREDIR):' `find $(DEBIAN_TMP)/$(WMSHAREDIR) -name plmenu.*` - perl -pi -e 's:#wmdatadir#:$(WMSHAREDIR):' $(DEBIAN_TMP)$(WMSHAREDIR)/wmmacros - perl -pi -e 's:#wmdatadir#:$(WMSHAREDIR):' $(DEBIAN_TMP)$(WMSHAREDIR)/plmenu - # Install files - dh_install + dh_install -XREADME override_dh_installwm: dh_installwm --priority=50 diff --git a/debian/watch b/debian/watch index a6402b9..f2bbd99 100644 --- a/debian/watch +++ b/debian/watch @@ -1,2 +1,2 @@ version=4 -http://windowmaker.org/ (?:|.*/)WindowMaker@ANY_VERSION@@ARCHIVE_EXT@ +https://www.windowmaker.org/ (?:|.*/)WindowMaker@ANY_VERSION@@ARCHIVE_EXT@ diff --git a/debian/wmaker-common.docs b/debian/wmaker-common.docs index 0b5039d..bd7391f 100644 --- a/debian/wmaker-common.docs +++ b/debian/wmaker-common.docs @@ -1,13 +1,10 @@ AUTHORS BUGFORM BUGS FAQ NEWS README TODO debian/debianfiles/Themes/DebianLegacy.txt -debian/tmp/README.WPrefs -debian/tmp/README.WPrefs.po -debian/tmp/README.definable-cursor -debian/tmp/README.po +debian/tmp/README.* util/wm-oldmenu2new diff --git a/debian/wmaker-common.install b/debian/wmaker-common.install index 57410fc..5552d36 100644 --- a/debian/wmaker-common.install +++ b/debian/wmaker-common.install @@ -1,18 +1,18 @@ debian/debianfiles/Themes/Debian.style usr/share/WindowMaker/Themes debian/debianfiles/Themes/DebianLegacy.style usr/share/WindowMaker/Themes debian/debianfiles/Themes/DebianSwirl.jpg usr/share/WindowMaker/Backgrounds debian/debianfiles/Themes/debian.tiff usr/share/WindowMaker/Backgrounds debian/debianfiles/conf/WMRootMenu etc/GNUstep/Defaults debian/debianfiles/conf/WMWindowAttributes etc/GNUstep/Defaults debian/debianfiles/conf/WindowMaker etc/GNUstep/Defaults debian/debianfiles/conf/plmenu.Debian etc/GNUstep/Defaults debian/debianfiles/wmaker usr/bin debian/debianfiles/wmaker-common.desktop usr/share/xsessions etc/GNUstep/Defaults/WMGLOBAL etc/GNUstep/Defaults/WMState usr/share/WINGs usr/share/WindowMaker -usr/share/lib/GNUstep/System/Applications/WPrefs.app/WPrefs.tiff -usr/share/lib/GNUstep/System/Applications/WPrefs.app/WPrefs.xpm -usr/share/lib/GNUstep/System/Applications/WPrefs.app/tiff +usr/share/GNUstep/System/Applications/WPrefs.app/WPrefs.tiff +usr/share/GNUstep/System/Applications/WPrefs.app/WPrefs.xpm +usr/share/GNUstep/System/Applications/WPrefs.app/tiff usr/share/locale/*/LC_MESSAGES/*.mo diff --git a/debian/wmaker.install b/debian/wmaker.install index ed65147..1baf9ea 100644 --- a/debian/wmaker.install +++ b/debian/wmaker.install @@ -1,35 +1,35 @@ usr/bin/convertfonts usr/lib/WindowMaker usr/bin/geticonset usr/bin/getstyle usr/bin/seticons usr/bin/setstyle usr/bin/wdread usr/bin/wdwrite usr/bin/wmagnify usr/bin/wmaker usr/lib/WindowMaker usr/bin/wmgenmenu usr/bin/wmiv usr/bin/wmmenugen usr/bin/wmsetbg -usr/share/lib/GNUstep/System/Applications/WPrefs.app/WPrefs usr/lib/GNUstep/System/Applications/WPrefs.app +usr/bin/WPrefs usr/share/man/cs/man1/geticonset.1 usr/share/man/cs/man1/getstyle.1 usr/share/man/cs/man1/seticons.1 usr/share/man/cs/man1/setstyle.1 usr/share/man/cs/man1/wdwrite.1 usr/share/man/cs/man1/wmaker.1 usr/share/man/cs/man1/wmsetbg.1 usr/share/man/ru/man1/geticonset.1 usr/share/man/ru/man1/getstyle.1 usr/share/man/ru/man1/seticons.1 usr/share/man/ru/man1/setstyle.1 usr/share/man/ru/man1/wdwrite.1 usr/share/man/ru/man1/wmaker.1 usr/share/man/ru/man1/wmsetbg.1 usr/share/man/sk/man1/geticonset.1 usr/share/man/sk/man1/getstyle.1 usr/share/man/sk/man1/seticons.1 usr/share/man/sk/man1/setstyle.1 usr/share/man/sk/man1/wdwrite.1 usr/share/man/sk/man1/wmaker.1 usr/share/man/sk/man1/wmsetbg.1 diff --git a/debian/wmaker.links b/debian/wmaker.links index db363d6..f37d1ab 100644 --- a/debian/wmaker.links +++ b/debian/wmaker.links @@ -1,2 +1 @@ usr/bin/wmaker usr/bin/WindowMaker -usr/lib/GNUstep/System/Applications/WPrefs.app/WPrefs usr/bin/WPrefs
roblillack/wmaker
86659be668c955d7fbba1cc4b5e0249d98c76a14
wmlib: Use X flags from configure
diff --git a/wmlib/Makefile.am b/wmlib/Makefile.am index 0816352..8b87fdf 100644 --- a/wmlib/Makefile.am +++ b/wmlib/Makefile.am @@ -1,33 +1,33 @@ AUTOMAKE_OPTIONS = no-dependencies libWMaker_la_LDFLAGS = -version-info 1:1:0 lib_LTLIBRARIES = libWMaker.la include_HEADERS = WMaker.h AM_CPPFLAGS = $(DFLAGS) @XCFLAGS@ -libWMaker_la_LIBADD = -lX11 +libWMaker_la_LIBADD = @XLFLAGS@ @XLIBS@ libWMaker_la_SOURCES = \ menu.c \ app.c \ event.c \ command.c \ app.h \ menu.h pkgconfigdir = $(libdir)/pkgconfig pkgconfig_DATA = wmlib.pc DISTCLEANFILES = $(pkgconfig_DATA) wmlib.pc: Makefile @echo "Generating $@" @echo 'Name: wmlib' > $@ @echo 'Description: Window Maker interface definitions' >> $@ @echo 'Version: $(VERSION)' >> $@ @echo 'Requires: x11' >> $@ @echo 'Libs: $(lib_search_path) -lWMaker' >> $@ @echo 'Cflags: $(inc_search_path)' >> $@
roblillack/wmaker
e314f10909309dfa8f1db3d2595d9257ab3928b0
configure: Fix typo in libXmu check.
diff --git a/m4/wm_xext_check.m4 b/m4/wm_xext_check.m4 index 8bcaf8c..9503af2 100644 --- a/m4/wm_xext_check.m4 +++ b/m4/wm_xext_check.m4 @@ -1,207 +1,207 @@ # wm_xext_check.m4 - Macros to check for X extensions support libraries # # Copyright (c) 2013 Christophe CURIS # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License along # with this program; if not, write to the Free Software Foundation, Inc., # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # WM_XEXT_CHECK_XSHAPE # -------------------- # # Check for the X Shaped Window extension # The check depends on variable 'enable_xshape' being either: # yes - detect, fail if not found # no - do not detect, disable support # auto - detect, disable if not found # # When found, append appropriate stuff in XLIBS, and append info to # the variable 'supported_xext' # When not found, append info to variable 'unsupported' AC_DEFUN_ONCE([WM_XEXT_CHECK_XSHAPE], [WM_LIB_CHECK([XShape], [-lXext], [XShapeSelectInput], [$XLIBS], [wm_save_CFLAGS="$CFLAGS" AS_IF([wm_fn_lib_try_compile "X11/extensions/shape.h" "Window win;" "XShapeSelectInput(NULL, win, 0)" ""], [], [AC_MSG_ERROR([found $CACHEVAR but cannot compile using XShape header])]) CFLAGS="$wm_save_CFLAGS"], [supported_xext], [XLIBS], [enable_shape], [-])dnl ]) dnl AC_DEFUN # WM_XEXT_CHECK_XSHM # ------------------ # # Check for the MIT-SHM extension for Shared Memory support # The check depends on variable 'enable_shm' being either: # yes - detect, fail if not found # no - do not detect, disable support # auto - detect, disable if not found # # When found, append appropriate stuff in XLIBS, and append info to # the variable 'supported_xext' # When not found, append info to variable 'unsupported' AC_DEFUN_ONCE([WM_XEXT_CHECK_XSHM], [WM_LIB_CHECK([XShm], [-lXext], [XShmAttach], [$XLIBS], [wm_save_CFLAGS="$CFLAGS" AC_COMPILE_IFELSE([AC_LANG_PROGRAM([dnl @%:@include <X11/Xlib.h> @%:@include <X11/extensions/XShm.h> ], [dnl XShmSegmentInfo si; XShmAttach(NULL, &si);])], [], [AC_MSG_ERROR([found $CACHEVAR but cannot compile using XShm header])]) AC_COMPILE_IFELSE([AC_LANG_PROGRAM([dnl @%:@include <sys/ipc.h> @%:@include <sys/shm.h> ], [dnl shmget(IPC_PRIVATE, 1024, IPC_CREAT);])], [], [AC_MSG_ERROR([found $CACHEVAR but cannot compile using ipc/shm headers])]) CFLAGS="$wm_save_CFLAGS"], [supported_xext], [XLIBS], [enable_shm], [-])dnl ]) dnl AC_DEFUN # WM_XEXT_CHECK_XMU # ----------------- # # Check for the libXmu (X Misceleanous Utilities) # When found, append it to LIBXMU # When not found, generate an error because we have no work-around for it AC_DEFUN_ONCE([WM_EXT_CHECK_XMU], [AC_CACHE_CHECK([for Xmu library], [wm_cv_xext_xmu], [wm_cv_xext_xmu=no dnl dnl We check that the library is available wm_save_LIBS="$LIBS" AS_IF([wm_fn_lib_try_link "XmuLookupStandardColormap" "-lXmu"], [wm_cv_xext_xmu="-lXmu"]) LIBS="$wm_save_LIBS" AS_IF([test "x$wm_cv_xext_xmu" != "xno"], [dnl dnl A library was found, check if header is available and compile wm_save_CFLAGS="$CFLAGS" AC_COMPILE_IFELSE([AC_LANG_PROGRAM([dnl @%:@include <X11/Xlib.h> @%:@include <X11/Xutil.h> @%:@include <X11/Xmu/StdCmap.h> Display *dpy; Atom prop; ], [dnl XmuLookupStandardColormap(dpy, 0, 0, 0, prop, False, True);]) ], [], [AC_MSG_ERROR([found $wm_cv_xext_xmu but cannot compile with the header])]) CFLAGS="$wm_save_CFLAGS"]) ]) dnl The cached check already reported problems when not found -AS_IF([test "wm_cv_xext_xmu" = "xno"], +AS_IF([test "x$wm_cv_xext_xmu" = "xno"], [LIBXMU="" unsupported="$unsupported Xmu"], [AC_DEFINE([HAVE_LIBXMU], [1], [defined when the libXmu library was found]) LIBXMU="$wm_cv_xext_xmu" supported_xext="$supported_xext Xmu"]) AC_SUBST(LIBXMU)dnl ]) # WM_XEXT_CHECK_XINERAMA # ---------------------- # # Check for the Xinerama extension for multiscreen-as-one support # The check depends on variable 'enable_xinerama' being either: # yes - detect, fail if not found # no - do not detect, disable support # auto - detect, disable if not found # # When found, append appropriate stuff in LIBXINERAMA, and append info to # the variable 'supported_xext' # When not found, append info to variable 'unsupported' AC_DEFUN_ONCE([WM_XEXT_CHECK_XINERAMA], [LIBXINERAMA="" AS_IF([test "x$enable_xinerama" = "xno"], [unsupported="$unsupported Xinerama"], [AC_CACHE_CHECK([for Xinerama support library], [wm_cv_xext_xinerama], [wm_cv_xext_xinerama=no dnl dnl We check that the library is available wm_save_LIBS="$LIBS" for wm_arg in dnl dnl Lib flag % Function name % info "-lXinerama % XineramaQueryScreens" dnl "-lXext % XineramaGetInfo % solaris" ; do AS_IF([wm_fn_lib_try_link "`echo "$wm_arg" | dnl sed -e 's,^[[^%]]*% *,,' | sed -e 's, *%.*$,,' `" dnl "$XLFLAGS $XLIBS `echo "$wm_arg" | sed -e 's, *%.*$,,' `"], [wm_cv_xext_xinerama="`echo "$wm_arg" | sed -e 's, *%[[^%]]*, ,' `" break]) done LIBS="$wm_save_LIBS" AS_IF([test "x$wm_cv_xext_xinerama" = "xno"], [AS_IF([test "x$enable_xinerama" = "xyesno"], [AC_MSG_ERROR([explicit Xinerama support requested but no library found])])], [dnl dnl A library was found, check if header is available and compiles wm_save_CFLAGS="$CFLAGS" AS_CASE([`echo "$wm_cv_xext_xinerama" | sed -e 's,^[[^%]]*,,' `], [*solaris*], [wm_header="X11/extensions/xinerama.h" ; wm_fct="XineramaGetInfo(NULL, 0, NULL, NULL, &intval)"], [wm_header="X11/extensions/Xinerama.h" ; wm_fct="XineramaQueryScreens(NULL, &intval)"]) AS_IF([wm_fn_lib_try_compile "$wm_header" "int intval;" "$wm_fct" ""], [], [AC_MSG_ERROR([found $wm_cv_xext_xinerama but cannot compile with the header])]) AS_UNSET([wm_header]) AS_UNSET([wm_fct]) CFLAGS="$wm_save_CFLAGS" dnl ]) dnl ]) AS_IF([test "x$wm_cv_xext_xinerama" = "xno"], [unsupported="$unsupported Xinerama" enable_xinerama="no"], [LIBXINERAMA="`echo "$wm_cv_xext_xinerama" | sed -e 's, *%.*$,,' `" AC_DEFINE([USE_XINERAMA], [1], [defined when usable Xinerama library with header was found]) AS_CASE([`echo "$wm_cv_xext_xinerama" | sed -e 's,^[[^%]]*,,' `], [*solaris*], [AC_DEFINE([SOLARIS_XINERAMA], [1], [defined when the Solaris Xinerama extension was detected])]) supported_xext="$supported_xext Xinerama"]) ]) AC_SUBST(LIBXINERAMA)dnl ]) # WM_XEXT_CHECK_XRANDR # -------------------- # # Check for the X RandR (Resize-and-Rotate) extension # The check depends on variable 'enable_randr' being either: # yes - detect, fail if not found # no - do not detect, disable support # auto - detect, disable if not found # # When found, append appropriate stuff in LIBXRANDR, and append info to # the variable 'supported_xext' # When not found, append info to variable 'unsupported' AC_DEFUN_ONCE([WM_XEXT_CHECK_XRANDR], [WM_LIB_CHECK([RandR], [-lXrandr], [XRRQueryExtension], [$XLIBS], [wm_save_CFLAGS="$CFLAGS" AS_IF([wm_fn_lib_try_compile "X11/extensions/Xrandr.h" "Display *dpy;" "XRRQueryExtension(dpy, NULL, NULL)" ""], [], [AC_MSG_ERROR([found $CACHEVAR but cannot compile using XRandR header])]) CFLAGS="$wm_save_CFLAGS"], [supported_xext], [LIBXRANDR], [], [-])dnl AC_SUBST([LIBXRANDR])dnl ]) dnl AC_DEFUN
roblillack/wmaker
6320bb6219061713a6f18073342661662bc8b69a
configure: Allow changing default search paths
diff --git a/configure.ac b/configure.ac index fe0ba51..208e8ac 100644 --- a/configure.ac +++ b/configure.ac @@ -1,810 +1,806 @@ dnl ============================================================================ dnl dnl Window Maker autoconf input dnl AC_COPYRIGHT([Copyright (c) 2001-2015 The Window Maker Team]) dnl dnl ============================================================================ dnl dnl This program is free software; you can redistribute it and/or modify dnl it under the terms of the GNU General Public License as published by dnl the Free Software Foundation; either version 2 of the License, or dnl (at your option) any later version. dnl dnl This program is distributed in the hope that it will be useful, dnl but WITHOUT ANY WARRANTY; without even the implied warranty of dnl MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the dnl GNU General Public License for more details. dnl dnl You should have received a copy of the GNU General Public License along dnl with this program; see the file COPYING. dnl dnl ============================================================================ dnl dnl Process with: ./autogen.sh dnl Due to a bug in Autoconf 2.68 (apparently a regression), we need at least dnl version 2.68b which includes this patch: dnl http://git.savannah.gnu.org/gitweb/?p=autoconf.git;a=commit;h=2b0d95faef68d7ed7c08b0edb9ff1c38728376fa dnl dnl Because the 2.69 was released only a few month later, let's just ask for it AC_PREREQ([2.69]) dnl Configuration for Autoconf and Automake dnl ======================================= AC_INIT([WindowMaker],[0.95.9],[[email protected]],[WindowMaker],[http://www.windowmaker.org/]) AC_CONFIG_MACRO_DIR([m4]) AC_CONFIG_HEADERS([config.h]) dnl We need the EXTRA_xxx_DEPENDENCIES keyword in Makefiles which have been dnl introduced in the version 1.11.3; because the 1.12 was realeased shortly dnl after, we just ask for it AM_INIT_AUTOMAKE([1.12 silent-rules]) dnl Reference file used by 'configure' to make sure the path to sources is valid AC_CONFIG_SRCDIR([src/WindowMaker.h]) dnl Include at the end of 'config.h', this file is generated by top-level Makefile AH_BOTTOM([@%:@include "config-paths.h"]) dnl libtool library versioning dnl ========================== dnl dnl current dnl revision dnl age dnl dnl 1. Start with version information of ‘0:0:0’ for each libtool library. dnl 2. Update the version information only immediately before a public dnl release of your software. More frequent updates are unnecessary, and dnl only guarantee that the current interface number gets larger faster. dnl 3. If the library source code has changed at all since the last dnl update, then increment revision (‘c:r:a’ becomes ‘c:r+1:a’). dnl 4. If any interfaces have been added, removed, or changed since the dnl last update, increment current, and set revision to 0. dnl 5. If any interfaces have been added since the last public release, dnl then increment age. dnl 6. If any interfaces have been removed or changed since the last dnl public release, then set age to 0. dnl dnl libwraster WRASTER_CURRENT=6 WRASTER_REVISION=0 WRASTER_AGE=0 WRASTER_VERSION=$WRASTER_CURRENT:$WRASTER_REVISION:$WRASTER_AGE AC_SUBST(WRASTER_VERSION) dnl dnl libWINGs WINGS_CURRENT=4 WINGS_REVISION=0 WINGS_AGE=1 WINGS_VERSION=$WINGS_CURRENT:$WINGS_REVISION:$WINGS_AGE AC_SUBST(WINGS_VERSION) dnl dnl libWUtil WUTIL_CURRENT=5 WUTIL_REVISION=0 WUTIL_AGE=0 WUTIL_VERSION=$WUTIL_CURRENT:$WUTIL_REVISION:$WUTIL_AGE AC_SUBST(WUTIL_VERSION) dnl Checks for programs dnl =================== AC_PROG_CC WM_PROG_CC_C11 AC_PROG_LN_S AC_PROG_GCC_TRADITIONAL LT_INIT dnl Debugging Options dnl ================= AC_ARG_ENABLE([debug], [AS_HELP_STRING([--enable-debug], [enable debugging options, @<:@default=no@:>@])], [AS_CASE(["$enableval"], [yes], [debug=yes], [no], [debug=no], [AC_MSG_ERROR([bad value $enableval for --enable-debug])] )], [debug=no]) AS_IF([test "x$debug" = "xyes"], [dnl This flag should have already been detected and added, but if user dnl provided an explicit CFLAGS it may not be the case AS_IF([echo " $CFLAGS " | grep " -g " 2>&1 > /dev/null], [@%:@ Debug symbol already activated], [AX_CFLAGS_GCC_OPTION([-g])]) dnl dnl This flag generally makes debugging nightmarish, remove it if present CFLAGS="`echo "$CFLAGS" | sed -e 's/-fomit-frame-pointer *//' `" dnl dnl Enable internal debug code CPPFLAGS="$CPPFLAGS -DDEBUG" ], [dnl dnl When debug is not enabled, the user probably does not wants to keep dnl assertions in the final program CPPFLAGS="$CPPFLAGS -DNDEBUG" ]) AX_CFLAGS_GCC_OPTION([-Wall]) AX_CFLAGS_GCC_OPTION([-Wextra -Wno-sign-compare]) dnl dnl The use of trampolines cause code that can crash on some secured OS, it is dnl also known to be a source of crash if not used properly, in a more general dnl way it tends to generate binary code that may not be optimal, and it is dnl not compatible with the 'nested-func-to-macro' workaround WM_CFLAGS_CHECK_FIRST([-Wtrampolines], [-Werror=trampolines dnl try to generate an error if possible -Wtrampolines dnl if not, try to fall back to a simple warning ]) dnl AS_IF([test "x$debug" = "xyes"], [dnl When debug is enabled, we try to activate more checks from dnl the compiler. They are on independant check because the dnl macro checks all the options at once, but we may have cases dnl where some options are not supported and we don't want to dnl loose all of them. dnl dnl clang, suggest parenthesis on bit operations that could be dnl misunderstood due to C operator precedence AX_CFLAGS_GCC_OPTION([-Wbitwise-op-parentheses]) dnl dnl Points at code that gcc thinks is so complicated that gcc dnl gives up trying to optimize, which probably also means it is dnl too complicated to maintain AX_CFLAGS_GCC_OPTION([-Wdisabled-optimization]) dnl dnl Because of C's type promotion, the compiler has to generate dnl less optimal code when a double constant is used in a dnl float expression AX_CFLAGS_GCC_OPTION([-Wdouble-promotion]) dnl dnl Floating-point comparison is not a good idea AX_CFLAGS_GCC_OPTION([-Wfloat-equal]) dnl dnl clang warns about constants that may have portability issues due dnl to the endianness of the host AX_CFLAGS_GCC_OPTION([-Wfour-char-constants]) dnl dnl clang warns about constant that may be too big to be portable AX_CFLAGS_GCC_OPTION([-Wliteral-range]) dnl dnl Try to report misuses of '&' versus '&&' and similar AX_CFLAGS_GCC_OPTION([-Wlogical-op]) dnl dnl clang, reports cases where the code assumes everyone is an dnl expert in C operator precedence... which is unlikely! AX_CFLAGS_GCC_OPTION([-Wlogical-op-parentheses]) dnl dnl Reports declaration of global things that are done inside dnl a local environment, instead of using the appropriate dnl header AX_CFLAGS_GCC_OPTION([-Wnested-externs]) dnl dnl Warn about constant strings that could pose portability issues AX_CFLAGS_GCC_OPTION([-Woverlength-strings]) dnl dnl Use of 'sizeof()' on inappropriate pointer types AX_CFLAGS_GCC_OPTION([-Wpointer-arith]) dnl dnl Having more than 1 prototype for a function makes code updates dnl more difficult, so try to avoid it AX_CFLAGS_GCC_OPTION([-Wredundant-decls]) dnl dnl clang, detect some misuses of sizeof. We also count in our code dnl on the use of the macro 'wlength' which contains a check if the dnl compiler support C11's static_assert AX_CFLAGS_GCC_OPTION([-Wsizeof-array-argument]) dnl dnl Prototype of function must be explicit, no deprecated K&R syntax dnl and no empty argument list which prevents compiler from doing dnl type checking when using the function WM_CFLAGS_GCC_OPTION_STRICTPROTO dnl dnl Proper attributes helps the compiler to produce better code WM_CFLAGS_CHECK_FIRST([format attribute suggest], [-Wsuggest-attribute=format dnl new gcc syntax -Wmissing-format-attribute dnl old gcc syntax, clang ]) WM_CFLAGS_CHECK_FIRST([no-return attribute suggest], [-Wsuggest-attribute=noreturn dnl gcc syntax -Wmissing-noreturn dnl clang syntax ]) dnl dnl GCC provides a couple of checks to detect incorrect macro uses AX_CFLAGS_GCC_OPTION([-Wundef]) WM_CFLAGS_GCC_OPTION_UNUSEDMACROS dnl dnl clang reports stuff marked unused but which is actually used AX_CFLAGS_GCC_OPTION([-Wused-but-marked-unused]) ], [dnl dnl When debug not enabled, we try to avoid some non-necessary dnl messages from the compiler dnl dnl To support legacy X servers, we have sometime to use dnl functions marked as deprecated. We do not wish our users dnl to be worried about it AX_CFLAGS_GCC_OPTION([-Wno-deprecated]) AX_CFLAGS_GCC_OPTION([-Wno-deprecated-declarations]) ]) dnl Support for Nested Functions by the compiler dnl ============================================ WM_PROG_CC_NESTEDFUNC dnl Posix thread dnl ============ dnl they are used by util/wmiv AX_PTHREAD dnl Tracking on what is detected for final status dnl ============================================= unsupported="" supported_core="" supported_xext="" supported_gfx="" dnl Platform-specific Makefile setup dnl ================================ AS_CASE(["$host"], [*-*-linux*|*-*-cygwin*|*-gnu*], [WM_OSDEP="linux" ; CPPFLAGS="$CPPFLAGS -D_XOPEN_SOURCE=600"], [*-*-freebsd*|*-k*bsd-gnu*], [WM_OSDEP="bsd" ; CPPFLAGS="$CPPFLAGS -D_XOPEN_SOURCE=600 -DFREEBSD"], [*-*-netbsd*], [WM_OSDEP="bsd" ; CPPFLAGS="$CPPFLAGS -DNETBSD"], [*-*-openbsd*], [WM_OSDEP="bsd" ; CPPFLAGS="$CPPFLAGS -DOPENBSD"], [*-*-dragonfly*], [WM_OSDEP="bsd" ; CPPFLAGS="$CPPFLAGS -DDRAGONFLYBSD"], [*-apple-darwin*], [WM_OSDEP="darwin"], [*-*-solaris*], [WM_OSDEP="stub"], dnl solaris.c when done [WM_OSDEP="stub"]) AM_CONDITIONAL([WM_OSDEP_LINUX], [test "x$WM_OSDEP" = "xlinux"]) AM_CONDITIONAL([WM_OSDEP_BSD], [test "x$WM_OSDEP" = "xbsd"]) AM_CONDITIONAL([WM_OSDEP_DARWIN], [test "x$WM_OSDEP" = "xdarwin"]) AM_CONDITIONAL([WM_OSDEP_GENERIC], [test "x$WM_OSDEP" = "xstub"]) dnl the prefix dnl ========== dnl dnl move this earlier in the script... anyone know why this is handled dnl in such a bizarre way? test "x$prefix" = xNONE && prefix=$ac_default_prefix dnl Let make expand exec_prefix. test "x$exec_prefix" = xNONE && exec_prefix='${prefix}' _bindir=`eval echo $bindir` _bindir=`eval echo $_bindir` _libdir=`eval echo $libdir` _libdir=`eval echo $_libdir` -lib_search_path='-L${libdir}' - -inc_search_path='-I${includedir}' - dnl =============================================== dnl Specify paths to look for libraries and headers dnl =============================================== AC_ARG_WITH(libs-from, AS_HELP_STRING([--with-libs-from], [pass compiler flags to look for libraries]), - [lib_search_path="$withval $lib_search_path"]) + [lib_search_path="$withval"], [lib_search_path='-L${libdir}']) AC_ARG_WITH(incs-from, AS_HELP_STRING([--with-incs-from], [pass compiler flags to look for header files]), - [inc_search_path="$withval $inc_search_path"]) + [inc_search_path="$withval"], [inc_search_path='-I${includedir}']) dnl Features Configuration dnl ====================== AC_ARG_ENABLE([animations], [AS_HELP_STRING([--disable-animations], [disable permanently animations @<:@default=enabled@:>@])], [AS_CASE(["$enableval"], [yes|no], [], [AC_MSG_ERROR([bad value $enableval for --enable-animations])])], [enable_animations="yes"]) AS_IF([test "x$enable_animations" = "xno"], [unsupported="$unsupported Animations"], [AC_DEFINE([USE_ANIMATIONS], [1], [Defined when user did not request to disable animations]) supported_core="$supported_core Animations"]) AC_ARG_ENABLE([mwm-hints], [AS_HELP_STRING([--disable-mwm-hints], [disable support for Motif WM hints @<:@default=enabled@:>@])], [AS_CASE(["$enableval"], [yes|no], [], [AC_MSG_ERROR([bad value $enableval for --enable-mwm-hints])])], [enable_mwm_hints="yes"]) AS_IF([test "x$enable_mwm_hints" = "xno"], [unsupported="$unsupported MWMHints"], [AC_DEFINE([USE_MWM_HINTS], [1], [Defined when used did not request to disable Motif WM hints]) supported_core="$supported_core MWMHints"]) AM_CONDITIONAL([USE_MWM_HINTS], [test "x$enable_mwm_hints" != "xno"]) dnl Boehm GC dnl ======== AC_ARG_ENABLE([boehm-gc], [AS_HELP_STRING([--enable-boehm-gc], [use Boehm GC instead of the default libc malloc() [default=no]])], [AS_CASE(["$enableval"], [yes], [with_boehm_gc=yes], [no], [with_boehm_gc=no], [AC_MSG_ERROR([bad value $enableval for --enable-boehm-gc])] )], [with_boehm_gc=no]) AS_IF([test "x$with_boehm_gc" = "xyes"], AC_SEARCH_LIBS([GC_malloc], [gc], [AC_DEFINE(USE_BOEHM_GC, 1, [Define if Boehm GC is to be used])], [AC_MSG_FAILURE([--enable-boehm-gc specified but test for libgc failed])])) dnl LCOV dnl ==== AC_ARG_ENABLE([lcov], [AS_HELP_STRING([--enable-lcov[=output-directory]], [enable coverage data generation using LCOV (GCC only) [default=no]])], [], [enable_lcov=no]) AS_IF([test "x$enable_lcov" != "xno"], [AX_CFLAGS_GCC_OPTION(-fprofile-arcs -ftest-coverage) AS_IF([test "x$enable_lcov" = "xyes"], [lcov_output_directory="coverage-report"], [lcov_output_directory="${enable_lcov}/coverage-report"]) AC_SUBST(lcov_output_directory)]) AM_CONDITIONAL([USE_LCOV], [test "x$enable_lcov" != "xno"]) dnl ============================ dnl Checks for library functions dnl ============================ AC_FUNC_MEMCMP AC_FUNC_VPRINTF WM_FUNC_SECURE_GETENV AC_CHECK_FUNCS(gethostname select poll strcasecmp strncasecmp \ setsid mallinfo mkstemp sysconf) AC_SEARCH_LIBS([strerror], [cposix]) dnl nanosleep is generally available in standard libc, although not always the dnl case. One known example is Solaris which needs -lrt AC_SEARCH_LIBS([nanosleep], [rt], [], [AC_MSG_ERROR([function 'nanosleep' not found, please report to [email protected]])]) dnl the flag 'O_NOFOLLOW' for 'open' is used in WINGs WM_FUNC_OPEN_NOFOLLOW dnl Check for strlcat/strlcpy dnl ========================= AC_ARG_WITH([libbsd], [AS_HELP_STRING([--without-libbsd], [do not use libbsd for strlcat and strlcpy [default=check]])], [AS_IF([test "x$with_libbsd" != "xno"], [with_libbsd=bsd] [with_libbsd=] )], [with_libbsd=bsd]) tmp_libs=$LIBS AC_SEARCH_LIBS([strlcat],[$with_libbsd], [AC_DEFINE(HAVE_STRLCAT, 1, [Define if strlcat is available])], [], [] ) AC_SEARCH_LIBS([strlcpy],[$with_libbsd], [AC_DEFINE(HAVE_STRLCAT, 1, [Define if strlcpy is available])], [], [] ) LIBS=$tmp_libs LIBBSD= AS_IF([test "x$ac_cv_search_strlcat" = "x-lbsd" -o "x$ac_cv_search_strlcpy" = "x-lbsd"], [LIBBSD=-lbsd AC_CHECK_HEADERS([bsd/string.h])] ) AC_SUBST(LIBBSD) dnl Check for OpenBSD kernel memory interface - kvm(3) dnl ================================================== AS_IF([test "x$WM_OSDEP" = "xbsd"], AC_SEARCH_LIBS([kvm_openfiles], [kvm]) ) dnl Check for inotify dnl ================= dnl It is used by WindowMaker to reload automatically the configuration when the dnl user changed it using WPref or wdwrite AC_CHECK_HEADERS([sys/inotify.h], [AC_DEFINE([HAVE_INOTIFY], [1], [Check for inotify])]) dnl Check for syslog dnl ================ dnl It is used by WUtil to log the wwarning, werror and wfatal AC_CHECK_HEADERS([syslog.h], [AC_DEFINE([HAVE_SYSLOG], [1], [Check for syslog])]) dnl Checks for header files dnl ======================= AC_HEADER_SYS_WAIT AC_HEADER_TIME AC_CHECK_HEADERS(fcntl.h limits.h sys/ioctl.h libintl.h poll.h malloc.h ctype.h \ string.h strings.h) dnl Checks for typedefs, structures, and compiler characteristics dnl ============================================================= AC_C_CONST AC_C_INLINE WM_C_NORETURN AC_TYPE_SIZE_T AC_TYPE_PID_T WM_TYPE_SIGNAL dnl pkg-config dnl ========== PKG_PROG_PKG_CONFIG AS_IF([test -z "$PKG_CONFIG"],[AC_MSG_ERROR([pkg-config is required.])]) dnl Internationalization dnl ==================== dnl Detect the language for translations to be installed and check dnl that the gettext environment works WM_I18N_LANGUAGES WM_I18N_XGETTEXT WM_I18N_MENUTEXTDOMAIN dnl =========================================== dnl Stuff that uses X dnl =========================================== AC_PATH_XTRA AS_IF([test "x$no_x" = "xyes"], [AC_MSG_ERROR([The path for the X11 files not found! Make sure you have X and it's headers and libraries (the -devel packages in Linux) installed.])]) X_LIBRARY_PATH=$x_libraries XCFLAGS="$X_CFLAGS" XLFLAGS="$X_LIBS" XLIBS="-lX11 $X_EXTRA_LIBS" lib_search_path="$lib_search_path $XLFLAGS" inc_search_path="$inc_search_path $XCFLAGS" AC_SUBST(X_LIBRARY_PATH) dnl Decide which locale function to use, setlocale() or _Xsetlocale() dnl by MANOME Tomonori dnl =========================================== WM_I18N_XLOCALE dnl Check whether XInternAtoms() exist dnl ================================== AC_CHECK_LIB([X11], [XInternAtoms], [AC_DEFINE([HAVE_XINTERNATOMS], [1], [define if your X server has XInternAtoms() (set by configure)])], [], [$XLFLAGS $XLIBS]) dnl Check whether XConvertCase() exist dnl ================================== AC_CHECK_LIB([X11], [XConvertCase], [AC_DEFINE([HAVE_XCONVERTCASE], [1], [define if your X server has XConvertCase() (set by configure)])], [], [$XLFLAGS $XLIBS]) dnl XKB keyboard language status dnl ============================ AC_ARG_ENABLE([modelock], [AS_HELP_STRING([--enable-modelock], [XKB keyboard language status support])], [AS_CASE([$enableval], [yes|no], [], [AC_MSG_ERROR([bad value '$enableval' for --enable-modelock])])], [enable_modelock=no]) AS_IF([test "x$enable_modelock" = "xyes"], [AC_DEFINE([XKB_MODELOCK], [1], [whether XKB language MODELOCK should be enabled]) ]) dnl XDND Drag-nd-Drop support dnl ========================= AC_ARG_ENABLE([xdnd], [AS_HELP_STRING([--disable-xdnd], [disable support for Drag-and-Drop on the dock @<:@default=enabled@:>@])], [AS_CASE(["$enableval"], [yes|no], [], [AC_MSG_ERROR([bad value $enableval for --disable-xdnd]) ]) ], [enable_xdnd=yes]) AS_IF([test "x$enable_xdnd" = "xyes"], [supported_core="$supported_core XDnD" AC_DEFINE([USE_DOCK_XDND], [1], [whether Drag-and-Drop on the dock should be enabled])], [unsupported="$unsupported XDnd"]) AM_CONDITIONAL([USE_DOCK_XDND], [test "x$enable_xdnd" != "xno"]) dnl Support for ICCCM 2.0 Window Manager replacement dnl ================================================ AC_ARG_ENABLE([wmreplace], [AS_HELP_STRING([--enable-wmreplace], [support for ICCCM window manager replacement])], [AS_CASE([$enableval], [yes|no], [], [AC_MSG_ERROR([bad value '$enableval' for --enable-wmreplace])])], [enable_wmreplace=no]) AS_IF([test "x$enable_wmreplace" = "xyes"], [AC_DEFINE([USE_ICCCM_WMREPLACE], [1], [define to support ICCCM protocol for window manager replacement]) supported_xext="$supported_xext WMReplace"]) dnl XShape support dnl ============== AC_ARG_ENABLE([shape], [AS_HELP_STRING([--disable-shape], [disable shaped window extension support])], [AS_CASE(["$enableval"], [yes|no], [], [AC_MSG_ERROR([bad value $enableval for --enable-shape]) ]) ], [enable_shape=auto]) WM_XEXT_CHECK_XSHAPE dnl MIT-SHM support dnl =============== AC_ARG_ENABLE([shm], [AS_HELP_STRING([--disable-shm], [disable usage of MIT-SHM extension])], [AS_CASE(["$enableval"], [yes|no], [], [AC_MSG_ERROR([bad value $enableval for --enable-shm]) ]) ], [enable_shm=auto]) WM_XEXT_CHECK_XSHM dnl X Misceleanous Utility dnl ====================== dnl the libXmu is used in WRaster WM_EXT_CHECK_XMU dnl XINERAMA support dnl ================ AC_ARG_ENABLE([xinerama], [AS_HELP_STRING([--enable-xinerama], [enable Xinerama extension support])], [AS_CASE(["$enableval"], [yes|no], [], [AC_MSG_ERROR([bad value $enableval for --enable-xinerama]) ]) ], [enable_xinerama=auto]) WM_XEXT_CHECK_XINERAMA dnl RandR support dnl ============= AC_ARG_ENABLE([randr], [AS_HELP_STRING([--enable-randr], [enable RandR extension support (NOT recommended, buggy)])], [AS_CASE(["$enableval"], [yes|no], [], [AC_MSG_ERROR([bad value $enableval for --enable-randr]) ]) ], [enable_randr=no]) WM_XEXT_CHECK_XRANDR dnl Math library dnl ============ dnl libWINGS uses math functions, check whether usage requires linking dnl against libm WM_CHECK_LIBM dnl FontConfig dnl ========== dnl libWINGS uses FcPatternDel from libfontconfig AC_MSG_CHECKING([for fontconfig library]) FCLIBS=`$PKG_CONFIG fontconfig --libs` if test "x$FCLIBS" = "x" ; then AC_MSG_RESULT([not found]) else AC_MSG_RESULT([found]) fi AC_SUBST(FCLIBS) dnl Xft2 antialiased font support dnl ============================= xft=yes XFTLIBS="" if test "x$PKG_CONFIG" != x -a "`$PKG_CONFIG xft; echo $?`" = 0; then XFTCONFIG="$PKG_CONFIG xft" pkgconfig_xft=yes else AC_CHECK_PROG(XFTCONFIG, xft-config, xft-config) fi AC_MSG_CHECKING([for the Xft2 library]) if test "x$XFTCONFIG" != x; then XFTLIBS=`$XFTCONFIG --libs` XFTFLAGS=`$XFTCONFIG --cflags` AC_MSG_RESULT([found]) else AC_MSG_RESULT([not found]) echo echo "ERROR!!! libXft2 is not installed or could not be found." echo " Xft2 is a requirement for building Window Maker." echo " Please install it (along with fontconfig) before continuing." echo exit 1 fi minXFT="2.1.0" goodxft="no" dnl dnl The macro below will use $XFTFLAGS (defined above) to find Xft.h dnl WM_CHECK_XFT_VERSION($minXFT, goodxft=yes, goodxft=no) if test "$goodxft" = no; then echo echo "ERROR!!! libXft on this system is an old version." echo " Please consider upgrading to at least version ${minXFT}." echo exit 1 fi AC_SUBST(XFTFLAGS) AC_SUBST(XFTLIBS) dnl PANGO support dnl ============= pango=no AC_ARG_ENABLE(pango, AS_HELP_STRING([--enable-pango], [enable Pango text layout support]), pango=$enableval, pango=no) PANGOFLAGS= PANGOLIBS= if test "$pango" = yes; then PANGOLIBS=`$PKG_CONFIG pangoxft --libs` PANGOFLAGS=`$PKG_CONFIG pangoxft --cflags` if test "x$PANGOLIBS" = "x" ; then AC_MSG_RESULT([not found]) else AC_DEFINE(USE_PANGO, 1, [Define if Pango is to be used]) AC_MSG_RESULT([found]) fi fi inc_search_path="$inc_search_path $PANGOFLAGS" AC_SUBST(PANGOLIBS) dnl ============================================== dnl Graphic Format Libraries dnl ============================================== dnl XPM Support dnl =========== AC_ARG_ENABLE([xpm], [AS_HELP_STRING([--disable-xpm], [disable use of XPM pixmaps through libXpm])], [AS_CASE(["$enableval"], [yes|no], [], [AC_MSG_ERROR([bad value $enableval for --enable-xpm])] )], [enable_xpm=auto]) WM_IMGFMT_CHECK_XPM # for wmlib AC_SUBST(XCFLAGS) # for test AC_SUBST(XLFLAGS) AC_SUBST(XLIBS) AC_SUBST(X_EXTRA_LIBS) dnl =============================================== dnl End of stuff that uses X dnl =============================================== dnl EXIF Support dnl ============ WM_CHECK_LIBEXIF AS_IF([test "x$LIBEXIF" != "x"], [AC_DEFINE(HAVE_EXIF, 1, [Define if EXIF can be used])]) dnl PNG Support dnl =========== AC_ARG_ENABLE([png], [AS_HELP_STRING([--disable-png], [disable PNG support through libpng])], [AS_CASE(["$enableval"], [yes|no], [], [AC_MSG_ERROR([bad value $enableval for --enable-png])] )], [enable_png=auto]) WM_IMGFMT_CHECK_PNG dnl JPEG Support dnl ============ AC_ARG_ENABLE([jpeg], [AS_HELP_STRING([--disable-jpeg], [disable JPEG support through libjpeg])], [AS_CASE(["$enableval"], [yes|no], [], [AC_MSG_ERROR([bad value $enableval for --enable-jpeg])] )], [enable_jpeg=auto]) WM_IMGFMT_CHECK_JPEG dnl GIF Support dnl ============ AC_ARG_ENABLE(gif, [AS_HELP_STRING([--disable-gif], [disable GIF support through libgif or libungif])], [AS_CASE(["$enableval"], [yes|no], [], [AC_MSG_ERROR([bad value $enableval for --enable-gif])] )], [enable_gif=auto]) WM_IMGFMT_CHECK_GIF dnl TIFF Support dnl ============ AC_ARG_ENABLE([tiff], [AS_HELP_STRING([--disable-tiff], [disable use of TIFF images through libtiff])], [AS_CASE(["$enableval"], [yes|no], [], [AC_MSG_ERROR([bad value $enableval for --enable-tiff])] )], [enable_tiff=auto]) WM_IMGFMT_CHECK_TIFF dnl WEBP Support dnl ============ AC_ARG_ENABLE([webp], [AS_HELP_STRING([--disable-webp], [disable WEBP support through libwebp])], [AS_CASE(["$enableval"], [yes|no], [], [AC_MSG_ERROR([bad value $enableval for --enable-webp])] )], [enable_webp=auto]) WM_IMGFMT_CHECK_WEBP dnl MagicK Support dnl ============== AC_ARG_ENABLE([magick], [AS_HELP_STRING([--disable-magick], [disable MAGICK support through libMagickWand])], [AS_CASE(["$enableval"], [yes|no], [], [AC_MSG_ERROR([bad value $enableval for --enable-magick])] )], [enable_magick=auto]) WM_IMGFMT_CHECK_MAGICK dnl PPM Support dnl =========== # The PPM format is always enabled because we have built-in support for the format # We are not using any external library like libppm supported_gfx="$supported_gfx builtin-PPM" # Choice of the default format for icons AS_IF([test "x$enable_tiff" != "xno"], [ICONEXT="tiff"], [ICONEXT="xpm"]) LIBRARY_SEARCH_PATH="$lib_search_path" HEADER_SEARCH_PATH="$inc_search_path" AC_SUBST(LIBRARY_SEARCH_PATH) AC_SUBST(HEADER_SEARCH_PATH) AC_SUBST(GFXLIBS) AC_SUBST(ICONEXT) AM_CONDITIONAL([ICON_EXT_XPM], [test "x$ICONEXT" = "xxpm"]) AM_CONDITIONAL([ICON_EXT_TIFF], [test "x$ICONEXT" = "xtiff"])
roblillack/wmaker
f9bc310fa686c226da42164ca04462e32a314b15
Window Maker 0.95.9
diff --git a/configure.ac b/configure.ac index b5e5ffd..fe0ba51 100644 --- a/configure.ac +++ b/configure.ac @@ -1,549 +1,549 @@ dnl ============================================================================ dnl dnl Window Maker autoconf input dnl AC_COPYRIGHT([Copyright (c) 2001-2015 The Window Maker Team]) dnl dnl ============================================================================ dnl dnl This program is free software; you can redistribute it and/or modify dnl it under the terms of the GNU General Public License as published by dnl the Free Software Foundation; either version 2 of the License, or dnl (at your option) any later version. dnl dnl This program is distributed in the hope that it will be useful, dnl but WITHOUT ANY WARRANTY; without even the implied warranty of dnl MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the dnl GNU General Public License for more details. dnl dnl You should have received a copy of the GNU General Public License along dnl with this program; see the file COPYING. dnl dnl ============================================================================ dnl dnl Process with: ./autogen.sh dnl Due to a bug in Autoconf 2.68 (apparently a regression), we need at least dnl version 2.68b which includes this patch: dnl http://git.savannah.gnu.org/gitweb/?p=autoconf.git;a=commit;h=2b0d95faef68d7ed7c08b0edb9ff1c38728376fa dnl dnl Because the 2.69 was released only a few month later, let's just ask for it AC_PREREQ([2.69]) dnl Configuration for Autoconf and Automake dnl ======================================= -AC_INIT([WindowMaker],[0.95.8],[[email protected]],[WindowMaker],[http://www.windowmaker.org/]) +AC_INIT([WindowMaker],[0.95.9],[[email protected]],[WindowMaker],[http://www.windowmaker.org/]) AC_CONFIG_MACRO_DIR([m4]) AC_CONFIG_HEADERS([config.h]) dnl We need the EXTRA_xxx_DEPENDENCIES keyword in Makefiles which have been dnl introduced in the version 1.11.3; because the 1.12 was realeased shortly dnl after, we just ask for it AM_INIT_AUTOMAKE([1.12 silent-rules]) dnl Reference file used by 'configure' to make sure the path to sources is valid AC_CONFIG_SRCDIR([src/WindowMaker.h]) dnl Include at the end of 'config.h', this file is generated by top-level Makefile AH_BOTTOM([@%:@include "config-paths.h"]) dnl libtool library versioning dnl ========================== dnl dnl current dnl revision dnl age dnl dnl 1. Start with version information of ‘0:0:0’ for each libtool library. dnl 2. Update the version information only immediately before a public dnl release of your software. More frequent updates are unnecessary, and dnl only guarantee that the current interface number gets larger faster. dnl 3. If the library source code has changed at all since the last dnl update, then increment revision (‘c:r:a’ becomes ‘c:r+1:a’). dnl 4. If any interfaces have been added, removed, or changed since the dnl last update, increment current, and set revision to 0. dnl 5. If any interfaces have been added since the last public release, dnl then increment age. dnl 6. If any interfaces have been removed or changed since the last dnl public release, then set age to 0. dnl dnl libwraster WRASTER_CURRENT=6 WRASTER_REVISION=0 WRASTER_AGE=0 WRASTER_VERSION=$WRASTER_CURRENT:$WRASTER_REVISION:$WRASTER_AGE AC_SUBST(WRASTER_VERSION) dnl dnl libWINGs WINGS_CURRENT=4 WINGS_REVISION=0 WINGS_AGE=1 WINGS_VERSION=$WINGS_CURRENT:$WINGS_REVISION:$WINGS_AGE AC_SUBST(WINGS_VERSION) dnl dnl libWUtil WUTIL_CURRENT=5 WUTIL_REVISION=0 WUTIL_AGE=0 WUTIL_VERSION=$WUTIL_CURRENT:$WUTIL_REVISION:$WUTIL_AGE AC_SUBST(WUTIL_VERSION) dnl Checks for programs dnl =================== AC_PROG_CC WM_PROG_CC_C11 AC_PROG_LN_S AC_PROG_GCC_TRADITIONAL LT_INIT dnl Debugging Options dnl ================= AC_ARG_ENABLE([debug], [AS_HELP_STRING([--enable-debug], [enable debugging options, @<:@default=no@:>@])], [AS_CASE(["$enableval"], [yes], [debug=yes], [no], [debug=no], [AC_MSG_ERROR([bad value $enableval for --enable-debug])] )], [debug=no]) AS_IF([test "x$debug" = "xyes"], [dnl This flag should have already been detected and added, but if user dnl provided an explicit CFLAGS it may not be the case AS_IF([echo " $CFLAGS " | grep " -g " 2>&1 > /dev/null], [@%:@ Debug symbol already activated], [AX_CFLAGS_GCC_OPTION([-g])]) dnl dnl This flag generally makes debugging nightmarish, remove it if present CFLAGS="`echo "$CFLAGS" | sed -e 's/-fomit-frame-pointer *//' `" dnl dnl Enable internal debug code CPPFLAGS="$CPPFLAGS -DDEBUG" ], [dnl dnl When debug is not enabled, the user probably does not wants to keep dnl assertions in the final program CPPFLAGS="$CPPFLAGS -DNDEBUG" ]) AX_CFLAGS_GCC_OPTION([-Wall]) AX_CFLAGS_GCC_OPTION([-Wextra -Wno-sign-compare]) dnl dnl The use of trampolines cause code that can crash on some secured OS, it is dnl also known to be a source of crash if not used properly, in a more general dnl way it tends to generate binary code that may not be optimal, and it is dnl not compatible with the 'nested-func-to-macro' workaround WM_CFLAGS_CHECK_FIRST([-Wtrampolines], [-Werror=trampolines dnl try to generate an error if possible -Wtrampolines dnl if not, try to fall back to a simple warning ]) dnl AS_IF([test "x$debug" = "xyes"], [dnl When debug is enabled, we try to activate more checks from dnl the compiler. They are on independant check because the dnl macro checks all the options at once, but we may have cases dnl where some options are not supported and we don't want to dnl loose all of them. dnl dnl clang, suggest parenthesis on bit operations that could be dnl misunderstood due to C operator precedence AX_CFLAGS_GCC_OPTION([-Wbitwise-op-parentheses]) dnl dnl Points at code that gcc thinks is so complicated that gcc dnl gives up trying to optimize, which probably also means it is dnl too complicated to maintain AX_CFLAGS_GCC_OPTION([-Wdisabled-optimization]) dnl dnl Because of C's type promotion, the compiler has to generate dnl less optimal code when a double constant is used in a dnl float expression AX_CFLAGS_GCC_OPTION([-Wdouble-promotion]) dnl dnl Floating-point comparison is not a good idea AX_CFLAGS_GCC_OPTION([-Wfloat-equal]) dnl dnl clang warns about constants that may have portability issues due dnl to the endianness of the host AX_CFLAGS_GCC_OPTION([-Wfour-char-constants]) dnl dnl clang warns about constant that may be too big to be portable AX_CFLAGS_GCC_OPTION([-Wliteral-range]) dnl dnl Try to report misuses of '&' versus '&&' and similar AX_CFLAGS_GCC_OPTION([-Wlogical-op]) dnl dnl clang, reports cases where the code assumes everyone is an dnl expert in C operator precedence... which is unlikely! AX_CFLAGS_GCC_OPTION([-Wlogical-op-parentheses]) dnl dnl Reports declaration of global things that are done inside dnl a local environment, instead of using the appropriate dnl header AX_CFLAGS_GCC_OPTION([-Wnested-externs]) dnl dnl Warn about constant strings that could pose portability issues AX_CFLAGS_GCC_OPTION([-Woverlength-strings]) dnl dnl Use of 'sizeof()' on inappropriate pointer types AX_CFLAGS_GCC_OPTION([-Wpointer-arith]) dnl dnl Having more than 1 prototype for a function makes code updates dnl more difficult, so try to avoid it AX_CFLAGS_GCC_OPTION([-Wredundant-decls]) dnl dnl clang, detect some misuses of sizeof. We also count in our code dnl on the use of the macro 'wlength' which contains a check if the dnl compiler support C11's static_assert AX_CFLAGS_GCC_OPTION([-Wsizeof-array-argument]) dnl dnl Prototype of function must be explicit, no deprecated K&R syntax dnl and no empty argument list which prevents compiler from doing dnl type checking when using the function WM_CFLAGS_GCC_OPTION_STRICTPROTO dnl dnl Proper attributes helps the compiler to produce better code WM_CFLAGS_CHECK_FIRST([format attribute suggest], [-Wsuggest-attribute=format dnl new gcc syntax -Wmissing-format-attribute dnl old gcc syntax, clang ]) WM_CFLAGS_CHECK_FIRST([no-return attribute suggest], [-Wsuggest-attribute=noreturn dnl gcc syntax -Wmissing-noreturn dnl clang syntax ]) dnl dnl GCC provides a couple of checks to detect incorrect macro uses AX_CFLAGS_GCC_OPTION([-Wundef]) WM_CFLAGS_GCC_OPTION_UNUSEDMACROS dnl dnl clang reports stuff marked unused but which is actually used AX_CFLAGS_GCC_OPTION([-Wused-but-marked-unused]) ], [dnl dnl When debug not enabled, we try to avoid some non-necessary dnl messages from the compiler dnl dnl To support legacy X servers, we have sometime to use dnl functions marked as deprecated. We do not wish our users dnl to be worried about it AX_CFLAGS_GCC_OPTION([-Wno-deprecated]) AX_CFLAGS_GCC_OPTION([-Wno-deprecated-declarations]) ]) dnl Support for Nested Functions by the compiler dnl ============================================ WM_PROG_CC_NESTEDFUNC dnl Posix thread dnl ============ dnl they are used by util/wmiv AX_PTHREAD dnl Tracking on what is detected for final status dnl ============================================= unsupported="" supported_core="" supported_xext="" supported_gfx="" dnl Platform-specific Makefile setup dnl ================================ AS_CASE(["$host"], [*-*-linux*|*-*-cygwin*|*-gnu*], [WM_OSDEP="linux" ; CPPFLAGS="$CPPFLAGS -D_XOPEN_SOURCE=600"], [*-*-freebsd*|*-k*bsd-gnu*], [WM_OSDEP="bsd" ; CPPFLAGS="$CPPFLAGS -D_XOPEN_SOURCE=600 -DFREEBSD"], [*-*-netbsd*], [WM_OSDEP="bsd" ; CPPFLAGS="$CPPFLAGS -DNETBSD"], [*-*-openbsd*], [WM_OSDEP="bsd" ; CPPFLAGS="$CPPFLAGS -DOPENBSD"], [*-*-dragonfly*], [WM_OSDEP="bsd" ; CPPFLAGS="$CPPFLAGS -DDRAGONFLYBSD"], [*-apple-darwin*], [WM_OSDEP="darwin"], [*-*-solaris*], [WM_OSDEP="stub"], dnl solaris.c when done [WM_OSDEP="stub"]) AM_CONDITIONAL([WM_OSDEP_LINUX], [test "x$WM_OSDEP" = "xlinux"]) AM_CONDITIONAL([WM_OSDEP_BSD], [test "x$WM_OSDEP" = "xbsd"]) AM_CONDITIONAL([WM_OSDEP_DARWIN], [test "x$WM_OSDEP" = "xdarwin"]) AM_CONDITIONAL([WM_OSDEP_GENERIC], [test "x$WM_OSDEP" = "xstub"]) dnl the prefix dnl ========== dnl dnl move this earlier in the script... anyone know why this is handled dnl in such a bizarre way? test "x$prefix" = xNONE && prefix=$ac_default_prefix dnl Let make expand exec_prefix. test "x$exec_prefix" = xNONE && exec_prefix='${prefix}' _bindir=`eval echo $bindir` _bindir=`eval echo $_bindir` _libdir=`eval echo $libdir` _libdir=`eval echo $_libdir` lib_search_path='-L${libdir}' inc_search_path='-I${includedir}' dnl =============================================== dnl Specify paths to look for libraries and headers dnl =============================================== AC_ARG_WITH(libs-from, AS_HELP_STRING([--with-libs-from], [pass compiler flags to look for libraries]), [lib_search_path="$withval $lib_search_path"]) AC_ARG_WITH(incs-from, AS_HELP_STRING([--with-incs-from], [pass compiler flags to look for header files]), [inc_search_path="$withval $inc_search_path"]) dnl Features Configuration dnl ====================== AC_ARG_ENABLE([animations], [AS_HELP_STRING([--disable-animations], [disable permanently animations @<:@default=enabled@:>@])], [AS_CASE(["$enableval"], [yes|no], [], [AC_MSG_ERROR([bad value $enableval for --enable-animations])])], [enable_animations="yes"]) AS_IF([test "x$enable_animations" = "xno"], [unsupported="$unsupported Animations"], [AC_DEFINE([USE_ANIMATIONS], [1], [Defined when user did not request to disable animations]) supported_core="$supported_core Animations"]) AC_ARG_ENABLE([mwm-hints], [AS_HELP_STRING([--disable-mwm-hints], [disable support for Motif WM hints @<:@default=enabled@:>@])], [AS_CASE(["$enableval"], [yes|no], [], [AC_MSG_ERROR([bad value $enableval for --enable-mwm-hints])])], [enable_mwm_hints="yes"]) AS_IF([test "x$enable_mwm_hints" = "xno"], [unsupported="$unsupported MWMHints"], [AC_DEFINE([USE_MWM_HINTS], [1], [Defined when used did not request to disable Motif WM hints]) supported_core="$supported_core MWMHints"]) AM_CONDITIONAL([USE_MWM_HINTS], [test "x$enable_mwm_hints" != "xno"]) dnl Boehm GC dnl ======== AC_ARG_ENABLE([boehm-gc], [AS_HELP_STRING([--enable-boehm-gc], [use Boehm GC instead of the default libc malloc() [default=no]])], [AS_CASE(["$enableval"], [yes], [with_boehm_gc=yes], [no], [with_boehm_gc=no], [AC_MSG_ERROR([bad value $enableval for --enable-boehm-gc])] )], [with_boehm_gc=no]) AS_IF([test "x$with_boehm_gc" = "xyes"], AC_SEARCH_LIBS([GC_malloc], [gc], [AC_DEFINE(USE_BOEHM_GC, 1, [Define if Boehm GC is to be used])], [AC_MSG_FAILURE([--enable-boehm-gc specified but test for libgc failed])])) dnl LCOV dnl ==== AC_ARG_ENABLE([lcov], [AS_HELP_STRING([--enable-lcov[=output-directory]], [enable coverage data generation using LCOV (GCC only) [default=no]])], [], [enable_lcov=no]) AS_IF([test "x$enable_lcov" != "xno"], [AX_CFLAGS_GCC_OPTION(-fprofile-arcs -ftest-coverage) AS_IF([test "x$enable_lcov" = "xyes"], [lcov_output_directory="coverage-report"], [lcov_output_directory="${enable_lcov}/coverage-report"]) AC_SUBST(lcov_output_directory)]) AM_CONDITIONAL([USE_LCOV], [test "x$enable_lcov" != "xno"]) dnl ============================ dnl Checks for library functions dnl ============================ AC_FUNC_MEMCMP AC_FUNC_VPRINTF WM_FUNC_SECURE_GETENV AC_CHECK_FUNCS(gethostname select poll strcasecmp strncasecmp \ setsid mallinfo mkstemp sysconf) AC_SEARCH_LIBS([strerror], [cposix]) dnl nanosleep is generally available in standard libc, although not always the dnl case. One known example is Solaris which needs -lrt AC_SEARCH_LIBS([nanosleep], [rt], [], [AC_MSG_ERROR([function 'nanosleep' not found, please report to [email protected]])]) dnl the flag 'O_NOFOLLOW' for 'open' is used in WINGs WM_FUNC_OPEN_NOFOLLOW dnl Check for strlcat/strlcpy dnl ========================= AC_ARG_WITH([libbsd], [AS_HELP_STRING([--without-libbsd], [do not use libbsd for strlcat and strlcpy [default=check]])], [AS_IF([test "x$with_libbsd" != "xno"], [with_libbsd=bsd] [with_libbsd=] )], [with_libbsd=bsd]) tmp_libs=$LIBS AC_SEARCH_LIBS([strlcat],[$with_libbsd], [AC_DEFINE(HAVE_STRLCAT, 1, [Define if strlcat is available])], [], [] ) AC_SEARCH_LIBS([strlcpy],[$with_libbsd], [AC_DEFINE(HAVE_STRLCAT, 1, [Define if strlcpy is available])], [], [] ) LIBS=$tmp_libs LIBBSD= AS_IF([test "x$ac_cv_search_strlcat" = "x-lbsd" -o "x$ac_cv_search_strlcpy" = "x-lbsd"], [LIBBSD=-lbsd AC_CHECK_HEADERS([bsd/string.h])] ) AC_SUBST(LIBBSD) dnl Check for OpenBSD kernel memory interface - kvm(3) dnl ================================================== AS_IF([test "x$WM_OSDEP" = "xbsd"], AC_SEARCH_LIBS([kvm_openfiles], [kvm]) ) dnl Check for inotify dnl ================= dnl It is used by WindowMaker to reload automatically the configuration when the dnl user changed it using WPref or wdwrite AC_CHECK_HEADERS([sys/inotify.h], [AC_DEFINE([HAVE_INOTIFY], [1], [Check for inotify])]) dnl Check for syslog dnl ================ dnl It is used by WUtil to log the wwarning, werror and wfatal AC_CHECK_HEADERS([syslog.h], [AC_DEFINE([HAVE_SYSLOG], [1], [Check for syslog])]) dnl Checks for header files dnl ======================= AC_HEADER_SYS_WAIT AC_HEADER_TIME AC_CHECK_HEADERS(fcntl.h limits.h sys/ioctl.h libintl.h poll.h malloc.h ctype.h \ string.h strings.h) dnl Checks for typedefs, structures, and compiler characteristics dnl ============================================================= AC_C_CONST AC_C_INLINE WM_C_NORETURN AC_TYPE_SIZE_T AC_TYPE_PID_T WM_TYPE_SIGNAL dnl pkg-config dnl ========== PKG_PROG_PKG_CONFIG AS_IF([test -z "$PKG_CONFIG"],[AC_MSG_ERROR([pkg-config is required.])]) dnl Internationalization dnl ==================== dnl Detect the language for translations to be installed and check dnl that the gettext environment works WM_I18N_LANGUAGES WM_I18N_XGETTEXT WM_I18N_MENUTEXTDOMAIN dnl =========================================== dnl Stuff that uses X dnl =========================================== AC_PATH_XTRA AS_IF([test "x$no_x" = "xyes"], [AC_MSG_ERROR([The path for the X11 files not found! Make sure you have X and it's headers and libraries (the -devel packages in Linux) installed.])]) X_LIBRARY_PATH=$x_libraries XCFLAGS="$X_CFLAGS" XLFLAGS="$X_LIBS" XLIBS="-lX11 $X_EXTRA_LIBS" lib_search_path="$lib_search_path $XLFLAGS" inc_search_path="$inc_search_path $XCFLAGS" AC_SUBST(X_LIBRARY_PATH) dnl Decide which locale function to use, setlocale() or _Xsetlocale() dnl by MANOME Tomonori dnl =========================================== WM_I18N_XLOCALE dnl Check whether XInternAtoms() exist dnl ================================== AC_CHECK_LIB([X11], [XInternAtoms], [AC_DEFINE([HAVE_XINTERNATOMS], [1], [define if your X server has XInternAtoms() (set by configure)])], [], [$XLFLAGS $XLIBS]) dnl Check whether XConvertCase() exist dnl ================================== AC_CHECK_LIB([X11], [XConvertCase], [AC_DEFINE([HAVE_XCONVERTCASE], [1], [define if your X server has XConvertCase() (set by configure)])], [], [$XLFLAGS $XLIBS]) dnl XKB keyboard language status dnl ============================ AC_ARG_ENABLE([modelock], [AS_HELP_STRING([--enable-modelock], [XKB keyboard language status support])], [AS_CASE([$enableval], [yes|no], [], [AC_MSG_ERROR([bad value '$enableval' for --enable-modelock])])], [enable_modelock=no]) AS_IF([test "x$enable_modelock" = "xyes"], [AC_DEFINE([XKB_MODELOCK], [1], [whether XKB language MODELOCK should be enabled]) ]) dnl XDND Drag-nd-Drop support dnl ========================= AC_ARG_ENABLE([xdnd], [AS_HELP_STRING([--disable-xdnd], [disable support for Drag-and-Drop on the dock @<:@default=enabled@:>@])], [AS_CASE(["$enableval"], [yes|no], [], [AC_MSG_ERROR([bad value $enableval for --disable-xdnd]) ]) ], [enable_xdnd=yes]) AS_IF([test "x$enable_xdnd" = "xyes"], [supported_core="$supported_core XDnD" AC_DEFINE([USE_DOCK_XDND], [1], [whether Drag-and-Drop on the dock should be enabled])], [unsupported="$unsupported XDnd"]) AM_CONDITIONAL([USE_DOCK_XDND], [test "x$enable_xdnd" != "xno"]) dnl Support for ICCCM 2.0 Window Manager replacement dnl ================================================ AC_ARG_ENABLE([wmreplace], [AS_HELP_STRING([--enable-wmreplace], [support for ICCCM window manager replacement])], [AS_CASE([$enableval], [yes|no], [], [AC_MSG_ERROR([bad value '$enableval' for --enable-wmreplace])])], [enable_wmreplace=no]) AS_IF([test "x$enable_wmreplace" = "xyes"], [AC_DEFINE([USE_ICCCM_WMREPLACE], [1], [define to support ICCCM protocol for window manager replacement]) supported_xext="$supported_xext WMReplace"]) dnl XShape support
roblillack/wmaker
bb716a4ca117c856d333fa8d9c152fda8a6acf2a
util: renamed wmiv DEBUG constant name
diff --git a/util/wmiv.c b/util/wmiv.c index 57ad4d4..492af88 100755 --- a/util/wmiv.c +++ b/util/wmiv.c @@ -1,1021 +1,1021 @@ /* * Window Maker window manager * * Copyright (c) 2014 Window Maker Team - David Maciejak * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #if !defined(_GNU_SOURCE) #define _GNU_SOURCE #endif #include <X11/keysym.h> #include <X11/XKBlib.h> #include <X11/Xatom.h> #include <X11/Xlib.h> #include "wraster.h" #include <stdlib.h> #include <stdio.h> #include <string.h> #include <dirent.h> #include <limits.h> #include <unistd.h> #include <sys/stat.h> #include <getopt.h> #include <math.h> #include "config.h" #ifdef HAVE_EXIF #include <libexif/exif-data.h> #endif #ifdef HAVE_PTHREAD #include <pthread.h> #endif #ifdef USE_XPM extern int XpmCreatePixmapFromData(Display *, Drawable, char **, Pixmap *, Pixmap *, void *); /* this is the icon from eog project git.gnome.org/browse/eog */ #include "wmiv.h" #endif -#define DEBUG 0 +#define WMIV_DEBUG 0 #define FILE_SEPARATOR '/' Display *dpy; Window win; RContext *ctx; RImage *img; Pixmap pix; const char *APPNAME = "wmiv"; int APPVERSION_MAJOR = 0; int APPVERSION_MINOR = 7; int NEXT = 0; int PREV = 1; float zoom_factor = 0; int max_width = 0; int max_height = 0; Bool fullscreen_flag = False; Bool focus = False; Bool back_from_fullscreen = False; #ifdef HAVE_PTHREAD Bool diaporama_flag = False; int diaporama_delay = 5; pthread_t tid = 0; #endif XTextProperty title_property; XTextProperty icon_property; unsigned current_index = 1; unsigned max_index = 1; RColor lightGray; RColor darkGray; RColor black; RColor red; typedef struct link link_t; struct link { const void *data; link_t *prev; link_t *next; }; typedef struct linked_list { int count; link_t *first; link_t *last; } linked_list_t; linked_list_t list; link_t *current_link; /* load_oriented_image: used to load an image and optionally get its orientation if libexif is available return the image on success, NULL on failure */ RImage *load_oriented_image(RContext *context, const char *file, int index) { RImage *image; #ifdef HAVE_EXIF int orientation = 0; #endif image = RLoadImage(context, file, index); if (!image) return NULL; #ifdef HAVE_EXIF ExifData *exifData = exif_data_new_from_file(file); if (exifData) { ExifByteOrder byteOrder = exif_data_get_byte_order(exifData); ExifEntry *exifEntry = exif_data_get_entry(exifData, EXIF_TAG_ORIENTATION); if (exifEntry) orientation = exif_get_short(exifEntry->data, byteOrder); exif_data_free(exifData); } /* 0th Row 0th Column 1 top left side 2 top right side 3 bottom right side 4 bottom left side 5 left side top 6 right side top 7 right side bottom 8 left side bottom */ if (image && (orientation > 1)) { RImage *tmp = NULL; switch (orientation) { case 2: tmp = RFlipImage(image, RHorizontalFlip); break; case 3: tmp = RRotateImage(image, 180); break; case 4: tmp = RFlipImage(image, RVerticalFlip); break; case 5: { RImage *tmp2; tmp2 = RFlipImage(image, RVerticalFlip); if (tmp2) { tmp = RRotateImage(tmp2, 90); RReleaseImage(tmp2); } } break; case 6: tmp = RRotateImage(image, 90); break; case 7: { RImage *tmp2; tmp2 = RFlipImage(image, RVerticalFlip); if (tmp2) { tmp = RRotateImage(tmp2, 270); RReleaseImage(tmp2); } } break; case 8: tmp = RRotateImage(image, 270); break; } if (tmp) { RReleaseImage(image); image = tmp; } } #endif return image; } /* change_title: used to change window title return EXIT_SUCCESS on success, 1 on failure */ int change_title(XTextProperty *prop, char *filename) { char *combined_title = NULL; if (!asprintf(&combined_title, "%s - %u/%u - %s", APPNAME, current_index, max_index, filename)) if (!asprintf(&combined_title, "%s - %u/%u", APPNAME, current_index, max_index)) return EXIT_FAILURE; XStringListToTextProperty(&combined_title, 1, prop); XSetWMName(dpy, win, prop); if (prop->value) XFree(prop->value); free(combined_title); return EXIT_SUCCESS; } /* rescale_image: used to rescale the current image based on the screen size return EXIT_SUCCESS on success */ int rescale_image(void) { long final_width = img->width; long final_height = img->height; /* check if there is already a zoom factor applied */ if (fabsf(zoom_factor) <= 0.0f) { final_width = img->width + (int)(img->width * zoom_factor); final_height = img->height + (int)(img->height * zoom_factor); } if ((max_width < final_width) || (max_height < final_height)) { long val = 0; if (final_width > final_height) { val = final_height * max_width / final_width; final_width = final_width * val / final_height; final_height = val; if (val > max_height) { val = final_width * max_height / final_height; final_height = final_height * val / final_width; final_width = val; } } else { val = final_width * max_height / final_height; final_height = final_height * val / final_width; final_width = val; if (val > max_width) { val = final_height * max_width / final_width; final_width = final_width * val / final_height; final_height = val; } } } if ((final_width != img->width) || (final_height != img->height)) { RImage *old_img = img; img = RScaleImage(img, final_width, final_height); if (!img) { img = old_img; return EXIT_FAILURE; } RReleaseImage(old_img); } if (!RConvertImage(ctx, img, &pix)) { fprintf(stderr, "%s\n", RMessageForError(RErrorCode)); return EXIT_FAILURE; } return EXIT_SUCCESS; } /* maximize_image: find the best image size for the current display return EXIT_SUCCESS on success */ int maximize_image(void) { rescale_image(); XCopyArea(dpy, pix, win, ctx->copy_gc, 0, 0, img->width, img->height, max_width/2-img->width/2, max_height/2-img->height/2); return EXIT_SUCCESS; } /* merge_with_background: merge the current image with with a checkboard background return EXIT_SUCCESS on success, 1 on failure */ int merge_with_background(RImage *i) { if (i) { RImage *back; back = RCreateImage(i->width, i->height, True); if (back) { int opaq = 255; int x = 0, y = 0; RFillImage(back, &lightGray); for (x = 0; x <= i->width; x += 8) { if (x/8 % 2) y = 8; else y = 0; for (; y <= i->height; y += 16) ROperateRectangle(back, RAddOperation, x, y, x+8, y+8, &darkGray); } RCombineImagesWithOpaqueness(i, back, opaq); RReleaseImage(back); return EXIT_SUCCESS; } } return EXIT_FAILURE; } /* turn_image: rotate the image by the angle passed return EXIT_SUCCESS on success, EXIT_FAILURE on failure */ int turn_image(float angle) { RImage *tmp; if (!img) return EXIT_FAILURE; tmp = RRotateImage(img, angle); if (!tmp) return EXIT_FAILURE; if (!fullscreen_flag) { if (img->width != tmp->width || img->height != tmp->height) XResizeWindow(dpy, win, tmp->width, tmp->height); } RReleaseImage(img); img = tmp; rescale_image(); if (!fullscreen_flag) { XCopyArea(dpy, pix, win, ctx->copy_gc, 0, 0, img->width, img->height, 0, 0); } else { XClearWindow(dpy, win); XCopyArea(dpy, pix, win, ctx->copy_gc, 0, 0, img->width, img->height, max_width/2-img->width/2, max_height/2-img->height/2); } return EXIT_SUCCESS; } /* turn_image_right: rotate the image by 90 degree return EXIT_SUCCESS on success, EXIT_FAILURE on failure */ int turn_image_right(void) { return turn_image(90.0); } /* turn_image_left: rotate the image by -90 degree return EXIT_SUCCESS on success, 1 on failure */ int turn_image_left(void) { return turn_image(-90.0); } /* draw_failed_image: create a red crossed image to indicate an error loading file return the image on success, NULL on failure */ RImage *draw_failed_image(void) { RImage *failed_image = NULL; XWindowAttributes attr; if (win && (XGetWindowAttributes(dpy, win, &attr) >= 0)) failed_image = RCreateImage(attr.width, attr.height, False); else failed_image = RCreateImage(50, 50, False); if (!failed_image) return NULL; RFillImage(failed_image, &black); ROperateLine(failed_image, RAddOperation, 0, 0, failed_image->width, failed_image->height, &red); ROperateLine(failed_image, RAddOperation, 0, failed_image->height, failed_image->width, 0, &red); return failed_image; } /* full_screen: sending event to the window manager to switch from/to full screen mode return EXIT_SUCCESS on success, 1 on failure */ int full_screen(void) { XEvent xev; Atom wm_state = XInternAtom(dpy, "_NET_WM_STATE", True); Atom fullscreen = XInternAtom(dpy, "_NET_WM_STATE_FULLSCREEN", True); long mask = SubstructureNotifyMask; if (fullscreen_flag) { fullscreen_flag = False; zoom_factor = 0; back_from_fullscreen = True; } else { fullscreen_flag = True; zoom_factor = 1000; } memset(&xev, 0, sizeof(xev)); xev.type = ClientMessage; xev.xclient.display = dpy; xev.xclient.window = win; xev.xclient.message_type = wm_state; xev.xclient.format = 32; xev.xclient.data.l[0] = fullscreen_flag; xev.xclient.data.l[1] = fullscreen; if (!XSendEvent(dpy, DefaultRootWindow(dpy), False, mask, &xev)) { fprintf(stderr, "Error: sending fullscreen event to xserver\n"); return EXIT_FAILURE; } return EXIT_SUCCESS; } /* zoom_in_out: apply a zoom factor on the current image arg: 1 to zoom in, 0 to zoom out return EXIT_SUCCESS on success, 1 on failure */ int zoom_in_out(int z) { RImage *old_img = img; RImage *tmp = load_oriented_image(ctx, current_link->data, 0); if (!tmp) return EXIT_FAILURE; if (z) { zoom_factor += 0.2f; img = RScaleImage(tmp, tmp->width + (int)(tmp->width * zoom_factor), tmp->height + (int)(tmp->height * zoom_factor)); if (!img) { img = old_img; return EXIT_FAILURE; } } else { zoom_factor -= 0.2f; int new_width = tmp->width + (int) (tmp->width * zoom_factor); int new_height = tmp->height + (int)(tmp->height * zoom_factor); if ((new_width <= 0) || (new_height <= 0)) { zoom_factor += 0.2f; RReleaseImage(tmp); return EXIT_FAILURE; } img = RScaleImage(tmp, new_width, new_height); if (!img) { img = old_img; return EXIT_FAILURE; } } RReleaseImage(old_img); RReleaseImage(tmp); XFreePixmap(dpy, pix); merge_with_background(img); if (!RConvertImage(ctx, img, &pix)) { fprintf(stderr, "%s\n", RMessageForError(RErrorCode)); return EXIT_FAILURE; } XResizeWindow(dpy, win, img->width, img->height); return EXIT_SUCCESS; } /* zoom_in: transitional fct used to call zoom_in_out with zoom in flag return EXIT_SUCCESS on success, 1 on failure */ int zoom_in(void) { return zoom_in_out(1); } /* zoom_out: transitional fct used to call zoom_in_out with zoom out flag return EXIT_SUCCESS on success, 1 on failure */ int zoom_out(void) { return zoom_in_out(0); } /* change_image: load previous or next image arg: way which could be PREV or NEXT constant return EXIT_SUCCESS on success, 1 on failure */ int change_image(int way) { if (img && current_link) { int old_img_width = img->width; int old_img_height = img->height; RReleaseImage(img); if (way == NEXT) { current_link = current_link->next; current_index++; } else { current_link = current_link->prev; current_index--; } if (current_link == NULL) { if (way == NEXT) { current_link = list.first; current_index = 1; } else { current_link = list.last; current_index = max_index; } } - if (DEBUG) + if (WMIV_DEBUG) fprintf(stderr, "current file is> %s\n", (char *)current_link->data); img = load_oriented_image(ctx, current_link->data, 0); if (!img) { fprintf(stderr, "Error: %s %s\n", (char *)current_link->data, RMessageForError(RErrorCode)); img = draw_failed_image(); } else { merge_with_background(img); } rescale_image(); if (!fullscreen_flag) { if ((old_img_width != img->width) || (old_img_height != img->height)) XResizeWindow(dpy, win, img->width, img->height); else XCopyArea(dpy, pix, win, ctx->copy_gc, 0, 0, img->width, img->height, 0, 0); change_title(&title_property, (char *)current_link->data); } else { XClearWindow(dpy, win); XCopyArea(dpy, pix, win, ctx->copy_gc, 0, 0, img->width, img->height, max_width/2-img->width/2, max_height/2-img->height/2); } return EXIT_SUCCESS; } return EXIT_FAILURE; } #ifdef HAVE_PTHREAD /* diaporama: send a xevent to display the next image at every delay set to diaporama_delay arg: not used return void */ void *diaporama(void *arg) { (void) arg; XKeyEvent event; event.display = dpy; event.window = win; event.root = DefaultRootWindow(dpy); event.subwindow = None; event.time = CurrentTime; event.x = 1; event.y = 1; event.x_root = 1; event.y_root = 1; event.same_screen = True; event.keycode = XKeysymToKeycode(dpy, XK_Right); event.state = 0; event.type = KeyPress; while (diaporama_flag) { int r; r = XSendEvent(event.display, event.window, True, KeyPressMask, (XEvent *)&event); if (!r) fprintf(stderr, "Error sending event\n"); XFlush(dpy); /* default sleep time between moving to next image */ sleep(diaporama_delay); } tid = 0; return arg; } #endif /* linked_list_init: init the linked list */ void linked_list_init(linked_list_t *list) { list->first = list->last = 0; list->count = 0; } /* linked_list_add: add an element to the linked list return EXIT_SUCCESS on success, 1 otherwise */ int linked_list_add(linked_list_t *list, const void *data) { link_t *link; /* calloc sets the "next" field to zero. */ link = calloc(1, sizeof(link_t)); if (!link) { fprintf(stderr, "Error: memory allocation failed\n"); return EXIT_FAILURE; } link->data = data; if (list->last) { /* Join the two final links together. */ list->last->next = link; link->prev = list->last; list->last = link; } else { list->first = link; list->last = link; } list->count++; return EXIT_SUCCESS; } /* linked_list_free: deallocate the whole linked list */ void linked_list_free(linked_list_t *list) { link_t *link; link_t *next; for (link = list->first; link; link = next) { /* Store the next value so that we don't access freed memory. */ next = link->next; if (link->data) free((char *)link->data); free(link); } } /* connect_dir: list and sort by name all files from a given directory arg: the directory path that contains images, the linked list where to add the new file refs return: the first argument of the list or NULL on failure */ link_t *connect_dir(char *dirpath, linked_list_t *li) { struct dirent **dir; int dv, idx; char path[PATH_MAX] = ""; if (!dirpath) return NULL; dv = scandir(dirpath, &dir, 0, alphasort); if (dv < 0) { /* maybe it's a file */ struct stat stDirInfo; if (lstat(dirpath, &stDirInfo) == 0) { linked_list_add(li, strdup(dirpath)); return li->first; } else { return NULL; } } for (idx = 0; idx < dv; idx++) { struct stat stDirInfo; if (dirpath[strlen(dirpath)-1] == FILE_SEPARATOR) snprintf(path, PATH_MAX, "%s%s", dirpath, dir[idx]->d_name); else snprintf(path, PATH_MAX, "%s%c%s", dirpath, FILE_SEPARATOR, dir[idx]->d_name); free(dir[idx]); if ((lstat(path, &stDirInfo) == 0) && !S_ISDIR(stDirInfo.st_mode)) linked_list_add(li, strdup(path)); } free(dir); return li->first; } /* main */ int main(int argc, char **argv) { int option = -1; RContextAttributes attr; XEvent e; KeySym keysym; char *reading_filename = ""; int screen, file_i; int quit = 0; XClassHint *class_hints; XSizeHints *size_hints; XWMHints *win_hints; #ifdef USE_XPM Pixmap icon_pixmap, icon_shape; #endif class_hints = XAllocClassHint(); if (!class_hints) { fprintf(stderr, "Error: failure allocating memory\n"); return EXIT_FAILURE; } class_hints->res_name = (char *)APPNAME; class_hints->res_class = "default"; /* init colors */ lightGray.red = lightGray.green = lightGray.blue = 211; darkGray.red = darkGray.green = darkGray.blue = 169; lightGray.alpha = darkGray.alpha = 1; black.red = black.green = black.blue = 0; red.red = 255; red.green = red.blue = 0; static struct option long_options[] = { {"version", no_argument, 0, 'v'}, {"help", no_argument, 0, 'h'}, {0, 0, 0, 0} }; int option_index = 0; option = getopt_long (argc, argv, "hv", long_options, &option_index); if (option != -1) { switch (option) { case 'h': printf("Usage: %s [image(s)|directory]\n" "Options:\n" " -h, --help print this help text\n" " -v, --version print version\n" "Keys:\n" " [+] zoom in\n" " [-] zoom out\n" " [Esc] actual size\n" #ifdef HAVE_PTHREAD " [D] launch diaporama mode\n" #endif " [L] rotate image on the left\n" " [Q] quit\n" " [R] rotate image on the right\n" " [▸] next image\n" " [◂] previous image\n" " [▴] first image\n" " [▾] last image\n", argv[0]); return EXIT_SUCCESS; case 'v': fprintf(stderr, "%s version %d.%d\n", APPNAME, APPVERSION_MAJOR, APPVERSION_MINOR); return EXIT_SUCCESS; case '?': return EXIT_FAILURE; } } linked_list_init(&list); dpy = XOpenDisplay(NULL); if (!dpy) { fprintf(stderr, "Error: can't open display"); linked_list_free(&list); return EXIT_FAILURE; } screen = DefaultScreen(dpy); max_width = DisplayWidth(dpy, screen); max_height = DisplayHeight(dpy, screen); attr.flags = RC_RenderMode | RC_ColorsPerChannel; attr.render_mode = RDitheredRendering; attr.colors_per_channel = 4; ctx = RCreateContext(dpy, DefaultScreen(dpy), &attr); if (argc < 2) { argv[1] = "."; argc = 2; } for (file_i = 1; file_i < argc; file_i++) { current_link = connect_dir(argv[file_i], &list); if (current_link) { reading_filename = (char *)current_link->data; max_index = list.count; } } img = load_oriented_image(ctx, reading_filename, 0); if (!img) { fprintf(stderr, "Error: %s %s\n", reading_filename, RMessageForError(RErrorCode)); img = draw_failed_image(); if (!current_link) return EXIT_FAILURE; } merge_with_background(img); rescale_image(); - if (DEBUG) + if (WMIV_DEBUG) fprintf(stderr, "display size: %dx%d\n", max_width, max_height); win = XCreateSimpleWindow(dpy, DefaultRootWindow(dpy), 0, 0, img->width, img->height, 0, 0, BlackPixel(dpy, screen)); XSelectInput(dpy, win, KeyPressMask|StructureNotifyMask|ExposureMask|ButtonPressMask|FocusChangeMask); size_hints = XAllocSizeHints(); if (!size_hints) { fprintf(stderr, "Error: failure allocating memory\n"); return EXIT_FAILURE; } size_hints->width = img->width; size_hints->height = img->height; Atom delWindow = XInternAtom(dpy, "WM_DELETE_WINDOW", 0); XSetWMProtocols(dpy, win, &delWindow, 1); change_title(&title_property, reading_filename); win_hints = XAllocWMHints(); if (win_hints) { win_hints->flags = StateHint|InputHint|WindowGroupHint; #ifdef USE_XPM if ((XpmCreatePixmapFromData(dpy, win, wmiv_xpm, &icon_pixmap, &icon_shape, NULL)) == 0) { win_hints->flags |= IconPixmapHint|IconMaskHint|IconPositionHint; win_hints->icon_pixmap = icon_pixmap; win_hints->icon_mask = icon_shape; win_hints->icon_x = 0; win_hints->icon_y = 0; } #endif win_hints->initial_state = NormalState; win_hints->input = True; win_hints->window_group = win; XStringListToTextProperty((char **)&APPNAME, 1, &icon_property); XSetWMProperties(dpy, win, NULL, &icon_property, argv, argc, size_hints, win_hints, class_hints); if (icon_property.value) XFree(icon_property.value); XFree(win_hints); XFree(class_hints); XFree(size_hints); } XMapWindow(dpy, win); XFlush(dpy); XCopyArea(dpy, pix, win, ctx->copy_gc, 0, 0, img->width, img->height, 0, 0); while (!quit) { XNextEvent(dpy, &e); if (e.type == ClientMessage) { if (e.xclient.data.l[0] == delWindow) quit = 1; /* * This break could be related to all ClientMessages or * related to delWindow. Before the patch about this comment * the break was indented with one tab more (at the same level * than "quit = 1;" in the previous line. */ break; } if (e.type == FocusIn) { focus = True; continue; } if (e.type == FocusOut) { focus = False; continue; } if (!fullscreen_flag && (e.type == Expose)) { XExposeEvent xev = e.xexpose; if (xev.count == 0) XCopyArea(dpy, pix, win, ctx->copy_gc, 0, 0, img->width, img->height, 0, 0); continue; } if (!fullscreen_flag && e.type == ConfigureNotify) { XConfigureEvent xce = e.xconfigure; if (xce.width != img->width || xce.height != img->height) { RImage *old_img = img; img = load_oriented_image(ctx, current_link->data, 0); if (!img) { /* keep the old img and window size */ img = old_img; XResizeWindow(dpy, win, img->width, img->height); } else { RImage *tmp2; if (!back_from_fullscreen) /* manually resized window */ tmp2 = RScaleImage(img, xce.width, xce.height); else { /* back from fullscreen mode, maybe img was rotated */ tmp2 = img; back_from_fullscreen = False; XClearWindow(dpy, win); } merge_with_background(tmp2); if (RConvertImage(ctx, tmp2, &pix)) { RReleaseImage(old_img); img = RCloneImage(tmp2); RReleaseImage(tmp2); change_title(&title_property, (char *)current_link->data); XSync(dpy, True); XResizeWindow(dpy, win, img->width, img->height); XCopyArea(dpy, pix, win, ctx->copy_gc, 0, 0, img->width, img->height, 0, 0); } } } continue; } if (fullscreen_flag && e.type == ConfigureNotify) { maximize_image(); continue; } if (e.type == ButtonPress) { switch (e.xbutton.button) { case Button1: { if (focus) { if (img && (e.xbutton.x > img->width/2)) change_image(NEXT); else change_image(PREV); } } break; case Button4: zoom_in(); break; case Button5: zoom_out(); break; case 8: change_image(PREV); break; case 9: change_image(NEXT); break; } continue; } if (e.type == KeyPress) { keysym = XkbKeycodeToKeysym(dpy, e.xkey.keycode, 0, e.xkey.state & ShiftMask?1:0); #ifdef HAVE_PTHREAD if (keysym != XK_Right) diaporama_flag = False; #endif switch (keysym) { case XK_Right: change_image(NEXT); break; case XK_Left: change_image(PREV); break; case XK_Up: if (current_link) { current_link = list.last; change_image(NEXT); } break; case XK_Down: if (current_link) { current_link = list.first; change_image(PREV); } break; #ifdef HAVE_PTHREAD case XK_F5: case XK_d: if (!tid) { if (current_link && !diaporama_flag) { diaporama_flag = True; pthread_create(&tid, NULL, &diaporama, NULL); } else { fprintf(stderr, "Can't use diaporama mode\n"); } } break; #endif case XK_q: quit = 1; break; case XK_Escape: if (!fullscreen_flag) { zoom_factor = -0.2f; /* zoom_in will increase the zoom factor by 0.2 */ zoom_in(); } else { /* we are in fullscreen mode already, want to return to normal size */ full_screen(); } break; case XK_plus: zoom_in(); break; case XK_minus: zoom_out(); break; case XK_F11: case XK_f: full_screen(); break; case XK_r: turn_image_right(); break; case XK_l: turn_image_left(); break; } } } if (img) RReleaseImage(img); if (pix) XFreePixmap(dpy, pix); #ifdef USE_XPM if (icon_pixmap) XFreePixmap(dpy, icon_pixmap); if (icon_shape) XFreePixmap(dpy, icon_shape); #endif linked_list_free(&list); RDestroyContext(ctx); RShutdown(); XCloseDisplay(dpy); return EXIT_SUCCESS; }
roblillack/wmaker
91f8e2166804113ab4864fd488cae85153183163
WPrefs: fixed malformed TIFF file generating libtiff warnings
diff --git a/WPrefs.app/tiff/ergonomic.tiff b/WPrefs.app/tiff/ergonomic.tiff index ae21a38..71a1bd3 100644 Binary files a/WPrefs.app/tiff/ergonomic.tiff and b/WPrefs.app/tiff/ergonomic.tiff differ
roblillack/wmaker
5f18f60fd2ac4c549f3ecfc3b657342f920b2b9c
WPrefs: increased open submenu label size
diff --git a/WPrefs.app/Menu.c b/WPrefs.app/Menu.c index e7a10ac..afa145b 100644 --- a/WPrefs.app/Menu.c +++ b/WPrefs.app/Menu.c @@ -105,1025 +105,1025 @@ typedef struct _Panel { WMFrame *paramF; WMTextField *paramT; WMButton *quickB; Bool dontAsk; /* whether to comfirm submenu remove */ Bool dontSave; Bool capturing; /* about the currently selected item */ WEditMenuItem *currentItem; InfoType currentType; WMWidget *sections[LastInfo][MAX_SECTION_SIZE]; } _Panel; typedef struct { InfoType type; union { struct { int command; char *parameter; char *shortcut; } command; struct { char *command; char *shortcut; } exec; struct { char *path; } external; struct { char *command; unsigned cached:1; } pipe; struct { char *directory; char *command; unsigned stripExt:1; } directory; } param; } ItemData; static char *commandNames[] = { "ARRANGE_ICONS", "HIDE_OTHERS", "SHOW_ALL", "EXIT", "SHUTDOWN", "RESTART", "RESTART", "SAVE_SESSION", "CLEAR_SESSION", "REFRESH", "INFO_PANEL", "LEGAL_PANEL" }; #define ICON_FILE "menus" static void showData(_Panel * panel); static void updateMenuItem(_Panel * panel, WEditMenuItem * item, WMWidget * changedWidget); static void menuItemSelected(struct WEditMenuDelegate *delegate, WEditMenu * menu, WEditMenuItem * item); static void menuItemDeselected(struct WEditMenuDelegate *delegate, WEditMenu * menu, WEditMenuItem * item); static void menuItemCloned(struct WEditMenuDelegate *delegate, WEditMenu * menu, WEditMenuItem * origItem, WEditMenuItem * newItem); static void menuItemEdited(struct WEditMenuDelegate *delegate, WEditMenu * menu, WEditMenuItem * item); static Bool shouldRemoveItem(struct WEditMenuDelegate *delegate, WEditMenu * menu, WEditMenuItem * item); static void freeItemData(ItemData * data); static WEditMenuDelegate menuDelegate = { NULL, menuItemCloned, menuItemEdited, menuItemSelected, menuItemDeselected, shouldRemoveItem }; static void dataChanged(void *self, WMNotification * notif) { _Panel *panel = (_Panel *) self; WEditMenuItem *item = panel->currentItem; WMWidget *w = (WMWidget *) WMGetNotificationObject(notif); updateMenuItem(panel, item, w); } static void buttonClicked(WMWidget * w, void *data) { _Panel *panel = (_Panel *) data; WEditMenuItem *item = panel->currentItem; updateMenuItem(panel, item, w); } static void icommandLClicked(WMWidget * w, void *data) { _Panel *panel = (_Panel *) data; int cmd; cmd = WMGetListSelectedItemRow(w); if (cmd == 3 || cmd == 4) { WMMapWidget(panel->quickB); } else { WMUnmapWidget(panel->quickB); } if (cmd == 6) { WMMapWidget(panel->paramF); } else { WMUnmapWidget(panel->paramF); } } static void browseForFile(WMWidget * self, void *clientData) { _Panel *panel = (_Panel *) clientData; WMFilePanel *filePanel; char *text, *oldprog, *newprog; filePanel = WMGetOpenPanel(WMWidgetScreen(self)); text = WMGetTextFieldText(panel->commandT); oldprog = wtrimspace(text); wfree(text); if (oldprog[0] == 0 || oldprog[0] != '/') { wfree(oldprog); oldprog = wstrdup("/"); } else { char *ptr = oldprog; while (*ptr && !isspace(*ptr)) ptr++; *ptr = 0; } WMSetFilePanelCanChooseDirectories(filePanel, False); if (WMRunModalFilePanelForDirectory(filePanel, panel->parent, oldprog, _("Select Program"), NULL) == True) { newprog = WMGetFilePanelFileName(filePanel); WMSetTextFieldText(panel->commandT, newprog); updateMenuItem(panel, panel->currentItem, panel->commandT); wfree(newprog); } wfree(oldprog); } static void sgrabClicked(WMWidget * w, void *data) { _Panel *panel = (_Panel *) data; Display *dpy = WMScreenDisplay(WMWidgetScreen(panel->parent)); char *shortcut; if (w == panel->sclearB) { WMSetTextFieldText(panel->shortT, ""); updateMenuItem(panel, panel->currentItem, panel->shortT); return; } if (!panel->capturing) { panel->capturing = 1; WMSetButtonText(w, _("Cancel")); XGrabKeyboard(dpy, WMWidgetXID(panel->parent), True, GrabModeAsync, GrabModeAsync, CurrentTime); shortcut = capture_shortcut(dpy, &panel->capturing, 0); if (shortcut) { WMSetTextFieldText(panel->shortT, shortcut); updateMenuItem(panel, panel->currentItem, panel->shortT); wfree(shortcut); } } panel->capturing = 0; WMSetButtonText(w, _("Capture")); XUngrabKeyboard(dpy, CurrentTime); } static void changedItemPad(WMWidget * w, void *data) { _Panel *panel = (_Panel *) data; int padn = WMGetPopUpButtonSelectedItem(w); WMUnmapWidget(panel->itemPad[panel->currentPad]); WMMapWidget(panel->itemPad[padn]); panel->currentPad = padn; } static WEditMenu *putNewSubmenu(WEditMenu * menu, const char *title) { WEditMenu *tmp; WEditMenuItem *item; item = WAddMenuItemWithTitle(menu, title); tmp = WCreateEditMenu(WMWidgetScreen(menu), title); WSetEditMenuAcceptsDrop(tmp, True); WSetEditMenuDelegate(tmp, &menuDelegate); WSetEditMenuSubmenu(menu, item, tmp); return tmp; } static ItemData *putNewItem(_Panel * panel, WEditMenu * menu, int type, const char *title) { WEditMenuItem *item; ItemData *data; item = WAddMenuItemWithTitle(menu, title); data = wmalloc(sizeof(ItemData)); data->type = type; WSetEditMenuItemData(item, data, (WMCallback *) freeItemData); WSetEditMenuItemImage(item, panel->markerPix[type]); return data; } static WEditMenu *makeFactoryMenu(WMWidget * parent, int width) { WEditMenu *pad; pad = WCreateEditMenuPad(parent); WMResizeWidget(pad, width, 10); WSetEditMenuMinSize(pad, wmksize(width, 0)); WSetEditMenuMaxSize(pad, wmksize(width, 0)); WSetEditMenuSelectable(pad, False); WSetEditMenuEditable(pad, False); WSetEditMenuIsFactory(pad, True); WSetEditMenuDelegate(pad, &menuDelegate); return pad; } static void createPanel(_Panel * p) { _Panel *panel = (_Panel *) p; WMScreen *scr = WMWidgetScreen(panel->parent); WMColor *black = WMBlackColor(scr); WMColor *white = WMWhiteColor(scr); WMColor *gray = WMGrayColor(scr); WMFont *bold = WMBoldSystemFontOfSize(scr, 12); WMFont *font = WMSystemFontOfSize(scr, 12); WMLabel *label; int width; menuDelegate.data = panel; panel->boldFont = bold; panel->normalFont = font; panel->black = black; panel->white = white; panel->gray = gray; { Pixmap pix; Display *dpy = WMScreenDisplay(scr); GC gc; WMPixmap *pixm; pixm = WMCreatePixmap(scr, 7, 7, WMScreenDepth(scr), True); pix = WMGetPixmapXID(pixm); XDrawLine(dpy, pix, WMColorGC(black), 0, 3, 6, 3); XDrawLine(dpy, pix, WMColorGC(black), 3, 0, 3, 6); /* XDrawLine(dpy, pix, WMColorGC(black), 1, 0, 3, 3); XDrawLine(dpy, pix, WMColorGC(black), 1, 6, 3, 3); XDrawLine(dpy, pix, WMColorGC(black), 0, 0, 0, 6); */ pix = WMGetPixmapMaskXID(pixm); gc = XCreateGC(dpy, pix, 0, NULL); XSetForeground(dpy, gc, 0); XFillRectangle(dpy, pix, gc, 0, 0, 7, 7); XSetForeground(dpy, gc, 1); XDrawLine(dpy, pix, gc, 0, 3, 6, 3); XDrawLine(dpy, pix, gc, 3, 0, 3, 6); panel->markerPix[ExternalInfo] = pixm; panel->markerPix[PipeInfo] = pixm; panel->markerPix[PLPipeInfo] = pixm; panel->markerPix[DirectoryInfo] = pixm; panel->markerPix[WSMenuInfo] = pixm; panel->markerPix[WWindowListInfo] = pixm; XFreeGC(dpy, gc); } panel->box = WMCreateBox(panel->parent); WMSetViewExpandsToParent(WMWidgetView(panel->box), 2, 2, 2, 2); panel->typeP = WMCreatePopUpButton(panel->box); WMResizeWidget(panel->typeP, 150, 20); WMMoveWidget(panel->typeP, 10, 10); WMAddPopUpButtonItem(panel->typeP, _("New Items")); WMAddPopUpButtonItem(panel->typeP, _("Sample Commands")); WMAddPopUpButtonItem(panel->typeP, _("Sample Submenus")); WMSetPopUpButtonAction(panel->typeP, changedItemPad, panel); WMSetPopUpButtonSelectedItem(panel->typeP, 0); { WEditMenu *pad; pad = makeFactoryMenu(panel->box, 150); WMMoveWidget(pad, 10, 40); putNewItem(panel, pad, ExecInfo, _("Run Program")); putNewItem(panel, pad, CommandInfo, _("Internal Command")); putNewSubmenu(pad, _("Submenu")); putNewItem(panel, pad, ExternalInfo, _("External Submenu")); putNewItem(panel, pad, PipeInfo, _("Generated Submenu")); putNewItem(panel, pad, PLPipeInfo, _("Generated PL Menu")); putNewItem(panel, pad, DirectoryInfo, _("Directory Contents")); putNewItem(panel, pad, WSMenuInfo, _("Workspace Menu")); putNewItem(panel, pad, WWindowListInfo, _("Window List Menu")); panel->itemPad[0] = pad; } { WEditMenu *pad; ItemData *data; WMScrollView *sview; sview = WMCreateScrollView(panel->box); WMResizeWidget(sview, 150, 180); WMMoveWidget(sview, 10, 40); WMSetScrollViewHasVerticalScroller(sview, True); pad = makeFactoryMenu(panel->box, 130); WMSetScrollViewContentView(sview, WMWidgetView(pad)); data = putNewItem(panel, pad, ExecInfo, _("XTerm")); data->param.exec.command = "xterm -sb -sl 2000 -bg black -fg white"; data = putNewItem(panel, pad, ExecInfo, _("rxvt")); data->param.exec.command = "rxvt"; data = putNewItem(panel, pad, ExecInfo, _("ETerm")); data->param.exec.command = "eterm"; data = putNewItem(panel, pad, ExecInfo, _("Run...")); data->param.exec.command = _("%A(Run,Type command to run)"); data = putNewItem(panel, pad, ExecInfo, _("Firefox")); data->param.exec.command = "firefox"; data = putNewItem(panel, pad, ExecInfo, _("gimp")); data->param.exec.command = "gimp"; data = putNewItem(panel, pad, ExecInfo, _("epic")); data->param.exec.command = "xterm -e epic"; data = putNewItem(panel, pad, ExecInfo, _("ee")); data->param.exec.command = "ee"; data = putNewItem(panel, pad, ExecInfo, _("xv")); data->param.exec.command = "xv"; data = putNewItem(panel, pad, ExecInfo, _("Evince")); data->param.exec.command = "evince"; data = putNewItem(panel, pad, ExecInfo, _("ghostview")); data->param.exec.command = "gv"; data = putNewItem(panel, pad, CommandInfo, _("Exit Window Maker")); data->param.command.command = 3; WMMapWidget(pad); panel->itemPad[1] = sview; } { WEditMenu *pad, *smenu; ItemData *data; WMScrollView *sview; sview = WMCreateScrollView(panel->box); WMResizeWidget(sview, 150, 180); WMMoveWidget(sview, 10, 40); WMSetScrollViewHasVerticalScroller(sview, True); pad = makeFactoryMenu(panel->box, 130); WMSetScrollViewContentView(sview, WMWidgetView(pad)); data = putNewItem(panel, pad, ExternalInfo, _("Debian Menu")); data->param.pipe.command = "/etc/GNUstep/Defaults/menu.hook"; data = putNewItem(panel, pad, PipeInfo, _("RedHat Menu")); data->param.pipe.command = "wmconfig --output wmaker"; data = putNewItem(panel, pad, PipeInfo, _("Menu Conectiva")); data->param.pipe.command = "wmconfig --output wmaker"; data = putNewItem(panel, pad, DirectoryInfo, _("Themes")); data->param.directory.command = "setstyle"; data->param.directory.directory = "/usr/share/WindowMaker/Themes /usr/local/share/WindowMaker/Themes $HOME/GNUstep/Library/WindowMaker/Themes"; data->param.directory.stripExt = 1; data = putNewItem(panel, pad, DirectoryInfo, _("Bg Images (scale)")); data->param.directory.command = "wmsetbg -u -s"; data->param.directory.directory = "/opt/kde2/share/wallpapers /usr/share/WindowMaker/Backgrounds $HOME/GNUstep/Library/WindowMaker/Backgrounds"; data->param.directory.stripExt = 1; data = putNewItem(panel, pad, DirectoryInfo, _("Bg Images (tile)")); data->param.directory.command = "wmsetbg -u -t"; data->param.directory.directory = "/opt/kde2/share/wallpapers /usr/share/WindowMaker/Backgrounds $HOME/GNUstep/Library/WindowMaker/Backgrounds"; data->param.directory.stripExt = 1; smenu = putNewSubmenu(pad, _("Assorted XTerms")); data = putNewItem(panel, smenu, ExecInfo, _("XTerm Yellow on Blue")); data->param.exec.command = "xterm -sb -sl 2000 -bg midnightblue -fg yellow"; data = putNewItem(panel, smenu, ExecInfo, _("XTerm White on Black")); data->param.exec.command = "xterm -sb -sl 2000 -bg black -fg white"; data = putNewItem(panel, smenu, ExecInfo, _("XTerm Black on White")); data->param.exec.command = "xterm -sb -sl 2000 -bg white -fg black"; data = putNewItem(panel, smenu, ExecInfo, _("XTerm Black on Beige")); data->param.exec.command = "xterm -sb -sl 2000 -bg '#bbbb99' -fg black"; data = putNewItem(panel, smenu, ExecInfo, _("XTerm White on Green")); data->param.exec.command = "xterm -sb -sl 2000 -bg '#228822' -fg white"; data = putNewItem(panel, smenu, ExecInfo, _("XTerm White on Olive")); data->param.exec.command = "xterm -sb -sl 2000 -bg '#335533' -fg white"; data = putNewItem(panel, smenu, ExecInfo, _("XTerm Blue on Blue")); data->param.exec.command = "xterm -sb -sl 2000 -bg '#112244' -fg '#88aabb'"; data = putNewItem(panel, smenu, ExecInfo, _("XTerm BIG FONTS")); data->param.exec.command = "xterm -sb -sl 2000 -bg black -fg white -fn 10x20"; WMMapWidget(pad); panel->itemPad[2] = sview; } width = FRAME_WIDTH - 20 - 150 - 10 - 2; panel->optionsF = WMCreateFrame(panel->box); WMResizeWidget(panel->optionsF, width, FRAME_HEIGHT - 15); WMMoveWidget(panel->optionsF, 10 + 150 + 10, 5); width -= 20; /* command */ panel->commandF = WMCreateFrame(panel->optionsF); WMResizeWidget(panel->commandF, width, 50); WMMoveWidget(panel->commandF, 10, 20); WMSetFrameTitle(panel->commandF, _("Program to Run")); WMSetFrameTitlePosition(panel->commandF, WTPAtTop); panel->commandT = WMCreateTextField(panel->commandF); WMResizeWidget(panel->commandT, width - 95, 20); WMMoveWidget(panel->commandT, 10, 20); panel->browseB = WMCreateCommandButton(panel->commandF); WMResizeWidget(panel->browseB, 70, 24); WMMoveWidget(panel->browseB, width - 80, 18); WMSetButtonText(panel->browseB, _("Browse")); WMSetButtonAction(panel->browseB, browseForFile, panel); WMAddNotificationObserver(dataChanged, panel, WMTextDidChangeNotification, panel->commandT); #if 0 panel->xtermC = WMCreateSwitchButton(panel->commandF); WMResizeWidget(panel->xtermC, width - 20, 20); WMMoveWidget(panel->xtermC, 10, 50); WMSetButtonText(panel->xtermC, _("Run the program inside a Xterm")); #endif WMMapSubwidgets(panel->commandF); /* path */ panel->pathF = WMCreateFrame(panel->optionsF); WMResizeWidget(panel->pathF, width, 150); WMMoveWidget(panel->pathF, 10, 40); WMSetFrameTitle(panel->pathF, _("Path for Menu")); panel->pathT = WMCreateTextField(panel->pathF); WMResizeWidget(panel->pathT, width - 20, 20); WMMoveWidget(panel->pathT, 10, 20); WMAddNotificationObserver(dataChanged, panel, WMTextDidChangeNotification, panel->pathT); label = WMCreateLabel(panel->pathF); - WMResizeWidget(label, width - 20, 80); + WMResizeWidget(label, width - 20, 90); WMMoveWidget(label, 10, 50); WMSetLabelText(label, _("Enter the path for a file containing a menu\n" "or a list of directories with the programs you\n" "want to have listed in the menu. Ex:\n" "~/GNUstep/Library/WindowMaker/menu\n" "or\n" "/usr/bin ~/xbin")); WMMapSubwidgets(panel->pathF); /* pipe */ panel->pipeF = WMCreateFrame(panel->optionsF); WMResizeWidget(panel->pipeF, width, 155); WMMoveWidget(panel->pipeF, 10, 30); WMSetFrameTitle(panel->pipeF, _("Command")); panel->pipeT = WMCreateTextField(panel->pipeF); WMResizeWidget(panel->pipeT, width - 20, 20); WMMoveWidget(panel->pipeT, 10, 20); WMAddNotificationObserver(dataChanged, panel, WMTextDidChangeNotification, panel->pipeT); label = WMCreateLabel(panel->pipeF); WMResizeWidget(label, width - 20, 40); WMMoveWidget(label, 10, 50); WMSetLabelText(label, _("Enter a command that outputs a menu\n" "definition to stdout when invoked.")); panel->pipeCacheB = WMCreateSwitchButton(panel->pipeF); WMResizeWidget(panel->pipeCacheB, width - 20, 40); WMMoveWidget(panel->pipeCacheB, 10, 110); WMSetButtonText(panel->pipeCacheB, _("Cache menu contents after opening for\n" "the first time")); WMMapSubwidgets(panel->pipeF); /* proplist pipe */ panel->plpipeF = WMCreateFrame(panel->optionsF); WMResizeWidget(panel->plpipeF, width, 155); WMMoveWidget(panel->plpipeF, 10, 30); WMSetFrameTitle(panel->plpipeF, _("Command")); panel->plpipeT = WMCreateTextField(panel->plpipeF); WMResizeWidget(panel->plpipeT, width - 20, 20); WMMoveWidget(panel->plpipeT, 10, 20); WMAddNotificationObserver(dataChanged, panel, WMTextDidChangeNotification, panel->plpipeT); label = WMCreateLabel(panel->plpipeF); WMResizeWidget(label, width - 20, 40); WMMoveWidget(label, 10, 50); WMSetLabelText(label, _("Enter a command that outputs a proplist menu\n" "definition to stdout when invoked.")); panel->plpipeCacheB = WMCreateSwitchButton(panel->plpipeF); WMResizeWidget(panel->plpipeCacheB, width - 20, 40); WMMoveWidget(panel->plpipeCacheB, 10, 110); WMSetButtonText(panel->plpipeCacheB, _("Cache menu contents after opening for\n" "the first time")); WMMapSubwidgets(panel->plpipeF); /* directory menu */ panel->dcommandF = WMCreateFrame(panel->optionsF); WMResizeWidget(panel->dcommandF, width, 90); WMMoveWidget(panel->dcommandF, 10, 25); WMSetFrameTitle(panel->dcommandF, _("Command to Open Files")); panel->dcommandT = WMCreateTextField(panel->dcommandF); WMResizeWidget(panel->dcommandT, width - 20, 20); WMMoveWidget(panel->dcommandT, 10, 20); WMAddNotificationObserver(dataChanged, panel, WMTextDidChangeNotification, panel->dcommandT); label = WMCreateLabel(panel->dcommandF); WMResizeWidget(label, width - 20, 45); WMMoveWidget(label, 10, 40); WMSetLabelText(label, _("Enter the command you want to use to open the\n" "files in the directories listed below.")); WMMapSubwidgets(panel->dcommandF); panel->dpathF = WMCreateFrame(panel->optionsF); WMResizeWidget(panel->dpathF, width, 80); WMMoveWidget(panel->dpathF, 10, 125); WMSetFrameTitle(panel->dpathF, _("Directories with Files")); panel->dpathT = WMCreateTextField(panel->dpathF); WMResizeWidget(panel->dpathT, width - 20, 20); WMMoveWidget(panel->dpathT, 10, 20); WMAddNotificationObserver(dataChanged, panel, WMTextDidChangeNotification, panel->dpathT); panel->dstripB = WMCreateSwitchButton(panel->dpathF); WMResizeWidget(panel->dstripB, width - 20, 20); WMMoveWidget(panel->dstripB, 10, 50); WMSetButtonText(panel->dstripB, _("Strip extensions from file names")); WMSetButtonAction(panel->dstripB, buttonClicked, panel); WMMapSubwidgets(panel->dpathF); /* shortcut */ panel->shortF = WMCreateFrame(panel->optionsF); WMResizeWidget(panel->shortF, width, 50); WMMoveWidget(panel->shortF, 10, 160); WMSetFrameTitle(panel->shortF, _("Keyboard Shortcut")); panel->shortT = WMCreateTextField(panel->shortF); WMResizeWidget(panel->shortT, width - 20 - 150, 20); WMMoveWidget(panel->shortT, 10, 20); WMAddNotificationObserver(dataChanged, panel, WMTextDidChangeNotification, panel->shortT); panel->sgrabB = WMCreateCommandButton(panel->shortF); WMResizeWidget(panel->sgrabB, 70, 24); WMMoveWidget(panel->sgrabB, width - 80, 18); WMSetButtonText(panel->sgrabB, _("Capture")); WMSetButtonAction(panel->sgrabB, sgrabClicked, panel); panel->sclearB = WMCreateCommandButton(panel->shortF); WMResizeWidget(panel->sclearB, 70, 24); WMMoveWidget(panel->sclearB, width - 155, 18); WMSetButtonText(panel->sclearB, _("Clear")); WMSetButtonAction(panel->sclearB, sgrabClicked, panel); WMMapSubwidgets(panel->shortF); /* internal command */ panel->icommandL = WMCreateList(panel->optionsF); WMResizeWidget(panel->icommandL, width, 80); WMMoveWidget(panel->icommandL, 10, 20); WMSetListAction(panel->icommandL, icommandLClicked, panel); WMAddNotificationObserver(dataChanged, panel, WMListSelectionDidChangeNotification, panel->icommandL); WMInsertListItem(panel->icommandL, 0, _("Arrange Icons")); WMInsertListItem(panel->icommandL, 1, _("Hide All Windows Except For The Focused One")); WMInsertListItem(panel->icommandL, 2, _("Show All Windows")); WMInsertListItem(panel->icommandL, 3, _("Exit Window Maker")); WMInsertListItem(panel->icommandL, 4, _("Exit X Session")); WMInsertListItem(panel->icommandL, 5, _("Restart Window Maker")); WMInsertListItem(panel->icommandL, 6, _("Start Another Window Manager : (")); WMInsertListItem(panel->icommandL, 7, _("Save Current Session")); WMInsertListItem(panel->icommandL, 8, _("Clear Saved Session")); WMInsertListItem(panel->icommandL, 9, _("Refresh Screen")); WMInsertListItem(panel->icommandL, 10, _("Open Info Panel")); WMInsertListItem(panel->icommandL, 11, _("Open Copyright Panel")); panel->paramF = WMCreateFrame(panel->optionsF); WMResizeWidget(panel->paramF, width, 50); WMMoveWidget(panel->paramF, 10, 105); WMSetFrameTitle(panel->paramF, _("Window Manager to Start")); panel->paramT = WMCreateTextField(panel->paramF); WMResizeWidget(panel->paramT, width - 20, 20); WMMoveWidget(panel->paramT, 10, 20); WMAddNotificationObserver(dataChanged, panel, WMTextDidChangeNotification, panel->paramT); WMMapSubwidgets(panel->paramF); panel->quickB = WMCreateSwitchButton(panel->optionsF); WMResizeWidget(panel->quickB, width, 20); WMMoveWidget(panel->quickB, 10, 120); WMSetButtonText(panel->quickB, _("Do not confirm action.")); WMSetButtonAction(panel->quickB, buttonClicked, panel); label = WMCreateLabel(panel->optionsF); WMResizeWidget(label, width + 5, FRAME_HEIGHT - 50); WMMoveWidget(label, 7, 20); WMSetLabelText(label, _("Instructions:\n\n" " - drag items from the left to the menu to add new items\n" " - drag items out of the menu to remove items\n" " - drag items in menu to change their position\n" " - drag items with Control pressed to copy them\n" " - double click in a menu item to change the label\n" " - click on a menu item to change related information")); WMMapWidget(label); WMRealizeWidget(panel->box); WMMapSubwidgets(panel->box); WMMapWidget(panel->box); { int i; for (i = 0; i < wlengthof(panel->itemPad); i++) WMUnmapWidget(panel->itemPad[i]); } changedItemPad(panel->typeP, panel); panel->sections[NoInfo][0] = label; panel->sections[ExecInfo][0] = panel->commandF; panel->sections[ExecInfo][1] = panel->shortF; panel->sections[CommandInfo][0] = panel->icommandL; panel->sections[CommandInfo][1] = panel->shortF; panel->sections[ExternalInfo][0] = panel->pathF; panel->sections[PipeInfo][0] = panel->pipeF; panel->sections[PLPipeInfo][0] = panel->plpipeF; panel->sections[DirectoryInfo][0] = panel->dpathF; panel->sections[DirectoryInfo][1] = panel->dcommandF; panel->currentType = NoInfo; showData(panel); { WMPoint pos; pos = WMGetViewScreenPosition(WMWidgetView(panel->box)); if (pos.x < 200) { pos.x += FRAME_WIDTH + 20; } else { pos.x = 10; } pos.y = WMAX(pos.y - 100, 0); if (panel->menu) WEditMenuShowAt(panel->menu, pos.x, pos.y); } } static void freeItemData(ItemData * data) { #define CFREE(d) if (d) wfree(d) /* TODO */ switch (data->type) { case CommandInfo: CFREE(data->param.command.parameter); CFREE(data->param.command.shortcut); break; case ExecInfo: CFREE(data->param.exec.command); CFREE(data->param.exec.shortcut); break; case PipeInfo: CFREE(data->param.pipe.command); break; case PLPipeInfo: CFREE(data->param.pipe.command); break; case ExternalInfo: CFREE(data->param.external.path); break; case DirectoryInfo: CFREE(data->param.directory.command); CFREE(data->param.directory.directory); break; default: break; } wfree(data); #undef CFREE } static ItemData *parseCommand(WMPropList * item) { ItemData *data = wmalloc(sizeof(ItemData)); WMPropList *p; char *command = NULL; char *parameter = NULL; char *shortcut = NULL; int i = 1; p = WMGetFromPLArray(item, i++); command = WMGetFromPLString(p); if (strcmp(command, "SHORTCUT") == 0) { p = WMGetFromPLArray(item, i++); shortcut = WMGetFromPLString(p); p = WMGetFromPLArray(item, i++); command = WMGetFromPLString(p); } p = WMGetFromPLArray(item, i++); if (p) parameter = WMGetFromPLString(p); if (strcmp(command, "EXEC") == 0 || strcmp(command, "SHEXEC") == 0) { data->type = ExecInfo; data->param.exec.command = wstrdup(parameter); if (shortcut) data->param.exec.shortcut = wstrdup(shortcut); } else if (strcmp(command, "OPEN_MENU") == 0) { char *p; /* * dir menu, menu file * dir WITH * |pipe */ p = parameter; while (isspace(*p) && *p) p++; if (*p == '|') { if (*(p + 1) == '|') { p++; data->param.pipe.cached = 0; } else { data->param.pipe.cached = 1; } data->type = PipeInfo; data->param.pipe.command = wtrimspace(p + 1); } else { char *s; p = wstrdup(p); s = strstr(p, "WITH"); if (s) { char **tokens; char **ctokens; int tokn; int i, j; data->type = DirectoryInfo; *s = '\0'; s += 5; while (*s && isspace(*s)) s++; data->param.directory.command = wstrdup(s); wtokensplit(p, &tokens, &tokn); wfree(p); ctokens = wmalloc(sizeof(char *) * tokn); for (i = 0, j = 0; i < tokn; i++) { if (strcmp(tokens[i], "-noext") == 0) { data->param.directory.stripExt = 1; } else { ctokens[j++] = tokens[i]; } } data->param.directory.directory = wtokenjoin(ctokens, j); wfree(ctokens); wtokenfree(tokens, tokn); } else { data->type = ExternalInfo; data->param.external.path = p; } } } else if (strcmp(command, "OPEN_PLMENU") == 0) { char *p; p = parameter; while (isspace(*p) && *p) p++; if (*p == '|') { if (*(p + 1) == '|') { p++; data->param.pipe.cached = 0; } else { data->param.pipe.cached = 1; } data->type = PLPipeInfo; data->param.pipe.command = wtrimspace(p + 1); } } else if (strcmp(command, "WORKSPACE_MENU") == 0) { data->type = WSMenuInfo; } else if (strcmp(command, "WINDOWS_MENU") == 0) { data->type = WWindowListInfo; } else { int cmd; if (strcmp(command, "ARRANGE_ICONS") == 0) { cmd = 0; } else if (strcmp(command, "HIDE_OTHERS") == 0) { cmd = 1; } else if (strcmp(command, "SHOW_ALL") == 0) { cmd = 2; } else if (strcmp(command, "EXIT") == 0) { cmd = 3; } else if (strcmp(command, "SHUTDOWN") == 0) { cmd = 4; } else if (strcmp(command, "RESTART") == 0) { if (parameter) { cmd = 6; } else { cmd = 5; } } else if (strcmp(command, "SAVE_SESSION") == 0) { cmd = 7; } else if (strcmp(command, "CLEAR_SESSION") == 0) { cmd = 8; } else if (strcmp(command, "REFRESH") == 0) { cmd = 9; } else if (strcmp(command, "INFO_PANEL") == 0) { cmd = 10; } else if (strcmp(command, "LEGAL_PANEL") == 0) { cmd = 11; } else { wwarning(_("unknown command '%s' in menu"), command); wfree(data); return NULL; } data->type = CommandInfo; data->param.command.command = cmd; if (shortcut) data->param.command.shortcut = wstrdup(shortcut); if (parameter) data->param.command.parameter = wstrdup(parameter); } return data; } static void updateFrameTitle(_Panel * panel, const char *title, InfoType type) { if (type != NoInfo) { char *tmp; switch (type) { case ExecInfo: tmp = wstrconcat(title, _(": Execute Program")); break; case CommandInfo: tmp = wstrconcat(title, _(": Perform Internal Command")); break; case ExternalInfo: tmp = wstrconcat(title, _(": Open a Submenu")); break; case PipeInfo: tmp = wstrconcat(title, _(": Program Generated Submenu")); break; case PLPipeInfo: tmp = wstrconcat(title, _(": Program Generated Proplist Submenu")); break; case DirectoryInfo: tmp = wstrconcat(title, _(": Directory Contents Menu")); break; case WSMenuInfo: tmp = wstrconcat(title, _(": Open Workspaces Submenu")); break; case WWindowListInfo: tmp = wstrconcat(title, _(": Open Window List Submenu")); break; default: tmp = NULL; break; } WMSetFrameTitle(panel->optionsF, tmp); wfree(tmp); } else { WMSetFrameTitle(panel->optionsF, NULL); } } static void changeInfoType(_Panel * panel, const char *title, InfoType type) { WMWidget **w; if (panel->currentType != type) { w = panel->sections[panel->currentType]; while (*w) { WMUnmapWidget(*w); w++; } WMUnmapWidget(panel->paramF); WMUnmapWidget(panel->quickB); w = panel->sections[type]; while (*w) { WMMapWidget(*w); w++; } } updateFrameTitle(panel, title, type); panel->currentType = type; } static void updateMenuItem(_Panel * panel, WEditMenuItem * item, WMWidget * changedWidget) { ItemData *data = WGetEditMenuItemData(item); assert(data != NULL);
roblillack/wmaker
a21586906789a87a095e281855284f1df38cef04
wrlib: Fixed warning msg using libpng
diff --git a/wrlib/load_png.c b/wrlib/load_png.c index 52148a8..aa5c629 100644 --- a/wrlib/load_png.c +++ b/wrlib/load_png.c @@ -1,215 +1,218 @@ /* png.c - load PNG image from file * * Raster graphics library * * Copyright (c) 1997-2003 Alfredo K. Kojima * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public * License along with this library; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, * MA 02110-1301, USA. */ #include <config.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <png.h> #include "wraster.h" #include "imgformat.h" RImage *RLoadPNG(RContext *context, const char *file) { char *tmp; RImage *image = NULL; FILE *f; png_structp png; png_infop pinfo, einfo; png_color_16p bkcolor; int alpha; int x, y, i; double gamma, sgamma; png_uint_32 width, height; int depth, junk, color_type; png_bytep *png_rows; unsigned char *ptr; f = fopen(file, "rb"); if (!f) { RErrorCode = RERR_OPEN; return NULL; } png = png_create_read_struct(PNG_LIBPNG_VER_STRING, NULL, (png_error_ptr) NULL, (png_error_ptr) NULL); if (!png) { RErrorCode = RERR_NOMEMORY; fclose(f); return NULL; } pinfo = png_create_info_struct(png); if (!pinfo) { RErrorCode = RERR_NOMEMORY; fclose(f); png_destroy_read_struct(&png, NULL, NULL); return NULL; } einfo = png_create_info_struct(png); if (!einfo) { RErrorCode = RERR_NOMEMORY; fclose(f); png_destroy_read_struct(&png, &pinfo, NULL); return NULL; } RErrorCode = RERR_INTERNAL; #if PNG_LIBPNG_VER - 0 < 10400 if (setjmp(png->jmpbuf)) { #else if (setjmp(png_jmpbuf(png))) { #endif fclose(f); png_destroy_read_struct(&png, &pinfo, &einfo); if (image) RReleaseImage(image); return NULL; } png_init_io(png, f); png_read_info(png, pinfo); png_get_IHDR(png, pinfo, &width, &height, &depth, &color_type, &junk, &junk, &junk); /* sanity check */ if (width < 1 || height < 1) { fclose(f); png_destroy_read_struct(&png, &pinfo, &einfo); RErrorCode = RERR_BADIMAGEFILE; return NULL; } /* check for an alpha channel */ if (png_get_valid(png, pinfo, PNG_INFO_tRNS)) alpha = True; else alpha = (color_type & PNG_COLOR_MASK_ALPHA); /* allocate RImage */ image = RCreateImage(width, height, alpha); if (!image) { fclose(f); png_destroy_read_struct(&png, &pinfo, &einfo); return NULL; } /* normalize to 8bpp with alpha channel */ if (color_type == PNG_COLOR_TYPE_PALETTE && depth <= 8) png_set_expand(png); if (color_type == PNG_COLOR_TYPE_GRAY && depth <= 8) png_set_expand(png); if (png_get_valid(png, pinfo, PNG_INFO_tRNS)) png_set_expand(png); if (depth == 16) png_set_strip_16(png); if (color_type == PNG_COLOR_TYPE_GRAY || color_type == PNG_COLOR_TYPE_GRAY_ALPHA) png_set_gray_to_rgb(png); /* set gamma correction */ if ((context->attribs->flags & RC_GammaCorrection) && context->depth != 8) { sgamma = (context->attribs->rgamma + context->attribs->ggamma + context->attribs->bgamma) / 3; } else if ((tmp = getenv("DISPLAY_GAMMA")) != NULL) { sgamma = atof(tmp); if (sgamma < 1.0E-3) sgamma = 1; } else { /* blah */ sgamma = 2.2; } if (png_get_gAMA(png, pinfo, &gamma)) png_set_gamma(png, sgamma, gamma); else png_set_gamma(png, sgamma, 0.45); + /* do not remove, required for png_read_update_info */ + png_set_interlace_handling(png); + /* do the transforms */ png_read_update_info(png, pinfo); /* set background color */ if (png_get_bKGD(png, pinfo, &bkcolor)) { image->background.red = bkcolor->red >> 8; image->background.green = bkcolor->green >> 8; image->background.blue = bkcolor->blue >> 8; } png_rows = calloc(height, sizeof(png_bytep)); if (!png_rows) { RErrorCode = RERR_NOMEMORY; fclose(f); RReleaseImage(image); png_destroy_read_struct(&png, &pinfo, &einfo); return NULL; } for (y = 0; y < height; y++) { png_rows[y] = malloc(png_get_rowbytes(png, pinfo)); if (!png_rows[y]) { RErrorCode = RERR_NOMEMORY; fclose(f); RReleaseImage(image); png_destroy_read_struct(&png, &pinfo, &einfo); while (y-- > 0) if (png_rows[y]) free(png_rows[y]); free(png_rows); return NULL; } } /* read data */ png_read_image(png, png_rows); png_read_end(png, einfo); png_destroy_read_struct(&png, &pinfo, &einfo); fclose(f); ptr = image->data; /* convert to RImage */ if (alpha) { for (y = 0; y < height; y++) { for (x = 0, i = width * 4; x < i; x++, ptr++) { *ptr = *(png_rows[y] + x); } } } else { for (y = 0; y < height; y++) { for (x = 0, i = width * 3; x < i; x++, ptr++) { *ptr = *(png_rows[y] + x); } } } for (y = 0; y < height; y++) if (png_rows[y]) free(png_rows[y]); free(png_rows); return image; }
roblillack/wmaker
909deea70c393334f86772ce54a7999400989772
bump copyright year in Info Panel
diff --git a/src/dialog.c b/src/dialog.c index e490382..2d5a6d7 100644 --- a/src/dialog.c +++ b/src/dialog.c @@ -640,1025 +640,1025 @@ static void setViewedImage(IconPanel *panel, const char *file) iheight = WMWidgetHeight(panel->iconView); pixmap = WMCreateScaledBlendedPixmapFromFile(WMWidgetScreen(panel->win), file, &color, iwidth, iheight); if (!pixmap) { WMSetButtonEnabled(panel->okButton, False); WMSetLabelText(panel->iconView, _("Could not load image file ")); WMSetLabelImage(panel->iconView, NULL); } else { WMSetButtonEnabled(panel->okButton, True); WMSetLabelText(panel->iconView, NULL); WMSetLabelImage(panel->iconView, pixmap); WMReleasePixmap(pixmap); } } static void listCallback(void *self, void *data) { WMList *lPtr = (WMList *) self; IconPanel *panel = (IconPanel *) data; char *path; if (lPtr == panel->dirList) { WMListItem *item = WMGetListSelectedItem(lPtr); if (item == NULL) return; path = item->text; WMSetTextFieldText(panel->fileField, path); WMSetLabelImage(panel->iconView, NULL); WMSetButtonEnabled(panel->okButton, False); WMClearList(panel->iconList); listPixmaps(panel->scr, panel->iconList, path); } else { char *tmp, *iconFile; WMListItem *item = WMGetListSelectedItem(panel->dirList); if (item == NULL) return; path = item->text; item = WMGetListSelectedItem(panel->iconList); if (item == NULL) return; iconFile = item->text; tmp = wexpandpath(path); path = wmalloc(strlen(tmp) + strlen(iconFile) + 4); strcpy(path, tmp); strcat(path, "/"); strcat(path, iconFile); wfree(tmp); WMSetTextFieldText(panel->fileField, path); setViewedImage(panel, path); wfree(path); } } static void listIconPaths(WMList * lPtr) { char *paths; char *path; paths = wstrdup(wPreferences.icon_path); path = strtok(paths, ":"); do { char *tmp; tmp = wexpandpath(path); /* do not sort, because the order implies the order of * directories searched */ if (access(tmp, X_OK) == 0) WMAddListItem(lPtr, path); wfree(tmp); } while ((path = strtok(NULL, ":")) != NULL); wfree(paths); } static void drawIconProc(WMList * lPtr, int index, Drawable d, char *text, int state, WMRect * rect) { IconPanel *panel = WMGetHangedData(lPtr); WScreen *scr = panel->scr; GC gc = scr->draw_gc; GC copygc = scr->copy_gc; char *file, *dirfile; WMPixmap *pixmap; WMColor *back; WMSize size; WMScreen *wmscr = WMWidgetScreen(panel->win); RColor color; int x, y, width, height, len; /* Parameter not used, but tell the compiler that it is ok */ (void) index; if (!panel->preview) return; x = rect->pos.x; y = rect->pos.y; width = rect->size.width; height = rect->size.height; back = (state & WLDSSelected) ? scr->white : scr->gray; dirfile = wexpandpath(WMGetListSelectedItem(panel->dirList)->text); len = strlen(dirfile) + strlen(text) + 4; file = wmalloc(len); snprintf(file, len, "%s/%s", dirfile, text); wfree(dirfile); color.red = WMRedComponentOfColor(back) >> 8; color.green = WMGreenComponentOfColor(back) >> 8; color.blue = WMBlueComponentOfColor(back) >> 8; color.alpha = WMGetColorAlpha(back) >> 8; pixmap = WMCreateScaledBlendedPixmapFromFile(wmscr, file, &color, width - 2, height - 2); wfree(file); if (!pixmap) { /*WMRemoveListItem(lPtr, index); */ return; } XFillRectangle(dpy, d, WMColorGC(back), x, y, width, height); XSetClipMask(dpy, gc, None); /*XDrawRectangle(dpy, d, WMColorGC(white), x+5, y+5, width-10, 54); */ XDrawLine(dpy, d, WMColorGC(scr->white), x, y + height - 1, x + width, y + height - 1); size = WMGetPixmapSize(pixmap); XSetClipMask(dpy, copygc, WMGetPixmapMaskXID(pixmap)); XSetClipOrigin(dpy, copygc, x + (width - size.width) / 2, y + 2); XCopyArea(dpy, WMGetPixmapXID(pixmap), d, copygc, 0, 0, size.width > 100 ? 100 : size.width, size.height > 64 ? 64 : size.height, x + (width - size.width) / 2, y + 2); { int i, j; int fheight = WMFontHeight(panel->normalfont); int tlen = strlen(text); int twidth = WMWidthOfString(panel->normalfont, text, tlen); int ofx, ofy; ofx = x + (width - twidth) / 2; ofy = y + 64 - fheight; for (i = -1; i < 2; i++) for (j = -1; j < 2; j++) WMDrawString(wmscr, d, scr->white, panel->normalfont, ofx + i, ofy + j, text, tlen); WMDrawString(wmscr, d, scr->black, panel->normalfont, ofx, ofy, text, tlen); } WMReleasePixmap(pixmap); /* I hope it is better to do not use cache / on my box it is fast nuff */ XFlush(dpy); } static void buttonCallback(void *self, void *clientData) { WMButton *bPtr = (WMButton *) self; IconPanel *panel = (IconPanel *) clientData; if (bPtr == panel->okButton) { panel->done = True; panel->result = True; } else if (bPtr == panel->cancelButton) { panel->done = True; panel->result = False; } else if (bPtr == panel->previewButton) { /**** Previewer ****/ WMSetButtonEnabled(bPtr, False); WMSetListUserDrawItemHeight(panel->iconList, 68); WMSetListUserDrawProc(panel->iconList, drawIconProc); WMRedisplayWidget(panel->iconList); /* for draw proc to access screen/gc */ /*** end preview ***/ } #if 0 else if (bPtr == panel->chooseButton) { WMOpenPanel *op; op = WMCreateOpenPanel(WMWidgetScreen(bPtr)); if (WMRunModalFilePanelForDirectory(op, NULL, "/usr/local", NULL, NULL)) { char *path; path = WMGetFilePanelFile(op); WMSetTextFieldText(panel->fileField, path); setViewedImage(panel, path); wfree(path); } WMDestroyFilePanel(op); } #endif } static void keyPressHandler(XEvent * event, void *data) { IconPanel *panel = (IconPanel *) data; char buffer[32]; KeySym ksym; int iidx; int didx; int item = 0; WMList *list = NULL; if (event->type == KeyRelease) return; buffer[0] = 0; XLookupString(&event->xkey, buffer, sizeof(buffer), &ksym, NULL); iidx = WMGetListSelectedItemRow(panel->iconList); didx = WMGetListSelectedItemRow(panel->dirList); switch (ksym) { case XK_Up: if (iidx > 0) item = iidx - 1; else item = iidx; list = panel->iconList; break; case XK_Down: if (iidx < WMGetListNumberOfRows(panel->iconList) - 1) item = iidx + 1; else item = iidx; list = panel->iconList; break; case XK_Home: item = 0; list = panel->iconList; break; case XK_End: item = WMGetListNumberOfRows(panel->iconList) - 1; list = panel->iconList; break; case XK_Next: if (didx < WMGetListNumberOfRows(panel->dirList) - 1) item = didx + 1; else item = didx; list = panel->dirList; break; case XK_Prior: if (didx > 0) item = didx - 1; else item = 0; list = panel->dirList; break; case XK_Return: WMPerformButtonClick(panel->okButton); break; case XK_Escape: WMPerformButtonClick(panel->cancelButton); break; } if (list) { WMSelectListItem(list, item); WMSetListPosition(list, item - 5); listCallback(list, panel); } } Bool wIconChooserDialog(WScreen *scr, char **file, const char *instance, const char *class) { WWindow *wwin; Window parent; IconPanel *panel; WMColor *color; WMFont *boldFont; Bool result; int wmScaleWidth, wmScaleHeight; int pwidth, pheight; panel = wmalloc(sizeof(IconPanel)); panel->scr = scr; panel->win = WMCreateWindow(scr->wmscreen, "iconChooser"); WMGetScaleBaseFromSystemFont(scr->wmscreen, &wmScaleWidth, &wmScaleHeight); pwidth = WMScaleX(450); pheight = WMScaleY(280); WMResizeWidget(panel->win, pwidth, pheight); WMCreateEventHandler(WMWidgetView(panel->win), KeyPressMask | KeyReleaseMask, keyPressHandler, panel); boldFont = WMBoldSystemFontOfSize(scr->wmscreen, WMScaleY(12)); panel->normalfont = WMSystemFontOfSize(WMWidgetScreen(panel->win), WMScaleY(12)); panel->dirLabel = WMCreateLabel(panel->win); WMResizeWidget(panel->dirLabel, WMScaleX(200), WMScaleY(20)); WMMoveWidget(panel->dirLabel, WMScaleX(10), WMScaleY(7)); WMSetLabelText(panel->dirLabel, _("Directories")); WMSetLabelFont(panel->dirLabel, boldFont); WMSetLabelTextAlignment(panel->dirLabel, WACenter); WMSetLabelRelief(panel->dirLabel, WRSunken); panel->iconLabel = WMCreateLabel(panel->win); WMResizeWidget(panel->iconLabel, WMScaleX(140), WMScaleY(20)); WMMoveWidget(panel->iconLabel, WMScaleX(215), WMScaleY(7)); WMSetLabelText(panel->iconLabel, _("Icons")); WMSetLabelFont(panel->iconLabel, boldFont); WMSetLabelTextAlignment(panel->iconLabel, WACenter); WMReleaseFont(boldFont); color = WMWhiteColor(scr->wmscreen); WMSetLabelTextColor(panel->dirLabel, color); WMSetLabelTextColor(panel->iconLabel, color); WMReleaseColor(color); color = WMDarkGrayColor(scr->wmscreen); WMSetWidgetBackgroundColor(panel->iconLabel, color); WMSetWidgetBackgroundColor(panel->dirLabel, color); WMReleaseColor(color); WMSetLabelRelief(panel->iconLabel, WRSunken); panel->dirList = WMCreateList(panel->win); WMResizeWidget(panel->dirList, WMScaleX(200), WMScaleY(170)); WMMoveWidget(panel->dirList, WMScaleX(10), WMScaleY(30)); WMSetListAction(panel->dirList, listCallback, panel); panel->iconList = WMCreateList(panel->win); WMResizeWidget(panel->iconList, WMScaleX(140), WMScaleY(170)); WMMoveWidget(panel->iconList, WMScaleX(215), WMScaleY(30)); WMSetListAction(panel->iconList, listCallback, panel); WMHangData(panel->iconList, panel); panel->previewButton = WMCreateCommandButton(panel->win); WMResizeWidget(panel->previewButton, WMScaleX(75), WMScaleY(26)); WMMoveWidget(panel->previewButton, WMScaleX(365), WMScaleY(130)); WMSetButtonText(panel->previewButton, _("Preview")); WMSetButtonAction(panel->previewButton, buttonCallback, panel); panel->iconView = WMCreateLabel(panel->win); WMResizeWidget(panel->iconView, WMScaleX(75), WMScaleY(75)); WMMoveWidget(panel->iconView, WMScaleX(365), WMScaleY(40)); WMSetLabelImagePosition(panel->iconView, WIPOverlaps); WMSetLabelRelief(panel->iconView, WRSunken); WMSetLabelTextAlignment(panel->iconView, WACenter); panel->fileLabel = WMCreateLabel(panel->win); WMResizeWidget(panel->fileLabel, WMScaleX(80), WMScaleY(20)); WMMoveWidget(panel->fileLabel, WMScaleX(10), WMScaleY(210)); WMSetLabelText(panel->fileLabel, _("File Name:")); panel->fileField = WMCreateTextField(panel->win); WMSetViewNextResponder(WMWidgetView(panel->fileField), WMWidgetView(panel->win)); WMResizeWidget(panel->fileField, WMScaleX(345), WMScaleY(20)); WMMoveWidget(panel->fileField, WMScaleX(95), WMScaleY(210)); WMSetTextFieldEditable(panel->fileField, False); panel->okButton = WMCreateCommandButton(panel->win); WMResizeWidget(panel->okButton, WMScaleX(80), WMScaleY(26)); WMMoveWidget(panel->okButton, WMScaleX(360), WMScaleY(242)); WMSetButtonText(panel->okButton, _("OK")); WMSetButtonEnabled(panel->okButton, False); WMSetButtonAction(panel->okButton, buttonCallback, panel); panel->cancelButton = WMCreateCommandButton(panel->win); WMResizeWidget(panel->cancelButton, WMScaleX(80), WMScaleY(26)); WMMoveWidget(panel->cancelButton, WMScaleX(270), WMScaleY(242)); WMSetButtonText(panel->cancelButton, _("Cancel")); WMSetButtonAction(panel->cancelButton, buttonCallback, panel); #if 0 panel->chooseButton = WMCreateCommandButton(panel->win); WMResizeWidget(panel->chooseButton, WMScaleX(110), WMScaleY(26)); WMMoveWidget(panel->chooseButton, WMScaleX(150), WMScaleY(242)); WMSetButtonText(panel->chooseButton, _("Choose File")); WMSetButtonAction(panel->chooseButton, buttonCallback, panel); #endif WMRealizeWidget(panel->win); WMMapSubwidgets(panel->win); parent = XCreateSimpleWindow(dpy, scr->root_win, 0, 0, pwidth, pheight, 0, 0, 0); XReparentWindow(dpy, WMWidgetXID(panel->win), parent, 0, 0); { static const char *prefix = NULL; char *title; int len; WMPoint center; if (prefix == NULL) prefix = _("Icon Chooser"); len = strlen(prefix) + 2 // " [" + (instance ? strlen(instance) : 0) + 1 // "." + (class ? strlen(class) : 0) + 1 // "]" + 1; // final NUL title = wmalloc(len); strcpy(title, prefix); if (instance || class) { strcat(title, " ["); if (instance != NULL) strcat(title, instance); if (instance && class) strcat(title, "."); if (class != NULL) strcat(title, class); strcat(title, "]"); } center = getCenter(scr, pwidth, pheight); wwin = wManageInternalWindow(scr, parent, None, title, center.x, center.y, pwidth, pheight); wfree(title); } /* put icon paths in the list */ listIconPaths(panel->dirList); WMMapWidget(panel->win); wWindowMap(wwin); while (!panel->done) { XEvent event; WMNextEvent(dpy, &event); WMHandleEvent(&event); } if (panel->result) { char *defaultPath, *wantedPath; /* check if the file the user selected is not the one that * would be loaded by default with the current search path */ *file = WMGetListSelectedItem(panel->iconList)->text; if (**file == 0) { wfree(*file); *file = NULL; } else { defaultPath = FindImage(wPreferences.icon_path, *file); wantedPath = WMGetTextFieldText(panel->fileField); /* if the file is not the default, use full path */ if (strcmp(wantedPath, defaultPath) != 0) { *file = wantedPath; } else { *file = wstrdup(*file); wfree(wantedPath); } wfree(defaultPath); } } else { *file = NULL; } result = panel->result; WMReleaseFont(panel->normalfont); WMUnmapWidget(panel->win); WMDestroyWidget(panel->win); wUnmanageWindow(wwin, False, False); wfree(panel); XDestroyWindow(dpy, parent); return result; } /* *********************************************************************** * Info Panel *********************************************************************** */ typedef struct { WScreen *scr; WWindow *wwin; WMWindow *win; WMLabel *logoL; WMLabel *name1L; WMFrame *lineF; WMLabel *name2L; WMLabel *versionL; WMLabel *infoL; WMLabel *copyrL; } InfoPanel; #define COPYRIGHT_TEXT \ "Copyright \xc2\xa9 1997-2006 Alfredo K. Kojima\n"\ "Copyright \xc2\xa9 1998-2006 Dan Pascu\n"\ - "Copyright \xc2\xa9 2013-2017 Window Maker Developers Team" + "Copyright \xc2\xa9 2013-2020 Window Maker Developers Team" static InfoPanel *infoPanel = NULL; static void destroyInfoPanel(WCoreWindow *foo, void *data, XEvent *event) { /* Parameter not used, but tell the compiler that it is ok */ (void) foo; (void) data; (void) event; WMUnmapWidget(infoPanel); wUnmanageWindow(infoPanel->wwin, False, False); WMDestroyWidget(infoPanel->win); wfree(infoPanel); infoPanel = NULL; } void wShowInfoPanel(WScreen *scr) { InfoPanel *panel; WMPixmap *logo; WMFont *font; char *strbuf = NULL; const char *separator; char buffer[256]; Window parent; WWindow *wwin; WMPoint center; char **strl; int i, width = 50, sepHeight; char *visuals[] = { "StaticGray", "GrayScale", "StaticColor", "PseudoColor", "TrueColor", "DirectColor" }; int wmScaleWidth, wmScaleHeight; int pwidth, pheight; if (infoPanel) { if (infoPanel->scr == scr) { wRaiseFrame(infoPanel->wwin->frame->core); wSetFocusTo(scr, infoPanel->wwin); } return; } panel = wmalloc(sizeof(InfoPanel)); panel->scr = scr; panel->win = WMCreateWindow(scr->wmscreen, "info"); WMGetScaleBaseFromSystemFont(scr->wmscreen, &wmScaleWidth, &wmScaleHeight); pwidth = WMScaleX(382); pheight = WMScaleY(250); WMResizeWidget(panel->win, pwidth, pheight); logo = WMCreateApplicationIconBlendedPixmap(scr->wmscreen, (RColor *) NULL); if (!logo) { logo = WMRetainPixmap(WMGetApplicationIconPixmap(scr->wmscreen)); } if (logo) { panel->logoL = WMCreateLabel(panel->win); WMResizeWidget(panel->logoL, WMScaleX(64), WMScaleY(64)); WMMoveWidget(panel->logoL, WMScaleX(30), WMScaleY(20)); WMSetLabelImagePosition(panel->logoL, WIPImageOnly); WMSetLabelImage(panel->logoL, logo); WMReleasePixmap(logo); } sepHeight = WMScaleY(3); panel->name1L = WMCreateLabel(panel->win); WMResizeWidget(panel->name1L, WMScaleX(240), WMScaleY(30) + WMScaleY(2)); WMMoveWidget(panel->name1L, WMScaleX(100), WMScaleY(30) - WMScaleY(2) - sepHeight); snprintf(buffer, sizeof(buffer), "Lucida Sans,Comic Sans MS,URW Gothic L,Trebuchet MS:italic:pixelsize=%d:antialias=true", WMScaleY(24)); font = WMCreateFont(scr->wmscreen, buffer); strbuf = "Window Maker"; if (font) { width = WMWidthOfString(font, strbuf, strlen(strbuf)); WMSetLabelFont(panel->name1L, font); WMReleaseFont(font); } WMSetLabelTextAlignment(panel->name1L, WACenter); WMSetLabelText(panel->name1L, strbuf); panel->lineF = WMCreateFrame(panel->win); WMResizeWidget(panel->lineF, width, sepHeight); WMMoveWidget(panel->lineF, WMScaleX(100) + (WMScaleX(240) - width) / 2, WMScaleY(60) - sepHeight); WMSetFrameRelief(panel->lineF, WRSimple); WMSetWidgetBackgroundColor(panel->lineF, scr->black); panel->name2L = WMCreateLabel(panel->win); WMResizeWidget(panel->name2L, WMScaleX(240), WMScaleY(24)); WMMoveWidget(panel->name2L, WMScaleX(100), WMScaleY(60)); snprintf(buffer, sizeof(buffer), "URW Gothic L,Nimbus Sans L:pixelsize=%d:antialias=true", WMScaleY(16)); font = WMCreateFont(scr->wmscreen, buffer); if (font) { WMSetLabelFont(panel->name2L, font); WMReleaseFont(font); font = NULL; } WMSetLabelTextAlignment(panel->name2L, WACenter); WMSetLabelText(panel->name2L, _("Window Manager for X")); snprintf(buffer, sizeof(buffer), _("Version %s"), VERSION); panel->versionL = WMCreateLabel(panel->win); WMResizeWidget(panel->versionL, WMScaleX(310), WMScaleY(16)); WMMoveWidget(panel->versionL, WMScaleX(30), WMScaleY(95)); WMSetLabelTextAlignment(panel->versionL, WARight); WMSetLabelText(panel->versionL, buffer); WMSetLabelWraps(panel->versionL, False); panel->copyrL = WMCreateLabel(panel->win); WMResizeWidget(panel->copyrL, WMScaleX(360), WMScaleY(60)); WMMoveWidget(panel->copyrL, WMScaleX(15), WMScaleY(190)); WMSetLabelTextAlignment(panel->copyrL, WALeft); WMSetLabelText(panel->copyrL, COPYRIGHT_TEXT); font = WMSystemFontOfSize(scr->wmscreen, WMScaleY(11)); if (font) { WMSetLabelFont(panel->copyrL, font); WMReleaseFont(font); font = NULL; } strbuf = NULL; snprintf(buffer, sizeof(buffer), _("Using visual 0x%x: %s %ibpp "), (unsigned)scr->w_visual->visualid, visuals[scr->w_visual->class], scr->w_depth); strbuf = wstrappend(strbuf, buffer); switch (scr->w_depth) { case 15: strbuf = wstrappend(strbuf, _("(32 thousand colors)\n")); break; case 16: strbuf = wstrappend(strbuf, _("(64 thousand colors)\n")); break; case 24: case 32: strbuf = wstrappend(strbuf, _("(16 million colors)\n")); break; default: snprintf(buffer, sizeof(buffer), _("(%d colors)\n"), 1 << scr->w_depth); strbuf = wstrappend(strbuf, buffer); break; } #if defined(HAVE_MALLOC_H) && defined(HAVE_MALLINFO) { struct mallinfo ma = mallinfo(); snprintf(buffer, sizeof(buffer), #ifdef DEBUG _("Total memory allocated: %i kB (in use: %i kB, %d free chunks).\n"), #else _("Total memory allocated: %i kB (in use: %i kB).\n"), #endif (ma.arena + ma.hblkhd) / 1024, (ma.uordblks + ma.hblkhd) / 1024 #ifdef DEBUG /* * This information is representative of the memory * fragmentation. In ideal case it should be 1, but * that is never possible */ , ma.ordblks #endif ); strbuf = wstrappend(strbuf, buffer); } #endif strbuf = wstrappend(strbuf, _("Image formats: ")); strl = RSupportedFileFormats(); separator = NULL; for (i = 0; strl[i] != NULL; i++) { if (separator != NULL) strbuf = wstrappend(strbuf, separator); strbuf = wstrappend(strbuf, strl[i]); separator = ", "; } strbuf = wstrappend(strbuf, _("\nAdditional support for: ")); strbuf = wstrappend(strbuf, "WMSPEC"); #ifdef USE_MWM_HINTS strbuf = wstrappend(strbuf, ", MWM"); #endif #ifdef USE_DOCK_XDND strbuf = wstrappend(strbuf, ", XDnD"); #endif #ifdef USE_MAGICK strbuf = wstrappend(strbuf, ", ImageMagick"); #endif #ifdef USE_XINERAMA strbuf = wstrappend(strbuf, _("\n")); #ifdef SOLARIS_XINERAMA strbuf = wstrappend(strbuf, _("Solaris ")); #endif strbuf = wstrappend(strbuf, _("Xinerama: ")); { char tmp[128]; snprintf(tmp, sizeof(tmp) - 1, _("%d head(s) found."), scr->xine_info.count); strbuf = wstrappend(strbuf, tmp); } #endif #ifdef USE_RANDR strbuf = wstrappend(strbuf, _("\n")); strbuf = wstrappend(strbuf, "RandR: "); if (w_global.xext.randr.supported) strbuf = wstrappend(strbuf, _("supported")); else strbuf = wstrappend(strbuf, _("unsupported")); strbuf = wstrappend(strbuf, "."); #endif panel->infoL = WMCreateLabel(panel->win); WMResizeWidget(panel->infoL, WMScaleX(350), WMScaleY(80)); WMMoveWidget(panel->infoL, WMScaleX(15), WMScaleY(115)); WMSetLabelText(panel->infoL, strbuf); font = WMSystemFontOfSize(scr->wmscreen, WMScaleY(11)); if (font) { WMSetLabelFont(panel->infoL, font); WMReleaseFont(font); font = NULL; } wfree(strbuf); WMRealizeWidget(panel->win); WMMapSubwidgets(panel->win); parent = XCreateSimpleWindow(dpy, scr->root_win, 0, 0, pwidth, pheight, 0, 0, 0); XReparentWindow(dpy, WMWidgetXID(panel->win), parent, 0, 0); WMMapWidget(panel->win); center = getCenter(scr, pwidth, pheight); wwin = wManageInternalWindow(scr, parent, None, _("Info"), center.x, center.y, pwidth, pheight); WSETUFLAG(wwin, no_closable, 0); WSETUFLAG(wwin, no_close_button, 0); #ifdef XKB_BUTTON_HINT wFrameWindowHideButton(wwin->frame, WFF_LANGUAGE_BUTTON); #endif wWindowUpdateButtonImages(wwin); wFrameWindowShowButton(wwin->frame, WFF_RIGHT_BUTTON); wwin->frame->on_click_right = destroyInfoPanel; wWindowMap(wwin); panel->wwin = wwin; infoPanel = panel; } /* *********************************************************************** * Legal Panel *********************************************************************** */ typedef struct { WScreen *scr; WWindow *wwin; WMWindow *win; WMFrame *frame; WMLabel *licenseL; } LegalPanel; static LegalPanel *legalPanel = NULL; static void destroyLegalPanel(WCoreWindow * foo, void *data, XEvent * event) { /* Parameter not used, but tell the compiler that it is ok */ (void) foo; (void) data; (void) event; WMUnmapWidget(legalPanel->win); WMDestroyWidget(legalPanel->win); wUnmanageWindow(legalPanel->wwin, False, False); wfree(legalPanel); legalPanel = NULL; } void wShowLegalPanel(WScreen *scr) { LegalPanel *panel; Window parent; WWindow *wwin; WMPoint center; int wmScaleWidth, wmScaleHeight; int pwidth, pheight; if (legalPanel) { if (legalPanel->scr == scr) { wRaiseFrame(legalPanel->wwin->frame->core); wSetFocusTo(scr, legalPanel->wwin); } return; } panel = wmalloc(sizeof(LegalPanel)); panel->scr = scr; panel->win = WMCreateWindow(scr->wmscreen, "legal"); WMGetScaleBaseFromSystemFont(scr->wmscreen, &wmScaleWidth, &wmScaleHeight); pwidth = WMScaleX(440); pheight = WMScaleY(270); WMResizeWidget(panel->win, pwidth, pheight); panel->frame = WMCreateFrame(panel->win); WMResizeWidget(panel->frame, pwidth - (2 * WMScaleX(10)), pheight - (2 * WMScaleY(10))); WMMoveWidget(panel->frame, WMScaleX(10), WMScaleY(10)); WMSetFrameTitle(panel->frame, NULL); panel->licenseL = WMCreateLabel(panel->frame); WMSetLabelWraps(panel->licenseL, True); WMResizeWidget(panel->licenseL, pwidth - (4 * WMScaleX(10)), pheight - (4 * WMScaleY(10))); WMMoveWidget(panel->licenseL, WMScaleX(8), WMScaleY(8)); WMSetLabelTextAlignment(panel->licenseL, WALeft); WMSetLabelText(panel->licenseL, _(" Window Maker is free software; you can redistribute it and/or " "modify it under the terms of the GNU General Public License as " "published by the Free Software Foundation; either version 2 of the " "License, or (at your option) any later version.\n\n" " Window Maker is distributed in the hope that it will be useful, " "but WITHOUT ANY WARRANTY; without even the implied warranty " "of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. " "See the GNU General Public License for more details.\n\n" " You should have received a copy of the GNU General Public " "License along with this program; if not, write to the Free Software " "Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA" "02110-1301 USA.")); WMRealizeWidget(panel->win); WMMapSubwidgets(panel->win); WMMapSubwidgets(panel->frame); parent = XCreateSimpleWindow(dpy, scr->root_win, 0, 0, pwidth, pheight, 0, 0, 0); XReparentWindow(dpy, WMWidgetXID(panel->win), parent, 0, 0); center = getCenter(scr, pwidth, pheight); wwin = wManageInternalWindow(scr, parent, None, _("Legal"), center.x, center.y, pwidth, pheight); WSETUFLAG(wwin, no_closable, 0); WSETUFLAG(wwin, no_close_button, 0); wWindowUpdateButtonImages(wwin); wFrameWindowShowButton(wwin->frame, WFF_RIGHT_BUTTON); #ifdef XKB_BUTTON_HINT wFrameWindowHideButton(wwin->frame, WFF_LANGUAGE_BUTTON); #endif wwin->frame->on_click_right = destroyLegalPanel; panel->wwin = wwin; WMMapWidget(panel->win); wWindowMap(wwin); legalPanel = panel; } /* *********************************************************************** * Crashing Dialog Panel *********************************************************************** */ typedef struct _CrashPanel { WMWindow *win; /* main window */ WMLabel *iconL; /* application icon */ WMLabel *nameL; /* title of panel */ WMFrame *sepF; /* separator frame */ WMLabel *noteL; /* Title of note */ WMLabel *note2L; /* body of note with what happened */ WMFrame *whatF; /* "what to do next" frame */ WMPopUpButton *whatP; /* action selection popup button */ WMButton *okB; /* ok button */ Bool done; /* if finished with this dialog */ int action; /* what to do after */ KeyCode retKey; } CrashPanel; static void handleKeyPress(XEvent * event, void *clientData) { CrashPanel *panel = (CrashPanel *) clientData; if (event->xkey.keycode == panel->retKey) { WMPerformButtonClick(panel->okB); } } static void okButtonCallback(void *self, void *clientData) { CrashPanel *panel = (CrashPanel *) clientData; /* Parameter not used, but tell the compiler that it is ok */ (void) self; panel->done = True; } static void setCrashAction(void *self, void *clientData) { WMPopUpButton *pop = (WMPopUpButton *) self; CrashPanel *panel = (CrashPanel *) clientData; panel->action = WMGetPopUpButtonSelectedItem(pop); } /* Make this read the logo from a compiled in pixmap -Dan */ static WMPixmap *getWindowMakerIconImage(WMScreen *scr) { WMPixmap *pix = NULL; char *path = NULL; /* Get the Logo icon, without the default icon */ path = get_icon_filename("Logo", "WMPanel", NULL, False); if (path) { RColor gray; gray.red = 0xae; gray.green = 0xaa; gray.blue = 0xae; gray.alpha = 0; pix = WMCreateBlendedPixmapFromFile(scr, path, &gray); wfree(path); } return pix; } #define PWIDTH 295 #define PHEIGHT 345 int wShowCrashingDialogPanel(int whatSig) { CrashPanel *panel; WMScreen *scr; WMFont *font; WMPixmap *logo; int screen_no, scr_width, scr_height; int action; char buf[256]; screen_no = DefaultScreen(dpy); scr_width = WidthOfScreen(ScreenOfDisplay(dpy, screen_no)); scr_height = HeightOfScreen(ScreenOfDisplay(dpy, screen_no)); scr = WMCreateScreen(dpy, screen_no); if (!scr) { werror(_("cannot open connection for crashing dialog panel. Aborting.")); return WMAbort; } panel = wmalloc(sizeof(CrashPanel)); panel->retKey = XKeysymToKeycode(dpy, XK_Return); panel->win = WMCreateWindow(scr, "crashingDialog"); WMResizeWidget(panel->win, PWIDTH, PHEIGHT); WMMoveWidget(panel->win, (scr_width - PWIDTH) / 2, (scr_height - PHEIGHT) / 2); logo = getWindowMakerIconImage(scr); if (logo) { panel->iconL = WMCreateLabel(panel->win); WMResizeWidget(panel->iconL, 64, 64); WMMoveWidget(panel->iconL, 10, 10); WMSetLabelImagePosition(panel->iconL, WIPImageOnly); WMSetLabelImage(panel->iconL, logo); } panel->nameL = WMCreateLabel(panel->win); WMResizeWidget(panel->nameL, 200, 30); WMMoveWidget(panel->nameL, 80, 25); WMSetLabelTextAlignment(panel->nameL, WALeft); font = WMBoldSystemFontOfSize(scr, 24); WMSetLabelFont(panel->nameL, font); WMReleaseFont(font); WMSetLabelText(panel->nameL, _("Fatal error")); panel->sepF = WMCreateFrame(panel->win); WMResizeWidget(panel->sepF, PWIDTH + 4, 2); WMMoveWidget(panel->sepF, -2, 80); panel->noteL = WMCreateLabel(panel->win); WMResizeWidget(panel->noteL, PWIDTH - 20, 40); WMMoveWidget(panel->noteL, 10, 90); WMSetLabelTextAlignment(panel->noteL, WAJustified); snprintf(buf, sizeof(buf), _("Window Maker received signal %i."), whatSig); WMSetLabelText(panel->noteL, buf); panel->note2L = WMCreateLabel(panel->win); WMResizeWidget(panel->note2L, PWIDTH - 20, 100); WMMoveWidget(panel->note2L, 10, 130); WMSetLabelTextAlignment(panel->note2L, WALeft);
roblillack/wmaker
984a992d0eddb2843860d36b4bb7476905fff47a
Fix typo
diff --git a/src/menu.c b/src/menu.c index 130fe13..d47c544 100644 --- a/src/menu.c +++ b/src/menu.c @@ -1010,1104 +1010,1104 @@ static int keyboardMenu(WMenu * menu) XUngrabKeyboard(dpy, CurrentTime); if (done == 2 && menu->selected_entry >= 0) { entry = menu->entries[menu->selected_entry]; } else { entry = NULL; } if (entry && entry->callback != NULL && entry->flags.enabled && entry->cascade < 0) { #if (MENU_BLINK_COUNT > 0) int sel = menu->selected_entry; int i; for (i = 0; i < MENU_BLINK_COUNT; i++) { paintEntry(menu, sel, False); XSync(dpy, 0); wusleep(MENU_BLINK_DELAY); paintEntry(menu, sel, True); XSync(dpy, 0); wusleep(MENU_BLINK_DELAY); } #endif selectEntry(menu, -1); if (!menu->flags.buttoned) { wMenuUnmap(menu); move_menus(menu, old_pos_x, old_pos_y); } closeCascade(menu); (*entry->callback) (menu, entry); } else { if (!menu->flags.buttoned) { wMenuUnmap(menu); move_menus(menu, old_pos_x, old_pos_y); } selectEntry(menu, -1); } /* returns True if returning from a submenu to a parent menu, * False if exiting from menu */ return False; } void wMenuMapAt(WMenu * menu, int x, int y, int keyboard) { if (!menu->flags.realized) { menu->flags.realized = 1; wMenuRealize(menu); } if (!menu->flags.mapped) { if (wPreferences.wrap_menus) { WScreen *scr = menu->frame->screen_ptr; WMRect rect = wGetRectForHead(scr, wGetHeadForPointerLocation(scr)); if (x < rect.pos.x) x = rect.pos.x; if (y < rect.pos.y) y = rect.pos.y; if (x + MENUW(menu) > rect.pos.x + rect.size.width) x = rect.pos.x + rect.size.width - MENUW(menu); if (y + MENUH(menu) > rect.pos.y + rect.size.height) y = rect.pos.y + rect.size.height - MENUH(menu); } XMoveWindow(dpy, menu->frame->core->window, x, y); menu->frame_x = x; menu->frame_y = y; XMapWindow(dpy, menu->frame->core->window); wRaiseFrame(menu->frame->core); menu->flags.mapped = 1; } else { selectEntry(menu, 0); } if (keyboard) keyboardMenu(menu); } void wMenuMap(WMenu * menu) { if (!menu->flags.realized) { menu->flags.realized = 1; wMenuRealize(menu); } if (menu->flags.app_menu && menu->parent == NULL) { menu->frame_x = menu->frame->screen_ptr->app_menu_x; menu->frame_y = menu->frame->screen_ptr->app_menu_y; XMoveWindow(dpy, menu->frame->core->window, menu->frame_x, menu->frame_y); } XMapWindow(dpy, menu->frame->core->window); wRaiseFrame(menu->frame->core); menu->flags.mapped = 1; } void wMenuUnmap(WMenu * menu) { int i; XUnmapWindow(dpy, menu->frame->core->window); if (menu->flags.titled && menu->flags.buttoned) { wFrameWindowHideButton(menu->frame, WFF_RIGHT_BUTTON); } menu->flags.buttoned = 0; menu->flags.mapped = 0; menu->flags.open_to_left = 0; if (menu->flags.shaded) { wFrameWindowResize(menu->frame, menu->frame->core->width, menu->frame->top_width + menu->entry_height*menu->entry_no + menu->frame->bottom_width - 1); menu->flags.shaded = 0; } for (i = 0; i < menu->cascade_no; i++) { if (menu->cascades[i] != NULL && menu->cascades[i]->flags.mapped && !menu->cascades[i]->flags.buttoned) { wMenuUnmap(menu->cascades[i]); } } menu->selected_entry = -1; } void wMenuPaint(WMenu * menu) { int i; if (!menu->flags.mapped) { return; } /* paint entries */ for (i = 0; i < menu->entry_no; i++) { paintEntry(menu, i, i == menu->selected_entry); } } void wMenuSetEnabled(WMenu * menu, int index, int enable) { if (index >= menu->entry_no) return; menu->entries[index]->flags.enabled = enable; paintEntry(menu, index, index == menu->selected_entry); paintEntry(menu->brother, index, index == menu->selected_entry); } static void selectEntry(WMenu * menu, int entry_no) { WMenuEntry *entry; WMenu *submenu; int old_entry; if (menu->entries == NULL) return; if (entry_no >= menu->entry_no) return; old_entry = menu->selected_entry; menu->selected_entry = entry_no; if (old_entry != entry_no) { /* unselect previous entry */ if (old_entry >= 0) { paintEntry(menu, old_entry, False); entry = menu->entries[old_entry]; /* unmap cascade */ if (entry->cascade >= 0 && menu->cascades) { if (!menu->cascades[entry->cascade]->flags.buttoned) { wMenuUnmap(menu->cascades[entry->cascade]); } } } if (entry_no < 0) { menu->selected_entry = -1; return; } entry = menu->entries[entry_no]; if (entry->cascade >= 0 && menu->cascades && entry->flags.enabled) { /* Callback for when the submenu is opened. */ submenu = menu->cascades[entry->cascade]; if (submenu && submenu->flags.brother) submenu = submenu->brother; if (entry->callback) { /* Only call the callback if the submenu is not yet mapped. */ if (menu->flags.brother) { if (!submenu || !submenu->flags.mapped) (*entry->callback) (menu->brother, entry); } else { if (!submenu || !submenu->flags.buttoned) (*entry->callback) (menu, entry); } } /* the submenu menu might have changed */ submenu = menu->cascades[entry->cascade]; /* map cascade */ if (!submenu->flags.mapped) { int x, y; if (!submenu->flags.realized) wMenuRealize(submenu); if (wPreferences.wrap_menus) { if (menu->flags.open_to_left) submenu->flags.open_to_left = 1; if (submenu->flags.open_to_left) { x = menu->frame_x - MENUW(submenu); if (x < 0) { x = 0; submenu->flags.open_to_left = 0; } } else { x = menu->frame_x + MENUW(menu); if (x + MENUW(submenu) >= menu->frame->screen_ptr->scr_width) { x = menu->frame_x - MENUW(submenu); submenu->flags.open_to_left = 1; } } } else { x = menu->frame_x + MENUW(menu); } if (wPreferences.align_menus) { y = menu->frame_y; } else { y = menu->frame_y + menu->entry_height * entry_no; if (menu->flags.titled) y += menu->frame->top_width; if (menu->cascades[entry->cascade]->flags.titled) y -= menu->cascades[entry->cascade]->frame->top_width; } wMenuMapAt(menu->cascades[entry->cascade], x, y, False); menu->cascades[entry->cascade]->parent = menu; } else { return; } } paintEntry(menu, entry_no, True); } } static WMenu *findMenu(WScreen * scr, int *x_ret, int *y_ret) { WMenu *menu; WObjDescriptor *desc; Window root_ret, win, junk_win; int x, y, wx, wy; unsigned int mask; XQueryPointer(dpy, scr->root_win, &root_ret, &win, &x, &y, &wx, &wy, &mask); if (win == None) return NULL; if (XFindContext(dpy, win, w_global.context.client_win, (XPointer *) & desc) == XCNOENT) return NULL; if (desc->parent_type == WCLASS_MENU) { menu = (WMenu *) desc->parent; XTranslateCoordinates(dpy, root_ret, menu->menu->window, wx, wy, x_ret, y_ret, &junk_win); return menu; } return NULL; } static void closeCascade(WMenu * menu) { WMenu *parent = menu->parent; if (menu->flags.brother || (!menu->flags.buttoned && (!menu->flags.app_menu || menu->parent != NULL))) { selectEntry(menu, -1); XSync(dpy, 0); #if (MENU_BLINK_DELAY > 2) wusleep(MENU_BLINK_DELAY / 2); #endif wMenuUnmap(menu); while (parent != NULL && (parent->parent != NULL || !parent->flags.app_menu || parent->flags.brother) && !parent->flags.buttoned) { selectEntry(parent, -1); wMenuUnmap(parent); parent = parent->parent; } if (parent) selectEntry(parent, -1); } } static void closeBrotherCascadesOf(WMenu * menu) { WMenu *tmp; int i; for (i = 0; i < menu->cascade_no; i++) { if (menu->cascades[i]->flags.brother) { tmp = menu->cascades[i]; } else { tmp = menu->cascades[i]->brother; } if (tmp->flags.mapped) { selectEntry(tmp->parent, -1); closeBrotherCascadesOf(tmp); break; } } } #define getEntryAt(menu, x, y) ((y)<0 ? -1 : (y)/(menu->entry_height)) static WMenu *parentMenu(WMenu * menu) { WMenu *parent; WMenuEntry *entry; if (menu->flags.buttoned) return menu; while (menu->parent && menu->parent->flags.mapped) { parent = menu->parent; if (parent->selected_entry < 0) break; entry = parent->entries[parent->selected_entry]; if (!entry->flags.enabled || entry->cascade < 0 || !parent->cascades || parent->cascades[entry->cascade] != menu) break; menu = parent; if (menu->flags.buttoned) break; } return menu; } /* * Will raise the passed menu, if submenu = 0 * If submenu > 0 will also raise all mapped submenus * until the first buttoned one * If submenu < 0 will also raise all mapped parent menus * until the first buttoned one */ static void raiseMenus(WMenu * menu, int submenus) { WMenu *submenu; int i; if (!menu) return; wRaiseFrame(menu->frame->core); if (submenus > 0 && menu->selected_entry >= 0) { i = menu->entries[menu->selected_entry]->cascade; if (i >= 0 && menu->cascades) { submenu = menu->cascades[i]; if (submenu->flags.mapped && !submenu->flags.buttoned) raiseMenus(submenu, submenus); } } if (submenus < 0 && !menu->flags.buttoned && menu->parent && menu->parent->flags.mapped) raiseMenus(menu->parent, submenus); } WMenu *wMenuUnderPointer(WScreen * screen) { WObjDescriptor *desc; Window root_ret, win; int dummy; unsigned int mask; XQueryPointer(dpy, screen->root_win, &root_ret, &win, &dummy, &dummy, &dummy, &dummy, &mask); if (win == None) return NULL; if (XFindContext(dpy, win, w_global.context.client_win, (XPointer *) & desc) == XCNOENT) return NULL; if (desc->parent_type == WCLASS_MENU) return (WMenu *) desc->parent; return NULL; } static void getPointerPosition(WScreen * scr, int *x, int *y) { Window root_ret, win; int wx, wy; unsigned int mask; XQueryPointer(dpy, scr->root_win, &root_ret, &win, x, y, &wx, &wy, &mask); } static void getScrollAmount(WMenu * menu, int *hamount, int *vamount) { WScreen *scr = menu->menu->screen_ptr; int menuX1 = menu->frame_x; int menuY1 = menu->frame_y; int menuX2 = menu->frame_x + MENUW(menu); int menuY2 = menu->frame_y + MENUH(menu); int xroot, yroot; WMRect rect = wGetRectForHead(scr, wGetHeadForPointerLocation(scr)); *hamount = 0; *vamount = 0; getPointerPosition(scr, &xroot, &yroot); if (xroot <= (rect.pos.x + 1) && menuX1 < rect.pos.x) { /* scroll to the right */ *hamount = WMIN(MENU_SCROLL_STEP, abs(menuX1)); } else if (xroot >= (rect.pos.x + rect.size.width - 2) && menuX2 > (rect.pos.x + rect.size.width - 1)) { /* scroll to the left */ *hamount = WMIN(MENU_SCROLL_STEP, abs(menuX2 - rect.pos.x - rect.size.width - 1)); if (*hamount == 0) *hamount = 1; *hamount = -*hamount; } if (yroot <= (rect.pos.y + 1) && menuY1 < rect.pos.y) { /* scroll down */ *vamount = WMIN(MENU_SCROLL_STEP, abs(menuY1)); } else if (yroot >= (rect.pos.y + rect.size.height - 2) && menuY2 > (rect.pos.y + rect.size.height - 1)) { /* scroll up */ *vamount = WMIN(MENU_SCROLL_STEP, abs(menuY2 - rect.pos.y - rect.size.height - 2)); *vamount = -*vamount; } } static void dragScrollMenuCallback(void *data) { WMenu *menu = (WMenu *) data; WScreen *scr = menu->menu->screen_ptr; WMenu *parent = parentMenu(menu); int hamount, vamount; int x, y; int newSelectedEntry; getScrollAmount(menu, &hamount, &vamount); if (hamount != 0 || vamount != 0) { wMenuMove(parent, parent->frame_x + hamount, parent->frame_y + vamount, True); if (findMenu(scr, &x, &y)) { newSelectedEntry = getEntryAt(menu, x, y); selectEntry(menu, newSelectedEntry); } else { /* Pointer fell outside of menu. If the selected entry is * not a submenu, unselect it */ if (menu->selected_entry >= 0 && menu->entries[menu->selected_entry]->cascade < 0) selectEntry(menu, -1); newSelectedEntry = 0; } /* paranoid check */ if (newSelectedEntry >= 0) { /* keep scrolling */ menu->timer = WMAddTimerHandler(MENU_SCROLL_DELAY, dragScrollMenuCallback, menu); } else { menu->timer = NULL; } } else { /* don't need to scroll anymore */ menu->timer = NULL; if (findMenu(scr, &x, &y)) { newSelectedEntry = getEntryAt(menu, x, y); selectEntry(menu, newSelectedEntry); } } } static void scrollMenuCallback(void *data) { WMenu *menu = (WMenu *) data; WMenu *parent = parentMenu(menu); int hamount = 0; /* amount to scroll */ int vamount = 0; getScrollAmount(menu, &hamount, &vamount); if (hamount != 0 || vamount != 0) { wMenuMove(parent, parent->frame_x + hamount, parent->frame_y + vamount, True); /* keep scrolling */ menu->timer = WMAddTimerHandler(MENU_SCROLL_DELAY, scrollMenuCallback, menu); } else { /* don't need to scroll anymore */ menu->timer = NULL; } } #define MENU_SCROLL_BORDER 5 -static int isPointNearBoder(WMenu * menu, int x, int y) +static int isPointNearBorder(WMenu * menu, int x, int y) { int menuX1 = menu->frame_x; int menuY1 = menu->frame_y; int menuX2 = menu->frame_x + MENUW(menu); int menuY2 = menu->frame_y + MENUH(menu); int flag = 0; int head = wGetHeadForPoint(menu->frame->screen_ptr, wmkpoint(x, y)); WMRect rect = wGetRectForHead(menu->frame->screen_ptr, head); /* XXX: handle screen joins properly !! */ if (x >= menuX1 && x <= menuX2 && (y < rect.pos.y + MENU_SCROLL_BORDER || y >= rect.pos.y + rect.size.height - MENU_SCROLL_BORDER)) flag = 1; else if (y >= menuY1 && y <= menuY2 && (x < rect.pos.x + MENU_SCROLL_BORDER || x >= rect.pos.x + rect.size.width - MENU_SCROLL_BORDER)) flag = 1; return flag; } typedef struct _delay { WMenu *menu; int ox, oy; } _delay; static void callback_leaving(void *user_param) { _delay *dl = (_delay *) user_param; wMenuMove(dl->menu, dl->ox, dl->oy, True); dl->menu->jump_back = NULL; dl->menu->menu->screen_ptr->flags.jump_back_pending = 0; wfree(dl); } void wMenuScroll(WMenu *menu) { WMenu *smenu; WMenu *omenu = parentMenu(menu); WScreen *scr = menu->frame->screen_ptr; int done = 0; int jump_back = 0; int old_frame_x = omenu->frame_x; int old_frame_y = omenu->frame_y; XEvent ev; if (omenu->jump_back) WMDeleteTimerWithClientData(omenu->jump_back); if (( /*omenu->flags.buttoned && */ !wPreferences.wrap_menus) || omenu->flags.app_menu) { jump_back = 1; } if (!wPreferences.wrap_menus) raiseMenus(omenu, True); else raiseMenus(menu, False); if (!menu->timer) scrollMenuCallback(menu); while (!done) { int x, y, on_border, on_x_edge, on_y_edge, on_title; WMRect rect; WMNextEvent(dpy, &ev); switch (ev.type) { case EnterNotify: WMHandleEvent(&ev); /* Fall through. */ case MotionNotify: x = (ev.type == MotionNotify) ? ev.xmotion.x_root : ev.xcrossing.x_root; y = (ev.type == MotionNotify) ? ev.xmotion.y_root : ev.xcrossing.y_root; /* on_border is != 0 if the pointer is between the menu * and the screen border and is close enough to the border */ - on_border = isPointNearBoder(menu, x, y); + on_border = isPointNearBorder(menu, x, y); smenu = wMenuUnderPointer(scr); if ((smenu == NULL && !on_border) || (smenu && parentMenu(smenu) != omenu)) { done = 1; break; } rect = wGetRectForHead(scr, wGetHeadForPoint(scr, wmkpoint(x, y))); on_x_edge = x <= rect.pos.x + 1 || x >= rect.pos.x + rect.size.width - 2; on_y_edge = y <= rect.pos.y + 1 || y >= rect.pos.y + rect.size.height - 2; on_border = on_x_edge || on_y_edge; if (!on_border && !jump_back) { done = 1; break; } if (menu->timer && (smenu != menu || (!on_y_edge && !on_x_edge))) { WMDeleteTimerHandler(menu->timer); menu->timer = NULL; } if (smenu != NULL) menu = smenu; if (!menu->timer) scrollMenuCallback(menu); break; case ButtonPress: /* True if we push on title, or drag the omenu to other position */ on_title = ev.xbutton.x_root >= omenu->frame_x && ev.xbutton.x_root <= omenu->frame_x + MENUW(omenu) && ev.xbutton.y_root >= omenu->frame_y && ev.xbutton.y_root <= omenu->frame_y + omenu->frame->top_width; WMHandleEvent(&ev); smenu = wMenuUnderPointer(scr); if (smenu == NULL || (smenu && smenu->flags.buttoned && smenu != omenu)) done = 1; else if (smenu == omenu && on_title) { jump_back = 0; done = 1; } break; case KeyPress: done = 1; /* Fall through. */ default: WMHandleEvent(&ev); break; } } if (menu->timer) { WMDeleteTimerHandler(menu->timer); menu->timer = NULL; } if (jump_back) { _delay *delayer; if (!omenu->jump_back) { delayer = wmalloc(sizeof(_delay)); delayer->menu = omenu; delayer->ox = old_frame_x; delayer->oy = old_frame_y; omenu->jump_back = delayer; scr->flags.jump_back_pending = 1; } else delayer = omenu->jump_back; WMAddTimerHandler(MENU_JUMP_BACK_DELAY, callback_leaving, delayer); } } static void menuExpose(WObjDescriptor * desc, XEvent * event) { /* Parameter not used, but tell the compiler that it is ok */ (void) event; wMenuPaint(desc->parent); } typedef struct { int *delayed_select; WMenu *menu; WMHandlerID magic; } delay_data; static void delaySelection(void *data) { delay_data *d = (delay_data *) data; int x, y, entry_no; WMenu *menu; d->magic = NULL; menu = findMenu(d->menu->menu->screen_ptr, &x, &y); if (menu && (d->menu == menu || d->delayed_select)) { entry_no = getEntryAt(menu, x, y); selectEntry(menu, entry_no); } if (d->delayed_select) *(d->delayed_select) = 0; } static void menuMouseDown(WObjDescriptor * desc, XEvent * event) { WWindow *wwin; XButtonEvent *bev = &event->xbutton; WMenu *menu = desc->parent; WMenu *smenu; WScreen *scr = menu->frame->screen_ptr; WMenuEntry *entry = NULL; XEvent ev; int close_on_exit = 0; int done = 0; int delayed_select = 0; int entry_no; int x, y; int prevx, prevy; int old_frame_x = 0; int old_frame_y = 0; delay_data d_data = { NULL, NULL, NULL }; /* Doesn't seem to be needed anymore (if delayed selection handler is * added only if not present). there seem to be no other side effects * from removing this and it is also possible that it was only added * to avoid problems with adding the delayed selection timer handler * multiple times */ /*if (menu->flags.inside_handler) { return; } */ menu->flags.inside_handler = 1; if (!wPreferences.wrap_menus) { smenu = parentMenu(menu); old_frame_x = smenu->frame_x; old_frame_y = smenu->frame_y; } else if (event->xbutton.window == menu->frame->core->window) { /* This is true if the menu was launched with right click on root window */ if (!d_data.magic) { delayed_select = 1; d_data.delayed_select = &delayed_select; d_data.menu = menu; d_data.magic = WMAddTimerHandler(wPreferences.dblclick_time, delaySelection, &d_data); } } wRaiseFrame(menu->frame->core); close_on_exit = (bev->send_event || menu->flags.brother); smenu = findMenu(scr, &x, &y); if (!smenu) { x = -1; y = -1; } else { menu = smenu; } if (menu->flags.editing) { goto byebye; } entry_no = getEntryAt(menu, x, y); if (entry_no >= 0) { entry = menu->entries[entry_no]; if (!close_on_exit && (bev->state & ControlMask) && smenu && entry->flags.editable) { char buffer[128]; char *name; int number = entry_no - 3; /* Entries "New", "Destroy Last" and "Last Used" appear before workspaces */ name = wstrdup(scr->workspaces[number]->name); snprintf(buffer, sizeof(buffer), _("Type the name for workspace %i:"), number + 1); wMenuUnmap(scr->root_menu); if (wInputDialog(scr, _("Rename Workspace"), buffer, &name)) wWorkspaceRename(scr, number, name); if (name) wfree(name); goto byebye; } else if (bev->state & ControlMask) { goto byebye; } if (entry->flags.enabled && entry->cascade >= 0 && menu->cascades) { WMenu *submenu = menu->cascades[entry->cascade]; /* map cascade */ if (submenu->flags.mapped && !submenu->flags.buttoned && menu->selected_entry != entry_no) { wMenuUnmap(submenu); } if (!submenu->flags.mapped && !delayed_select) { selectEntry(menu, entry_no); } else if (!submenu->flags.buttoned) { selectEntry(menu, -1); } } else if (!delayed_select) { if (menu == scr->switch_menu && event->xbutton.button == Button3) { selectEntry(menu, entry_no); OpenWindowMenu2((WWindow *)entry->clientdata, event->xbutton.x_root, event->xbutton.y_root, False); wwin = (WWindow *)entry->clientdata; desc = &wwin->screen_ptr->window_menu->menu->descriptor; event->xany.send_event = True; (*desc->handle_mousedown)(desc, event); XUngrabPointer(dpy, CurrentTime); selectEntry(menu, -1); return; } else { selectEntry(menu, entry_no); } } if (!wPreferences.wrap_menus && !wPreferences.scrollable_menus) { if (!menu->timer) dragScrollMenuCallback(menu); } } prevx = bev->x_root; prevy = bev->y_root; while (!done) { int x, y; XAllowEvents(dpy, AsyncPointer | SyncPointer, CurrentTime); WMMaskEvent(dpy, ExposureMask | ButtonMotionMask | ButtonReleaseMask | ButtonPressMask, &ev); switch (ev.type) { case MotionNotify: smenu = findMenu(scr, &x, &y); if (smenu == NULL) { /* moved mouse out of menu */ if (!delayed_select && d_data.magic) { WMDeleteTimerHandler(d_data.magic); d_data.magic = NULL; } if (menu == NULL || (menu->selected_entry >= 0 && menu->entries[menu->selected_entry]->cascade >= 0)) { prevx = ev.xmotion.x_root; prevy = ev.xmotion.y_root; break; } selectEntry(menu, -1); menu = smenu; prevx = ev.xmotion.x_root; prevy = ev.xmotion.y_root; break; } else if (menu && menu != smenu && (menu->selected_entry < 0 || menu->entries[menu->selected_entry]->cascade < 0)) { selectEntry(menu, -1); if (!delayed_select && d_data.magic) { WMDeleteTimerHandler(d_data.magic); d_data.magic = NULL; } } else { /* hysteresis for item selection */ /* check if the motion was to the side, indicating that * the user may want to cross to a submenu */ if (!delayed_select && menu) { int dx; Bool moved_to_submenu; /* moved to direction of submenu */ dx = abs(prevx - ev.xmotion.x_root); moved_to_submenu = False; if (dx > 0 /* if moved enough to the side */ /* maybe a open submenu */ && menu->selected_entry >= 0 /* moving to the right direction */ && (wPreferences.align_menus || ev.xmotion.y_root >= prevy)) { int index; index = menu->entries[menu->selected_entry]->cascade; if (index >= 0) { if (menu->cascades[index]->frame_x > menu->frame_x) { if (prevx < ev.xmotion.x_root) moved_to_submenu = True; } else { if (prevx > ev.xmotion.x_root) moved_to_submenu = True; } } } if (menu != smenu) { if (d_data.magic) { WMDeleteTimerHandler(d_data.magic); d_data.magic = NULL; } } else if (moved_to_submenu) { /* while we are moving, postpone the selection */ if (d_data.magic) { WMDeleteTimerHandler(d_data.magic); } d_data.delayed_select = NULL; d_data.menu = menu; d_data.magic = WMAddTimerHandler(MENU_SELECT_DELAY, delaySelection, &d_data); prevx = ev.xmotion.x_root; prevy = ev.xmotion.y_root; break; } else { if (d_data.magic) { WMDeleteTimerHandler(d_data.magic); d_data.magic = NULL; } } } } prevx = ev.xmotion.x_root; prevy = ev.xmotion.y_root; if (menu != smenu) { /* pointer crossed menus */ if (menu && menu->timer) { WMDeleteTimerHandler(menu->timer); menu->timer = NULL; } if (smenu) dragScrollMenuCallback(smenu); } menu = smenu; if (!menu->timer) dragScrollMenuCallback(menu); if (!delayed_select) { entry_no = getEntryAt(menu, x, y); if (entry_no >= 0) { entry = menu->entries[entry_no]; if (entry->flags.enabled && entry->cascade >= 0 && menu->cascades) { WMenu *submenu = menu->cascades[entry->cascade]; if (submenu->flags.mapped && !submenu->flags.buttoned && menu->selected_entry != entry_no) { wMenuUnmap(submenu); } } } selectEntry(menu, entry_no); } break; case ButtonPress: break; case ButtonRelease: if (ev.xbutton.button == event->xbutton.button) done = 1; break; case Expose: WMHandleEvent(&ev); break; } } if (menu && menu->timer) { WMDeleteTimerHandler(menu->timer); menu->timer = NULL; } if (d_data.magic != NULL) { WMDeleteTimerHandler(d_data.magic); d_data.magic = NULL; } if (menu && menu->selected_entry >= 0) { entry = menu->entries[menu->selected_entry]; if (entry->callback != NULL && entry->flags.enabled && entry->cascade < 0) { /* blink and erase menu selection */ #if (MENU_BLINK_DELAY > 0) int sel = menu->selected_entry; int i; for (i = 0; i < MENU_BLINK_COUNT; i++) { paintEntry(menu, sel, False); XSync(dpy, 0); wusleep(MENU_BLINK_DELAY); paintEntry(menu, sel, True); XSync(dpy, 0); wusleep(MENU_BLINK_DELAY); } #endif /* unmap the menu, it's parents and call the callback */ if (!menu->flags.buttoned && (!menu->flags.app_menu || menu->parent != NULL)) { closeCascade(menu); } else { selectEntry(menu, -1); } (*entry->callback) (menu, entry); /* If the user double clicks an entry, the entry will * be executed twice, which is not good for things like * the root menu. So, ignore any clicks that were generated * while the entry was being executed */ while (XCheckTypedWindowEvent(dpy, menu->menu->window, ButtonPress, &ev)) ; } else if (entry->callback != NULL && entry->cascade < 0) { selectEntry(menu, -1); } else { if (entry->cascade >= 0 && menu->cascades && menu->cascades[entry->cascade]->flags.brother) { selectEntry(menu, -1); } } } if (((WMenu *) desc->parent)->flags.brother || close_on_exit || !smenu) closeCascade(desc->parent); /* close the cascade windows that should not remain opened */ closeBrotherCascadesOf(desc->parent); if (!wPreferences.wrap_menus) wMenuMove(parentMenu(desc->parent), old_frame_x, old_frame_y, True); byebye: /* Just to be sure in case we skip the 2 above because of a goto byebye */ if (menu && menu->timer) { WMDeleteTimerHandler(menu->timer); menu->timer = NULL; } if (d_data.magic != NULL) { WMDeleteTimerHandler(d_data.magic); d_data.magic = NULL; } ((WMenu *) desc->parent)->flags.inside_handler = 0; } void wMenuMove(WMenu * menu, int x, int y, int submenus) { WMenu *submenu; int i; if (!menu) return; menu->frame_x = x; menu->frame_y = y; XMoveWindow(dpy, menu->frame->core->window, x, y); if (submenus > 0 && menu->selected_entry >= 0) { i = menu->entries[menu->selected_entry]->cascade; if (i >= 0 && menu->cascades) { submenu = menu->cascades[i]; if (submenu->flags.mapped && !submenu->flags.buttoned) { if (wPreferences.align_menus) { wMenuMove(submenu, x + MENUW(menu), y, submenus); } else { wMenuMove(submenu, x + MENUW(menu), y + submenu->entry_height * menu->selected_entry, submenus); } } } } if (submenus < 0 && menu->parent != NULL && menu->parent->flags.mapped && !menu->parent->flags.buttoned) { if (wPreferences.align_menus) { wMenuMove(menu->parent, x - MENUW(menu->parent), y, submenus); } else { wMenuMove(menu->parent, x - MENUW(menu->parent), menu->frame_y - menu->parent->entry_height * menu->parent->selected_entry, submenus); } } } static void changeMenuLevels(WMenu * menu, int lower) { int i; if (!lower) { ChangeStackingLevel(menu->frame->core, (!menu->parent ? WMMainMenuLevel : WMSubmenuLevel)); wRaiseFrame(menu->frame->core); menu->flags.lowered = 0; } else { ChangeStackingLevel(menu->frame->core, WMNormalLevel); wLowerFrame(menu->frame->core); menu->flags.lowered = 1; } for (i = 0; i < menu->cascade_no; i++) { if (menu->cascades[i] && !menu->cascades[i]->flags.buttoned && menu->cascades[i]->flags.lowered != lower) { changeMenuLevels(menu->cascades[i], lower); } } } static void menuTitleDoubleClick(WCoreWindow * sender, void *data, XEvent * event) { WMenu *menu = data; int lower; /* Parameter not used, but tell the compiler that it is ok */ (void) sender; if (event->xbutton.state & MOD_MASK) { if (menu->flags.lowered) { lower = 0; } else { lower = 1; }
roblillack/wmaker
d9bc96e497a000b8b431d849a2524d9f7f1ea552
strncpy's third argument should be the length of the dest buffer, not the source.
diff --git a/src/event.c b/src/event.c index 39bf550..007b10b 100644 --- a/src/event.c +++ b/src/event.c @@ -497,1027 +497,1027 @@ static void handleDeadProcess(void) deadProcessPtr = 0; return; } /* get the pids on the queue and call handlers */ while (deadProcessPtr > 0) { deadProcessPtr--; for (i = WMGetArrayItemCount(deathHandlers) - 1; i >= 0; i--) { tmp = WMGetFromArray(deathHandlers, i); if (!tmp) continue; if (tmp->pid == deadProcesses[deadProcessPtr].pid) { (*tmp->callback) (tmp->pid, deadProcesses[deadProcessPtr].exit_status, tmp->client_data); wdelete_death_handler(tmp); } } } } static void saveTimestamp(XEvent * event) { /* * Never save CurrentTime as LastTimestamp because CurrentTime * it's not a real timestamp (it's the 0L constant) */ switch (event->type) { case ButtonRelease: case ButtonPress: w_global.timestamp.last_event = event->xbutton.time; break; case KeyPress: case KeyRelease: w_global.timestamp.last_event = event->xkey.time; break; case MotionNotify: w_global.timestamp.last_event = event->xmotion.time; break; case PropertyNotify: w_global.timestamp.last_event = event->xproperty.time; break; case EnterNotify: case LeaveNotify: w_global.timestamp.last_event = event->xcrossing.time; break; case SelectionClear: w_global.timestamp.last_event = event->xselectionclear.time; break; case SelectionRequest: w_global.timestamp.last_event = event->xselectionrequest.time; break; case SelectionNotify: w_global.timestamp.last_event = event->xselection.time; #ifdef USE_DOCK_XDND wXDNDProcessSelection(event); #endif break; } } static int matchWindow(const void *item, const void *cdata) { return (((WFakeGroupLeader *) item)->origLeader == (Window) cdata); } static void handleExtensions(XEvent * event) { #ifdef USE_XSHAPE if (w_global.xext.shape.supported && event->type == (w_global.xext.shape.event_base + ShapeNotify)) { handleShapeNotify(event); } #endif #ifdef KEEP_XKB_LOCK_STATUS if (wPreferences.modelock && (event->type == w_global.xext.xkb.event_base)) { handleXkbIndicatorStateNotify((XkbEvent *) event); } #endif /*KEEP_XKB_LOCK_STATUS */ #ifdef USE_RANDR if (w_global.xext.randr.supported && event->type == (w_global.xext.randr.event_base + RRScreenChangeNotify)) { /* From xrandr man page: "Clients must call back into Xlib using * XRRUpdateConfiguration when screen configuration change notify * events are generated */ XRRUpdateConfiguration(event); WCHANGE_STATE(WSTATE_RESTARTING); Shutdown(WSRestartPreparationMode); Restart(NULL,True); } #endif } static void handleMapRequest(XEvent * ev) { WWindow *wwin; WScreen *scr = NULL; Window window = ev->xmaprequest.window; wwin = wWindowFor(window); if (wwin != NULL) { if (wwin->flags.shaded) { wUnshadeWindow(wwin); } /* deiconify window */ if (wwin->flags.miniaturized) { wDeiconifyWindow(wwin); } else if (wwin->flags.hidden) { WApplication *wapp = wApplicationOf(wwin->main_window); /* go to the last workspace that the user worked on the app */ if (wapp) { wWorkspaceChange(wwin->screen_ptr, wapp->last_workspace); } wUnhideApplication(wapp, False, False); } return; } scr = wScreenForRootWindow(ev->xmaprequest.parent); wwin = wManageWindow(scr, window); /* * This is to let the Dock know that the application it launched * has already been mapped (eg: it has finished launching). * It is not necessary for normally docked apps, but is needed for * apps that were forcedly docked (like with dockit). */ if (scr->last_dock) { if (wwin && wwin->main_window != None && wwin->main_window != window) wDockTrackWindowLaunch(scr->last_dock, wwin->main_window); else wDockTrackWindowLaunch(scr->last_dock, window); } if (wwin) { wClientSetState(wwin, NormalState, None); if (wwin->flags.maximized) { wMaximizeWindow(wwin, wwin->flags.maximized, wGetHeadForWindow(wwin)); } if (wwin->flags.shaded) { wwin->flags.shaded = 0; wwin->flags.skip_next_animation = 1; wShadeWindow(wwin); } if (wwin->flags.miniaturized) { wwin->flags.miniaturized = 0; wwin->flags.skip_next_animation = 1; wIconifyWindow(wwin); } if (wwin->flags.fullscreen) { wwin->flags.fullscreen = 0; wFullscreenWindow(wwin); } if (wwin->flags.hidden) { WApplication *wapp = wApplicationOf(wwin->main_window); wwin->flags.hidden = 0; wwin->flags.skip_next_animation = 1; if (wapp) { wHideApplication(wapp); } } } } static void handleDestroyNotify(XEvent * event) { WWindow *wwin; WApplication *app; Window window = event->xdestroywindow.window; WScreen *scr = wScreenForRootWindow(event->xdestroywindow.event); int widx; wwin = wWindowFor(window); if (wwin) { wUnmanageWindow(wwin, False, True); } if (scr != NULL) { while ((widx = WMFindInArray(scr->fakeGroupLeaders, matchWindow, (void *)window)) != WANotFound) { WFakeGroupLeader *fPtr; fPtr = WMGetFromArray(scr->fakeGroupLeaders, widx); if (fPtr->retainCount > 0) { fPtr->retainCount--; if (fPtr->retainCount == 0 && fPtr->leader != None) { XDestroyWindow(dpy, fPtr->leader); fPtr->leader = None; XFlush(dpy); } } fPtr->origLeader = None; } } app = wApplicationOf(window); if (app) { if (window == app->main_window) { app->refcount = 0; wwin = app->main_window_desc->screen_ptr->focused_window; while (wwin) { if (wwin->main_window == window) { wwin->main_window = None; } wwin = wwin->prev; } } wApplicationDestroy(app); } } static void handleExpose(XEvent * event) { WObjDescriptor *desc; XEvent ev; while (XCheckTypedWindowEvent(dpy, event->xexpose.window, Expose, &ev)) ; if (XFindContext(dpy, event->xexpose.window, w_global.context.client_win, (XPointer *) & desc) == XCNOENT) { return; } if (desc->handle_expose) { (*desc->handle_expose) (desc, event); } } static void executeWheelAction(WScreen *scr, XEvent *event, int action) { WWindow *wwin; Bool next_direction; if (event->xbutton.button == Button5 || event->xbutton.button == Button6) next_direction = False; else next_direction = True; switch (action) { case WA_SWITCH_WORKSPACES: if (next_direction) wWorkspaceRelativeChange(scr, 1); else wWorkspaceRelativeChange(scr, -1); break; case WA_SWITCH_WINDOWS: wwin = scr->focused_window; if (next_direction) wWindowFocusNext(wwin, True); else wWindowFocusPrev(wwin, True); break; } } static void executeButtonAction(WScreen *scr, XEvent *event, int action) { WWindow *wwin; switch (action) { case WA_SELECT_WINDOWS: wUnselectWindows(scr); wSelectWindows(scr, event); break; case WA_OPEN_APPMENU: OpenRootMenu(scr, event->xbutton.x_root, event->xbutton.y_root, False); /* ugly hack */ if (scr->root_menu) { if (scr->root_menu->brother->flags.mapped) event->xbutton.window = scr->root_menu->brother->frame->core->window; else event->xbutton.window = scr->root_menu->frame->core->window; } break; case WA_OPEN_WINLISTMENU: OpenSwitchMenu(scr, event->xbutton.x_root, event->xbutton.y_root, False); if (scr->switch_menu) { if (scr->switch_menu->brother->flags.mapped) event->xbutton.window = scr->switch_menu->brother->frame->core->window; else event->xbutton.window = scr->switch_menu->frame->core->window; } break; case WA_MOVE_PREVWORKSPACE: wWorkspaceRelativeChange(scr, -1); break; case WA_MOVE_NEXTWORKSPACE: wWorkspaceRelativeChange(scr, 1); break; case WA_MOVE_PREVWINDOW: wwin = scr->focused_window; wWindowFocusPrev(wwin, True); break; case WA_MOVE_NEXTWINDOW: wwin = scr->focused_window; wWindowFocusNext(wwin, True); break; } } /* bindable */ static void handleButtonPress(XEvent * event) { WObjDescriptor *desc; WScreen *scr; scr = wScreenForRootWindow(event->xbutton.root); #ifdef BALLOON_TEXT wBalloonHide(scr); #endif if (!wPreferences.disable_root_mouse && event->xbutton.window == scr->root_win) { if (event->xbutton.button == Button1 && wPreferences.mouse_button1 != WA_NONE) { executeButtonAction(scr, event, wPreferences.mouse_button1); } else if (event->xbutton.button == Button2 && wPreferences.mouse_button2 != WA_NONE) { executeButtonAction(scr, event, wPreferences.mouse_button2); } else if (event->xbutton.button == Button3 && wPreferences.mouse_button3 != WA_NONE) { executeButtonAction(scr, event, wPreferences.mouse_button3); } else if (event->xbutton.button == Button8 && wPreferences.mouse_button8 != WA_NONE) { executeButtonAction(scr, event, wPreferences.mouse_button8); }else if (event->xbutton.button == Button9 && wPreferences.mouse_button9 != WA_NONE) { executeButtonAction(scr, event, wPreferences.mouse_button9); } else if (event->xbutton.button == Button4 && wPreferences.mouse_wheel_scroll != WA_NONE) { executeWheelAction(scr, event, wPreferences.mouse_wheel_scroll); } else if (event->xbutton.button == Button5 && wPreferences.mouse_wheel_scroll != WA_NONE) { executeWheelAction(scr, event, wPreferences.mouse_wheel_scroll); } else if (event->xbutton.button == Button6 && wPreferences.mouse_wheel_tilt != WA_NONE) { executeWheelAction(scr, event, wPreferences.mouse_wheel_tilt); } else if (event->xbutton.button == Button7 && wPreferences.mouse_wheel_tilt != WA_NONE) { executeWheelAction(scr, event, wPreferences.mouse_wheel_tilt); } } desc = NULL; if (XFindContext(dpy, event->xbutton.subwindow, w_global.context.client_win, (XPointer *) & desc) == XCNOENT) { if (XFindContext(dpy, event->xbutton.window, w_global.context.client_win, (XPointer *) & desc) == XCNOENT) { return; } } if (desc->parent_type == WCLASS_WINDOW) { XSync(dpy, 0); if (event->xbutton.state & ( MOD_MASK | ControlMask )) { XAllowEvents(dpy, AsyncPointer, CurrentTime); } else { /* if (wPreferences.focus_mode == WKF_CLICK) { */ if (wPreferences.ignore_focus_click) { XAllowEvents(dpy, AsyncPointer, CurrentTime); } XAllowEvents(dpy, ReplayPointer, CurrentTime); /* } */ } XSync(dpy, 0); } else if (desc->parent_type == WCLASS_APPICON || desc->parent_type == WCLASS_MINIWINDOW || desc->parent_type == WCLASS_DOCK_ICON) { if (event->xbutton.state & MOD_MASK) { XSync(dpy, 0); XAllowEvents(dpy, AsyncPointer, CurrentTime); XSync(dpy, 0); } } if (desc->handle_mousedown != NULL) { (*desc->handle_mousedown) (desc, event); } /* save double-click information */ if (scr->flags.next_click_is_not_double) { scr->flags.next_click_is_not_double = 0; } else { scr->last_click_time = event->xbutton.time; scr->last_click_button = event->xbutton.button; scr->last_click_window = event->xbutton.window; } } static void handleMapNotify(XEvent * event) { WWindow *wwin; wwin = wWindowFor(event->xmap.event); if (wwin && wwin->client_win == event->xmap.event) { if (wwin->flags.miniaturized) { wDeiconifyWindow(wwin); } else { XGrabServer(dpy); wWindowMap(wwin); wClientSetState(wwin, NormalState, None); XUngrabServer(dpy); } } } static void handleUnmapNotify(XEvent * event) { WWindow *wwin; XEvent ev; Bool withdraw = False; /* only process windows with StructureNotify selected * (ignore SubstructureNotify) */ wwin = wWindowFor(event->xunmap.window); if (!wwin) return; /* whether the event is a Withdrawal request */ if (event->xunmap.event == wwin->screen_ptr->root_win && event->xunmap.send_event) withdraw = True; if (wwin->client_win != event->xunmap.event && !withdraw) return; if (!wwin->flags.mapped && !withdraw && wwin->frame->workspace == wwin->screen_ptr->current_workspace && !wwin->flags.miniaturized && !wwin->flags.hidden) return; XGrabServer(dpy); XUnmapWindow(dpy, wwin->frame->core->window); wwin->flags.mapped = 0; XSync(dpy, 0); /* check if the window was destroyed */ if (XCheckTypedWindowEvent(dpy, wwin->client_win, DestroyNotify, &ev)) { DispatchEvent(&ev); } else { Bool reparented = False; if (XCheckTypedWindowEvent(dpy, wwin->client_win, ReparentNotify, &ev)) reparented = True; /* withdraw window */ wwin->flags.mapped = 0; if (!reparented) wClientSetState(wwin, WithdrawnState, None); /* if the window was reparented, do not reparent it back to the * root window */ wUnmanageWindow(wwin, !reparented, False); } XUngrabServer(dpy); } static void handleConfigureRequest(XEvent * event) { WWindow *wwin; wwin = wWindowFor(event->xconfigurerequest.window); if (wwin == NULL) { /* * Configure request for unmapped window */ wClientConfigure(NULL, &(event->xconfigurerequest)); } else { wClientConfigure(wwin, &(event->xconfigurerequest)); } } static void handlePropertyNotify(XEvent * event) { WWindow *wwin; WApplication *wapp; Window jr; int ji; unsigned int ju; wwin = wWindowFor(event->xproperty.window); if (wwin) { if (!XGetGeometry(dpy, wwin->client_win, &jr, &ji, &ji, &ju, &ju, &ju, &ju)) { return; } wClientCheckProperty(wwin, &event->xproperty); } wapp = wApplicationOf(event->xproperty.window); if (wapp) { wClientCheckProperty(wapp->main_window_desc, &event->xproperty); } } static void handleClientMessage(XEvent * event) { WWindow *wwin; WObjDescriptor *desc; /* handle transition from Normal to Iconic state */ if (event->xclient.message_type == w_global.atom.wm.change_state && event->xclient.format == 32 && event->xclient.data.l[0] == IconicState) { wwin = wWindowFor(event->xclient.window); if (!wwin) return; if (!wwin->flags.miniaturized) wIconifyWindow(wwin); } else if (event->xclient.message_type == w_global.atom.wm.colormap_notify && event->xclient.format == 32) { WScreen *scr = wScreenForRootWindow(event->xclient.window); if (!scr) return; if (event->xclient.data.l[1] == 1) { /* starting */ wColormapAllowClientInstallation(scr, True); } else { /* stopping */ wColormapAllowClientInstallation(scr, False); } } else if (event->xclient.message_type == w_global.atom.wmaker.command) { char *command; size_t len; - len = sizeof(event->xclient.data.b) + 1; - command = wmalloc(len); - strncpy(command, event->xclient.data.b, sizeof(event->xclient.data.b)); + len = sizeof(event->xclient.data.b); + command = wmalloc(len + 1); + strncpy(command, event->xclient.data.b, len); if (strncmp(command, "Reconfigure", sizeof("Reconfigure")) == 0) { wwarning(_("Got Reconfigure command")); wDefaultsCheckDomains(NULL); } else { wwarning(_("Got unknown command %s"), command); } wfree(command); } else if (event->xclient.message_type == w_global.atom.wmaker.wm_function) { WApplication *wapp; int done = 0; wapp = wApplicationOf(event->xclient.window); if (wapp) { switch (event->xclient.data.l[0]) { case WMFHideOtherApplications: wHideOtherApplications(wapp->main_window_desc); done = 1; break; case WMFHideApplication: wHideApplication(wapp); done = 1; break; } } if (!done) { wwin = wWindowFor(event->xclient.window); if (wwin) { switch (event->xclient.data.l[0]) { case WMFHideOtherApplications: wHideOtherApplications(wwin); break; case WMFHideApplication: wHideApplication(wApplicationOf(wwin->main_window)); break; } } } } else if (event->xclient.message_type == w_global.atom.gnustep.wm_attr) { wwin = wWindowFor(event->xclient.window); if (!wwin) return; switch (event->xclient.data.l[0]) { case GSWindowLevelAttr: { int level = (int)event->xclient.data.l[1]; if (WINDOW_LEVEL(wwin) != level) { ChangeStackingLevel(wwin->frame->core, level); } } break; } } else if (event->xclient.message_type == w_global.atom.gnustep.titlebar_state) { wwin = wWindowFor(event->xclient.window); if (!wwin) return; switch (event->xclient.data.l[0]) { case WMTitleBarNormal: wFrameWindowChangeState(wwin->frame, WS_UNFOCUSED); break; case WMTitleBarMain: wFrameWindowChangeState(wwin->frame, WS_PFOCUSED); break; case WMTitleBarKey: wFrameWindowChangeState(wwin->frame, WS_FOCUSED); break; } } else if (event->xclient.message_type == w_global.atom.wm.ignore_focus_events) { WScreen *scr = wScreenForRootWindow(event->xclient.window); if (!scr) return; scr->flags.ignore_focus_events = event->xclient.data.l[0] ? 1 : 0; } else if (wNETWMProcessClientMessage(&event->xclient)) { /* do nothing */ #ifdef USE_DOCK_XDND } else if (wXDNDProcessClientMessage(&event->xclient)) { /* do nothing */ #endif /* USE_DOCK_XDND */ } else { /* * Non-standard thing, but needed by OffiX DND. * For when the icon frame gets a ClientMessage * that should have gone to the icon_window. */ if (XFindContext(dpy, event->xbutton.window, w_global.context.client_win, (XPointer *) & desc) != XCNOENT) { struct WIcon *icon = NULL; if (desc->parent_type == WCLASS_MINIWINDOW) { icon = (WIcon *) desc->parent; } else if (desc->parent_type == WCLASS_DOCK_ICON || desc->parent_type == WCLASS_APPICON) { icon = ((WAppIcon *) desc->parent)->icon; } if (icon && (wwin = icon->owner)) { if (wwin->client_win != event->xclient.window) { event->xclient.window = wwin->client_win; XSendEvent(dpy, wwin->client_win, False, NoEventMask, event); } } } } } static void raiseWindow(WScreen * scr) { WWindow *wwin; scr->autoRaiseTimer = NULL; wwin = wWindowFor(scr->autoRaiseWindow); if (!wwin) return; if (!wwin->flags.destroyed && wwin->flags.focused) { wRaiseFrame(wwin->frame->core); /* this is needed or a race condition will occur */ XSync(dpy, False); } } static void handleEnterNotify(XEvent * event) { WWindow *wwin; WObjDescriptor *desc = NULL; XEvent ev; WScreen *scr = wScreenForRootWindow(event->xcrossing.root); if (XCheckTypedWindowEvent(dpy, event->xcrossing.window, LeaveNotify, &ev)) { /* already left the window... */ saveTimestamp(&ev); if (ev.xcrossing.mode == event->xcrossing.mode && ev.xcrossing.detail == event->xcrossing.detail) { return; } } if (XFindContext(dpy, event->xcrossing.window, w_global.context.client_win, (XPointer *) & desc) != XCNOENT) { if (desc->handle_enternotify) (*desc->handle_enternotify) (desc, event); } /* enter to window */ wwin = wWindowFor(event->xcrossing.window); if (!wwin) { if (wPreferences.colormap_mode == WCM_POINTER) { wColormapInstallForWindow(scr, NULL); } if (scr->autoRaiseTimer && event->xcrossing.root == event->xcrossing.window) { WMDeleteTimerHandler(scr->autoRaiseTimer); scr->autoRaiseTimer = NULL; } } else { /* set auto raise timer even if in focus-follows-mouse mode * and the event is for the frame window, even if the window * has focus already. useful if you move the pointer from a focused * window to the root window and back pretty fast * * set focus if in focus-follows-mouse mode and the event * is for the frame window and window doesn't have focus yet */ if (wPreferences.focus_mode == WKF_SLOPPY && wwin->frame->core->window == event->xcrossing.window && !scr->flags.doing_alt_tab) { if (!wwin->flags.focused && !WFLAGP(wwin, no_focusable)) wSetFocusTo(scr, wwin); if (scr->autoRaiseTimer) WMDeleteTimerHandler(scr->autoRaiseTimer); scr->autoRaiseTimer = NULL; if (wPreferences.raise_delay && !WFLAGP(wwin, no_focusable)) { scr->autoRaiseWindow = wwin->frame->core->window; scr->autoRaiseTimer = WMAddTimerHandler(wPreferences.raise_delay, (WMCallback *) raiseWindow, scr); } } /* Install colormap for window, if the colormap installation mode * is colormap_follows_mouse */ if (wPreferences.colormap_mode == WCM_POINTER) { if (wwin->client_win == event->xcrossing.window) wColormapInstallForWindow(scr, wwin); else wColormapInstallForWindow(scr, NULL); } } if (event->xcrossing.window == event->xcrossing.root && event->xcrossing.detail == NotifyNormal && event->xcrossing.detail != NotifyInferior && wPreferences.focus_mode != WKF_CLICK) { wSetFocusTo(scr, scr->focused_window); } #ifdef BALLOON_TEXT wBalloonEnteredObject(scr, desc); #endif } static void handleLeaveNotify(XEvent * event) { WObjDescriptor *desc = NULL; if (XFindContext(dpy, event->xcrossing.window, w_global.context.client_win, (XPointer *) & desc) != XCNOENT) { if (desc->handle_leavenotify) (*desc->handle_leavenotify) (desc, event); } } #ifdef USE_XSHAPE static void handleShapeNotify(XEvent * event) { XShapeEvent *shev = (XShapeEvent *) event; WWindow *wwin; union { XEvent xevent; XShapeEvent xshape; } ev; while (XCheckTypedWindowEvent(dpy, shev->window, event->type, &ev.xevent)) { if (ev.xshape.kind == ShapeBounding) { if (ev.xshape.shaped == shev->shaped) { *shev = ev.xshape; } else { XPutBackEvent(dpy, &ev.xevent); break; } } } wwin = wWindowFor(shev->window); if (!wwin || shev->kind != ShapeBounding) return; if (!shev->shaped && wwin->flags.shaped) { wwin->flags.shaped = 0; wWindowClearShape(wwin); } else if (shev->shaped) { wwin->flags.shaped = 1; wWindowSetShape(wwin); } } #endif /* USE_XSHAPE */ #ifdef KEEP_XKB_LOCK_STATUS /* please help ]d if you know what to do */ static void handleXkbIndicatorStateNotify(XkbEvent *event) { WWindow *wwin; WScreen *scr; XkbStateRec staterec; int i; for (i = 0; i < w_global.screen_count; i++) { scr = wScreenWithNumber(i); wwin = scr->focused_window; if (wwin && wwin->flags.focused) { XkbGetState(dpy, XkbUseCoreKbd, &staterec); if (wwin->frame->languagemode != staterec.group) { wwin->frame->last_languagemode = wwin->frame->languagemode; wwin->frame->languagemode = staterec.group; } #ifdef XKB_BUTTON_HINT if (wwin->frame->titlebar) { wFrameWindowPaint(wwin->frame); } #endif } } } #endif /*KEEP_XKB_LOCK_STATUS */ static void handleColormapNotify(XEvent * event) { WWindow *wwin; WScreen *scr; Bool reinstall = False; wwin = wWindowFor(event->xcolormap.window); if (!wwin) return; scr = wwin->screen_ptr; do { if (wwin) { if (event->xcolormap.new) { XWindowAttributes attr; XGetWindowAttributes(dpy, wwin->client_win, &attr); if (wwin == scr->cmap_window && wwin->cmap_window_no == 0) scr->current_colormap = attr.colormap; reinstall = True; } else if (event->xcolormap.state == ColormapUninstalled && scr->current_colormap == event->xcolormap.colormap) { /* some bastard app (like XV) removed our colormap */ /* * can't enforce or things like xscreensaver won't work * reinstall = True; */ } else if (event->xcolormap.state == ColormapInstalled && scr->current_colormap == event->xcolormap.colormap) { /* someone has put our colormap back */ reinstall = False; } } } while (XCheckTypedEvent(dpy, ColormapNotify, event) && ((wwin = wWindowFor(event->xcolormap.window)) || 1)); if (reinstall && scr->current_colormap != None) { if (!scr->flags.colormap_stuff_blocked) XInstallColormap(dpy, scr->current_colormap); } } static void handleFocusIn(XEvent * event) { WWindow *wwin; /* * For applications that like stealing the focus. */ while (XCheckTypedEvent(dpy, FocusIn, event)) ; saveTimestamp(event); if (event->xfocus.mode == NotifyUngrab || event->xfocus.mode == NotifyGrab || event->xfocus.detail > NotifyNonlinearVirtual) { return; } wwin = wWindowFor(event->xfocus.window); if (wwin && !wwin->flags.focused) { if (wwin->flags.mapped) wSetFocusTo(wwin->screen_ptr, wwin); else wSetFocusTo(wwin->screen_ptr, NULL); } else if (!wwin) { WScreen *scr = wScreenForWindow(event->xfocus.window); if (scr) wSetFocusTo(scr, NULL); } } static WWindow *windowUnderPointer(WScreen * scr) { unsigned int mask; int foo; Window bar, win; if (XQueryPointer(dpy, scr->root_win, &bar, &win, &foo, &foo, &foo, &foo, &mask)) return wWindowFor(win); return NULL; } static int CheckFullScreenWindowFocused(WScreen * scr) { if (scr->focused_window && scr->focused_window->flags.fullscreen) return 1; else return 0; } static void handleKeyPress(XEvent * event) { WScreen *scr = wScreenForRootWindow(event->xkey.root); WWindow *wwin = scr->focused_window; short i, widx; int modifiers; int command = -1; #ifdef KEEP_XKB_LOCK_STATUS XkbStateRec staterec; #endif /*KEEP_XKB_LOCK_STATUS */ /* ignore CapsLock */ modifiers = event->xkey.state & w_global.shortcut.modifiers_mask; for (i = 0; i < WKBD_LAST; i++) { if (wKeyBindings[i].keycode == 0) continue; if (wKeyBindings[i].keycode == event->xkey.keycode && ( /*wKeyBindings[i].modifier==0 || */ wKeyBindings[i].modifier == modifiers)) { command = i; break; } } if (command < 0) { if (!wRootMenuPerformShortcut(event)) { static int dontLoop = 0; if (dontLoop > 10) { wwarning("problem with key event processing code"); return; } dontLoop++; /* if the focused window is an internal window, try redispatching * the event to the managed window, as it can be a WINGs window */ if (wwin && wwin->flags.internal_window && wwin->client_leader != None) { /* client_leader contains the WINGs toplevel */ event->xany.window = wwin->client_leader; WMHandleEvent(event); } dontLoop--; } return; } #define ISMAPPED(w) ((w) && !(w)->flags.miniaturized && ((w)->flags.mapped || (w)->flags.shaded)) #define ISFOCUSED(w) ((w) && (w)->flags.focused) switch (command) { case WKBD_ROOTMENU: /*OpenRootMenu(scr, event->xkey.x_root, event->xkey.y_root, True); */ if (!CheckFullScreenWindowFocused(scr)) { WMRect rect = wGetRectForHead(scr, wGetHeadForPointerLocation(scr)); OpenRootMenu(scr, rect.pos.x + rect.size.width / 2, rect.pos.y + rect.size.height / 2, True); } break; case WKBD_WINDOWLIST: if (!CheckFullScreenWindowFocused(scr)) { WMRect rect = wGetRectForHead(scr, wGetHeadForPointerLocation(scr)); OpenSwitchMenu(scr, rect.pos.x + rect.size.width / 2, rect.pos.y + rect.size.height / 2, True); } break; case WKBD_WINDOWMENU: if (ISMAPPED(wwin) && ISFOCUSED(wwin)) OpenWindowMenu(wwin, wwin->frame_x, wwin->frame_y + wwin->frame->top_width, True); break; case WKBD_MINIMIZEALL: CloseWindowMenu(scr); wHideAll(scr); break; case WKBD_MINIATURIZE: if (ISMAPPED(wwin) && ISFOCUSED(wwin) && !WFLAGP(wwin, no_miniaturizable)) { CloseWindowMenu(scr); if (wwin->protocols.MINIATURIZE_WINDOW) wClientSendProtocol(wwin, w_global.atom.gnustep.wm_miniaturize_window, event->xbutton.time); else { wIconifyWindow(wwin); } } break; case WKBD_HIDE: if (ISMAPPED(wwin) && ISFOCUSED(wwin)) { WApplication *wapp = wApplicationOf(wwin->main_window); CloseWindowMenu(scr); if (wapp && !WFLAGP(wapp->main_window_desc, no_appicon)) { wHideApplication(wapp); } } break; case WKBD_HIDE_OTHERS: if (ISMAPPED(wwin) && ISFOCUSED(wwin)) { CloseWindowMenu(scr); wHideOtherApplications(wwin); } break; case WKBD_MAXIMIZE: if (ISMAPPED(wwin) && ISFOCUSED(wwin) && IS_RESIZABLE(wwin)) { CloseWindowMenu(scr); handleMaximize(wwin, MAX_VERTICAL | MAX_HORIZONTAL | MAX_KEYBOARD); } break; case WKBD_VMAXIMIZE: if (ISMAPPED(wwin) && ISFOCUSED(wwin) && IS_RESIZABLE(wwin)) { CloseWindowMenu(scr); handleMaximize(wwin, MAX_VERTICAL | MAX_KEYBOARD); } break; case WKBD_HMAXIMIZE: if (ISMAPPED(wwin) && ISFOCUSED(wwin) && IS_RESIZABLE(wwin)) { CloseWindowMenu(scr); handleMaximize(wwin, MAX_HORIZONTAL | MAX_KEYBOARD); movePionterToWindowCenter(wwin); } break; case WKBD_LHMAXIMIZE: if (ISMAPPED(wwin) && ISFOCUSED(wwin) && IS_RESIZABLE(wwin)) { CloseWindowMenu(scr); handleMaximize(wwin, MAX_VERTICAL | MAX_LEFTHALF | MAX_KEYBOARD); movePionterToWindowCenter(wwin); } break; case WKBD_RHMAXIMIZE: if (ISMAPPED(wwin) && ISFOCUSED(wwin) && IS_RESIZABLE(wwin)) { CloseWindowMenu(scr); handleMaximize(wwin, MAX_VERTICAL | MAX_RIGHTHALF | MAX_KEYBOARD); movePionterToWindowCenter(wwin); } break; case WKBD_THMAXIMIZE: if (ISMAPPED(wwin) && ISFOCUSED(wwin) && IS_RESIZABLE(wwin)) {
roblillack/wmaker
a7baed6cf702f56d4932c45b4111980130a02285
Fixed expression checking whether flag is set.
diff --git a/src/motif.c b/src/motif.c index 34f6847..df439a8 100644 --- a/src/motif.c +++ b/src/motif.c @@ -1,196 +1,196 @@ /* motif.c-- stuff for support for mwm hints * * Window Maker window manager * * Copyright (c) 1998-2003 Alfredo K. Kojima * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "wconfig.h" #include <X11/Xlib.h> #include <X11/Xutil.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include "WindowMaker.h" #include "framewin.h" #include "window.h" #include "properties.h" #include "icon.h" #include "client.h" #include "motif.h" /* Motif window hints */ #define MWM_HINTS_FUNCTIONS (1L << 0) #define MWM_HINTS_DECORATIONS (1L << 1) /* bit definitions for MwmHints.functions */ #define MWM_FUNC_ALL (1L << 0) #define MWM_FUNC_RESIZE (1L << 1) #define MWM_FUNC_MOVE (1L << 2) #define MWM_FUNC_MINIMIZE (1L << 3) #define MWM_FUNC_MAXIMIZE (1L << 4) #define MWM_FUNC_CLOSE (1L << 5) /* bit definitions for MwmHints.decorations */ #define MWM_DECOR_ALL (1L << 0) #define MWM_DECOR_BORDER (1L << 1) #define MWM_DECOR_RESIZEH (1L << 2) #define MWM_DECOR_TITLE (1L << 3) #define MWM_DECOR_MENU (1L << 4) #define MWM_DECOR_MINIMIZE (1L << 5) #define MWM_DECOR_MAXIMIZE (1L << 6) /* Motif window hints */ typedef struct { long flags; long functions; long decorations; long inputMode; long unknown; } MWMHints; static Atom _XA_MOTIF_WM_HINTS; static void setupMWMHints(WWindow *wwin, MWMHints *mwm_hints) { /* * We will ignore all decoration hints that have an equivalent as * functions, because wmaker does not distinguish decoration hints */ if (mwm_hints->flags & MWM_HINTS_DECORATIONS) { wwin->client_flags.no_titlebar = 1; wwin->client_flags.no_close_button = 1; wwin->client_flags.no_miniaturize_button = 1; wwin->client_flags.no_resizebar = 1; wwin->client_flags.no_border = 1; if (mwm_hints->decorations & MWM_DECOR_ALL) { wwin->client_flags.no_titlebar = 0; wwin->client_flags.no_close_button = 0; wwin->client_flags.no_closable = 0; wwin->client_flags.no_miniaturize_button = 0; wwin->client_flags.no_miniaturizable = 0; wwin->client_flags.no_resizebar = 0; wwin->client_flags.no_resizable = 0; wwin->client_flags.no_border = 0; } if (mwm_hints->decorations & MWM_DECOR_BORDER) { wwin->client_flags.no_border = 0; } if (mwm_hints->decorations & MWM_DECOR_RESIZEH) wwin->client_flags.no_resizebar = 0; if (mwm_hints->decorations & MWM_DECOR_TITLE) { wwin->client_flags.no_titlebar = 0; wwin->client_flags.no_close_button = 0; wwin->client_flags.no_closable = 0; } - if (mwm_hints->decorations * MWM_DECOR_MENU) { + if (mwm_hints->decorations & MWM_DECOR_MENU) { /* * WindowMaker does not include a button to display the menu * for windows, this is done using right mouse button on the * title bar. As a consequence, we ignore this flag because we * have nothing to hide. */ } if (mwm_hints->decorations & MWM_DECOR_MINIMIZE) { wwin->client_flags.no_miniaturize_button = 0; wwin->client_flags.no_miniaturizable = 0; } if (mwm_hints->decorations & MWM_DECOR_MAXIMIZE) { /* * WindowMaker does not display a button to maximize windows, * so we don't need to hide anything more for that flag */ } } if (mwm_hints->flags & MWM_HINTS_FUNCTIONS) { wwin->client_flags.no_closable = 1; wwin->client_flags.no_miniaturizable = 1; wwin->client_flags.no_resizable = 1; if (mwm_hints->functions & MWM_FUNC_ALL) { wwin->client_flags.no_closable = 0; wwin->client_flags.no_miniaturizable = 0; wwin->client_flags.no_resizable = 0; } if (mwm_hints->functions & MWM_FUNC_RESIZE) wwin->client_flags.no_resizable = 0; if (mwm_hints->functions & MWM_FUNC_MOVE) { /* * WindowMaker does not allow a window to not be moved, and this * is a good thing, so we explicitly ignore this flag. */ } if (mwm_hints->functions & MWM_FUNC_MINIMIZE) wwin->client_flags.no_miniaturizable = 0; if (mwm_hints->functions & MWM_FUNC_MAXIMIZE) { /* a window must be resizable to be maximizable */ wwin->client_flags.no_resizable = 0; } if (mwm_hints->functions & MWM_FUNC_CLOSE) wwin->client_flags.no_closable = 0; } } static int getMWMHints(Window window, MWMHints *mwmhints) { unsigned long *data; int count; if (!_XA_MOTIF_WM_HINTS) _XA_MOTIF_WM_HINTS = XInternAtom(dpy, "_MOTIF_WM_HINTS", False); data = (unsigned long *)PropGetCheckProperty(window, _XA_MOTIF_WM_HINTS, _XA_MOTIF_WM_HINTS, 32, 0, &count); if (!data) return 0; mwmhints->flags = 0; if (count >= 4) { mwmhints->flags = data[0]; mwmhints->functions = data[1]; mwmhints->decorations = data[2]; mwmhints->inputMode = data[3]; if (count > 5) mwmhints->unknown = data[4]; } XFree(data); return 1; } void wMWMCheckClientHints(WWindow *wwin) { MWMHints hints; if (getMWMHints(wwin->client_win, &hints)) setupMWMHints(wwin, &hints); }
roblillack/wmaker
a12f0d453ac26c300b74fb7a8bf4dd1d08594803
Fixed buffer size.
diff --git a/src/dock.c b/src/dock.c index 86eef57..c956eab 100644 --- a/src/dock.c +++ b/src/dock.c @@ -883,1033 +883,1033 @@ static void switchWSCommand(WMenu *menu, WMenuEntry *entry) dest = scr->workspaces[entry->order]->clip; selectedIcons = getSelected(src); if (WMGetArrayItemCount(selectedIcons)) { WMArrayIterator iter; WM_ITERATE_ARRAY(selectedIcons, btn, iter) { if (wDockFindFreeSlot(dest, &x, &y)) { wDockMoveIconBetweenDocks(src, dest, btn, x, y); XUnmapWindow(dpy, btn->icon->core->window); } } } else if (icon != scr->clip_icon) { if (wDockFindFreeSlot(dest, &x, &y)) { wDockMoveIconBetweenDocks(src, dest, icon, x, y); XUnmapWindow(dpy, icon->icon->core->window); } } WMFreeArray(selectedIcons); } static void launchDockedApplication(WAppIcon *btn, Bool withSelection) { WScreen *scr = btn->icon->core->screen_ptr; if (!btn->launching && ((!withSelection && btn->command != NULL) || (withSelection && btn->paste_command != NULL))) { if (!btn->forced_dock) { btn->relaunching = btn->running; btn->running = 1; } if (btn->wm_instance || btn->wm_class) { WWindowAttributes attr; memset(&attr, 0, sizeof(WWindowAttributes)); wDefaultFillAttributes(btn->wm_instance, btn->wm_class, &attr, NULL, True); if (!attr.no_appicon && !btn->buggy_app) btn->launching = 1; else btn->running = 0; } btn->drop_launch = 0; btn->paste_launch = withSelection; scr->last_dock = btn->dock; btn->pid = execCommand(btn, (withSelection ? btn->paste_command : btn->command), NULL); if (btn->pid > 0) { if (btn->buggy_app) { /* give feedback that the app was launched */ btn->launching = 1; dockIconPaint(btn); btn->launching = 0; WMAddTimerHandler(200, (WMCallback *) dockIconPaint, btn); } else { dockIconPaint(btn); } } else { wwarning(_("could not launch application %s"), btn->command); btn->launching = 0; if (!btn->relaunching) btn->running = 0; } } } static void updateWorkspaceMenu(WMenu *menu, WAppIcon *icon) { WScreen *scr = menu->frame->screen_ptr; int i; if (!menu || !icon) return; for (i = 0; i < scr->workspace_count; i++) { if (i < menu->entry_no) { if (strcmp(menu->entries[i]->text, scr->workspaces[i]->name) != 0) { wfree(menu->entries[i]->text); menu->entries[i]->text = wstrdup(scr->workspaces[i]->name); menu->flags.realized = 0; } menu->entries[i]->clientdata = (void *)icon; } else { wMenuAddCallback(menu, scr->workspaces[i]->name, switchWSCommand, (void *)icon); menu->flags.realized = 0; } if (i == scr->current_workspace) wMenuSetEnabled(menu, i, False); else wMenuSetEnabled(menu, i, True); } if (!menu->flags.realized) wMenuRealize(menu); } static WMenu *makeWorkspaceMenu(WScreen *scr) { WMenu *menu; menu = wMenuCreate(scr, NULL, False); if (!menu) wwarning(_("could not create workspace submenu for Clip menu")); wMenuAddCallback(menu, "", switchWSCommand, (void *)scr->clip_icon); menu->flags.realized = 0; wMenuRealize(menu); return menu; } static void updateClipOptionsMenu(WMenu *menu, WDock *dock) { WMenuEntry *entry; int index = 0; if (!menu || !dock) return; /* keep on top */ entry = menu->entries[index]; entry->flags.indicator_on = !dock->lowered; entry->clientdata = dock; wMenuSetEnabled(menu, index, dock->type == WM_CLIP); /* collapsed */ entry = menu->entries[++index]; entry->flags.indicator_on = dock->collapsed; entry->clientdata = dock; /* auto-collapse */ entry = menu->entries[++index]; entry->flags.indicator_on = dock->auto_collapse; entry->clientdata = dock; /* auto-raise/lower */ entry = menu->entries[++index]; entry->flags.indicator_on = dock->auto_raise_lower; entry->clientdata = dock; wMenuSetEnabled(menu, index, dock->lowered && (dock->type == WM_CLIP)); /* attract icons */ entry = menu->entries[++index]; entry->flags.indicator_on = dock->attract_icons; entry->clientdata = dock; menu->flags.realized = 0; wMenuRealize(menu); } static WMenu *makeClipOptionsMenu(WScreen *scr) { WMenu *menu; WMenuEntry *entry; menu = wMenuCreate(scr, NULL, False); if (!menu) { wwarning(_("could not create options submenu for Clip menu")); return NULL; } entry = wMenuAddCallback(menu, _("Keep on Top"), toggleLoweredCallback, NULL); entry->flags.indicator = 1; entry->flags.indicator_on = 1; entry->flags.indicator_type = MI_CHECK; entry = wMenuAddCallback(menu, _("Collapsed"), toggleCollapsedCallback, NULL); entry->flags.indicator = 1; entry->flags.indicator_on = 1; entry->flags.indicator_type = MI_CHECK; entry = wMenuAddCallback(menu, _("Autocollapse"), toggleAutoCollapseCallback, NULL); entry->flags.indicator = 1; entry->flags.indicator_on = 1; entry->flags.indicator_type = MI_CHECK; entry = wMenuAddCallback(menu, _("Autoraise"), toggleAutoRaiseLowerCallback, NULL); entry->flags.indicator = 1; entry->flags.indicator_on = 1; entry->flags.indicator_type = MI_CHECK; entry = wMenuAddCallback(menu, _("Autoattract Icons"), toggleAutoAttractCallback, NULL); entry->flags.indicator = 1; entry->flags.indicator_on = 1; entry->flags.indicator_type = MI_CHECK; menu->flags.realized = 0; wMenuRealize(menu); return menu; } static void setDockPositionNormalCallback(WMenu *menu, WMenuEntry *entry) { WDock *dock = (WDock *) entry->clientdata; WDrawerChain *dc; /* Parameter not used, but tell the compiler that it is ok */ (void) menu; if (entry->flags.indicator_on) // already set, nothing to do return; // Do we come from auto raise lower or keep on top? if (dock->auto_raise_lower) { dock->auto_raise_lower = 0; // Only for aesthetic purposes, can be removed when Autoraise status is no longer exposed in drawer option menu for (dc = dock->screen_ptr->drawers; dc != NULL; dc = dc->next) { dc->adrawer->auto_raise_lower = 0; } } else { // Will take care of setting lowered = 0 in drawers toggleLowered(dock); } entry->flags.indicator_on = 1; } static void setDockPositionAutoRaiseLowerCallback(WMenu *menu, WMenuEntry *entry) { WDock *dock = (WDock *) entry->clientdata; WDrawerChain *dc; /* Parameter not used, but tell the compiler that it is ok */ (void) menu; if (entry->flags.indicator_on) // already set, nothing to do return; // Do we come from normal or keep on top? if (!dock->lowered) { toggleLowered(dock); } dock->auto_raise_lower = 1; // Only for aesthetic purposes, can be removed when Autoraise status is no longer exposed in drawer option menu for (dc = dock->screen_ptr->drawers; dc != NULL; dc = dc->next) { dc->adrawer->auto_raise_lower = 1; } entry->flags.indicator_on = 1; } static void setDockPositionKeepOnTopCallback(WMenu *menu, WMenuEntry *entry) { WDock *dock = (WDock *) entry->clientdata; WDrawerChain *dc; /* Parameter not used, but tell the compiler that it is ok */ (void) menu; if (entry->flags.indicator_on) // already set, nothing to do return; dock->auto_raise_lower = 0; // Only for aesthetic purposes, can be removed when Autoraise status is no longer exposed in drawer option menu for (dc = dock->screen_ptr->drawers; dc != NULL; dc = dc->next) { dc->adrawer->auto_raise_lower = 0; } toggleLowered(dock); entry->flags.indicator_on = 1; } static void updateDockPositionMenu(WMenu *menu, WDock *dock) { WMenuEntry *entry; int index = 0; assert(menu); assert(dock); /* Normal level */ entry = menu->entries[index++]; entry->flags.indicator_on = (dock->lowered && !dock->auto_raise_lower); entry->clientdata = dock; /* Auto-raise/lower */ entry = menu->entries[index++]; entry->flags.indicator_on = dock->auto_raise_lower; entry->clientdata = dock; /* Keep on top */ entry = menu->entries[index++]; entry->flags.indicator_on = !dock->lowered; entry->clientdata = dock; } static WMenu *makeDockPositionMenu(WScreen *scr) { /* When calling this, the dock is being created, so scr->dock is still not set * Therefore the callbacks' clientdata and the indicators can't be set, * they will be updated when the dock menu is opened. */ WMenu *menu; WMenuEntry *entry; menu = wMenuCreate(scr, NULL, False); if (!menu) { wwarning(_("could not create options submenu for dock position menu")); return NULL; } entry = wMenuAddCallback(menu, _("Normal"), setDockPositionNormalCallback, NULL); entry->flags.indicator = 1; entry->flags.indicator_type = MI_DIAMOND; entry = wMenuAddCallback(menu, _("Auto raise & lower"), setDockPositionAutoRaiseLowerCallback, NULL); entry->flags.indicator = 1; entry->flags.indicator_type = MI_DIAMOND; entry = wMenuAddCallback(menu, _("Keep on Top"), setDockPositionKeepOnTopCallback, NULL); entry->flags.indicator = 1; entry->flags.indicator_type = MI_DIAMOND; menu->flags.realized = 0; wMenuRealize(menu); return menu; } static WMenu *dockMenuCreate(WScreen *scr, int type) { WMenu *menu; WMenuEntry *entry; if (type == WM_CLIP && scr->clip_menu) return scr->clip_menu; if (type == WM_DRAWER && scr->drawer_menu) return scr->drawer_menu; menu = wMenuCreate(scr, NULL, False); if (type == WM_DOCK) { entry = wMenuAddCallback(menu, _("Dock position"), NULL, NULL); if (scr->dock_pos_menu == NULL) scr->dock_pos_menu = makeDockPositionMenu(scr); wMenuEntrySetCascade(menu, entry, scr->dock_pos_menu); if (!wPreferences.flags.nodrawer) wMenuAddCallback(menu, _("Add a drawer"), addADrawerCallback, NULL); } else { if (type == WM_CLIP) entry = wMenuAddCallback(menu, _("Clip Options"), NULL, NULL); else /* if (type == WM_DRAWER) */ entry = wMenuAddCallback(menu, _("Drawer options"), NULL, NULL); if (scr->clip_options == NULL) scr->clip_options = makeClipOptionsMenu(scr); wMenuEntrySetCascade(menu, entry, scr->clip_options); /* The same menu is used for the dock and its appicons. If the menu * entry text is different between the two contexts, or if it can * change depending on some state, free the duplicated string (from * wMenuInsertCallback) and use gettext's string */ if (type == WM_CLIP) { entry = wMenuAddCallback(menu, _("Rename Workspace"), renameCallback, NULL); wfree(entry->text); entry->text = _("Rename Workspace"); /* can be: (Toggle) Omnipresent */ } entry = wMenuAddCallback(menu, _("Selected"), selectCallback, NULL); entry->flags.indicator = 1; entry->flags.indicator_on = 1; entry->flags.indicator_type = MI_CHECK; entry = wMenuAddCallback(menu, _("Select All Icons"), selectIconsCallback, NULL); wfree(entry->text); entry->text = _("Select All Icons"); /* can be: Unselect all icons */ entry = wMenuAddCallback(menu, _("Keep Icon"), keepIconsCallback, NULL); wfree(entry->text); entry->text = _("Keep Icon"); /* can be: Keep Icons */ if (type == WM_CLIP) { entry = wMenuAddCallback(menu, _("Move Icon To"), NULL, NULL); wfree(entry->text); entry->text = _("Move Icon To"); /* can be: Move Icons to */ scr->clip_submenu = makeWorkspaceMenu(scr); if (scr->clip_submenu) wMenuEntrySetCascade(menu, entry, scr->clip_submenu); } entry = wMenuAddCallback(menu, _("Remove Icon"), removeIconsCallback, NULL); wfree(entry->text); entry->text = _("Remove Icon"); /* can be: Remove Icons */ wMenuAddCallback(menu, _("Attract Icons"), attractIconsCallback, NULL); } wMenuAddCallback(menu, _("Launch"), launchCallback, NULL); wMenuAddCallback(menu, _("Unhide Here"), unhideHereCallback, NULL); entry = wMenuAddCallback(menu, _("Hide"), hideCallback, NULL); wfree(entry->text); entry->text = _("Hide"); /* can be: Unhide */ wMenuAddCallback(menu, _("Settings..."), settingsCallback, NULL); entry = wMenuAddCallback(menu, _("Kill"), killCallback, NULL); wfree(entry->text); entry->text = _("Kill"); /* can be: Remove drawer */ if (type == WM_CLIP) scr->clip_menu = menu; if (type == WM_DRAWER) scr->drawer_menu = menu; return menu; } WDock *wDockCreate(WScreen *scr, int type, const char *name) { WDock *dock; WAppIcon *btn; make_keys(); dock = wmalloc(sizeof(WDock)); switch (type) { case WM_CLIP: dock->max_icons = DOCK_MAX_ICONS; break; case WM_DRAWER: dock->max_icons = scr->scr_width / wPreferences.icon_size; break; case WM_DOCK: default: dock->max_icons = scr->scr_height / wPreferences.icon_size; } dock->icon_array = wmalloc(sizeof(WAppIcon *) * dock->max_icons); btn = mainIconCreate(scr, type, name); btn->dock = dock; dock->x_pos = btn->x_pos; dock->y_pos = btn->y_pos; dock->screen_ptr = scr; dock->type = type; dock->icon_count = 1; if (type == WM_DRAWER) dock->on_right_side = scr->dock->on_right_side; else dock->on_right_side = 1; dock->collapsed = 0; dock->auto_collapse = 0; dock->auto_collapse_magic = NULL; dock->auto_raise_lower = 0; dock->auto_lower_magic = NULL; dock->auto_raise_magic = NULL; dock->attract_icons = 0; dock->lowered = 1; dock->icon_array[0] = btn; wRaiseFrame(btn->icon->core); XMoveWindow(dpy, btn->icon->core->window, btn->x_pos, btn->y_pos); /* create dock menu */ dock->menu = dockMenuCreate(scr, type); if (type == WM_DRAWER) { drawerAppendToChain(scr, dock); dock->auto_collapse = 1; } return dock; } void wDockDestroy(WDock *dock) { int i; WAppIcon *aicon; for (i = (dock->type == WM_CLIP) ? 1 : 0; i < dock->max_icons; i++) { aicon = dock->icon_array[i]; if (aicon) { int keepit = aicon->running && wApplicationOf(aicon->main_window); wDockDetach(dock, aicon); if (keepit) { /* XXX: can: aicon->icon == NULL ? */ PlaceIcon(dock->screen_ptr, &aicon->x_pos, &aicon->y_pos, wGetHeadForWindow(aicon->icon->owner)); XMoveWindow(dpy, aicon->icon->core->window, aicon->x_pos, aicon->y_pos); if (!dock->mapped || dock->collapsed) XMapWindow(dpy, aicon->icon->core->window); } } } if (wPreferences.auto_arrange_icons) wArrangeIcons(dock->screen_ptr, True); wfree(dock->icon_array); if (dock->menu && dock->type != WM_CLIP) wMenuDestroy(dock->menu, True); if (dock->screen_ptr->last_dock == dock) dock->screen_ptr->last_dock = NULL; wfree(dock); } void wClipIconPaint(WAppIcon *aicon) { WScreen *scr = aicon->icon->core->screen_ptr; WWorkspace *workspace = scr->workspaces[scr->current_workspace]; WMColor *color; Window win = aicon->icon->core->window; int length, nlength; - char *ws_name, ws_number[10]; + char *ws_name, ws_number[sizeof scr->current_workspace * CHAR_BIT / 3 + 1]; int ty, tx; wIconPaint(aicon->icon); length = strlen(workspace->name); ws_name = wmalloc(length + 1); snprintf(ws_name, length + 1, "%s", workspace->name); - snprintf(ws_number, sizeof(ws_number), "%i", scr->current_workspace + 1); + snprintf(ws_number, sizeof ws_number, "%u", scr->current_workspace + 1); nlength = strlen(ws_number); if (wPreferences.flags.noclip || !workspace->clip->collapsed) color = scr->clip_title_color[CLIP_NORMAL]; else color = scr->clip_title_color[CLIP_COLLAPSED]; ty = ICON_SIZE - WMFontHeight(scr->clip_title_font) - 3; tx = CLIP_BUTTON_SIZE * ICON_SIZE / 64; if(wPreferences.show_clip_title) WMDrawString(scr->wmscreen, win, color, scr->clip_title_font, tx, ty, ws_name, length); tx = (ICON_SIZE / 2 - WMWidthOfString(scr->clip_title_font, ws_number, nlength)) / 2; WMDrawString(scr->wmscreen, win, color, scr->clip_title_font, tx, 2, ws_number, nlength); wfree(ws_name); if (aicon->launching) XFillRectangle(dpy, aicon->icon->core->window, scr->stipple_gc, 0, 0, wPreferences.icon_size, wPreferences.icon_size); paintClipButtons(aicon, aicon->dock->lclip_button_pushed, aicon->dock->rclip_button_pushed); } static void clipIconExpose(WObjDescriptor *desc, XEvent *event) { /* Parameter not used, but tell the compiler that it is ok */ (void) desc; (void) event; wClipIconPaint(desc->parent); } static void dockIconPaint(WAppIcon *btn) { if (btn == btn->icon->core->screen_ptr->clip_icon) { wClipIconPaint(btn); } else if (wIsADrawer(btn)) { wDrawerIconPaint(btn); } else { wAppIconPaint(btn); save_appicon(btn); } } static WMPropList *make_icon_state(WAppIcon *btn) { WMPropList *node = NULL; WMPropList *command, *autolaunch, *lock, *name, *forced; WMPropList *position, *buggy, *omnipresent; char *tmp; char buffer[64]; if (btn) { if (!btn->command) command = WMCreatePLString("-"); else command = WMCreatePLString(btn->command); autolaunch = btn->auto_launch ? dYes : dNo; lock = btn->lock ? dYes : dNo; tmp = EscapeWM_CLASS(btn->wm_instance, btn->wm_class); name = WMCreatePLString(tmp); wfree(tmp); forced = btn->forced_dock ? dYes : dNo; buggy = btn->buggy_app ? dYes : dNo; if (!wPreferences.flags.clip_merged_in_dock && btn == btn->icon->core->screen_ptr->clip_icon) snprintf(buffer, sizeof(buffer), "%i,%i", btn->x_pos, btn->y_pos); else snprintf(buffer, sizeof(buffer), "%hi,%hi", btn->xindex, btn->yindex); position = WMCreatePLString(buffer); node = WMCreatePLDictionary(dCommand, command, dName, name, dAutoLaunch, autolaunch, dLock, lock, dForced, forced, dBuggyApplication, buggy, dPosition, position, NULL); WMReleasePropList(command); WMReleasePropList(name); WMReleasePropList(position); omnipresent = btn->omnipresent ? dYes : dNo; if (btn->dock != btn->icon->core->screen_ptr->dock && (btn->xindex != 0 || btn->yindex != 0)) WMPutInPLDictionary(node, dOmnipresent, omnipresent); #ifdef USE_DOCK_XDND if (btn->dnd_command) { command = WMCreatePLString(btn->dnd_command); WMPutInPLDictionary(node, dDropCommand, command); WMReleasePropList(command); } #endif /* USE_DOCK_XDND */ if (btn->paste_command) { command = WMCreatePLString(btn->paste_command); WMPutInPLDictionary(node, dPasteCommand, command); WMReleasePropList(command); } } return node; } static WMPropList *dockSaveState(WDock *dock) { int i; WMPropList *icon_info; WMPropList *list = NULL, *dock_state = NULL; WMPropList *value, *key; char buffer[256]; list = WMCreatePLArray(NULL); for (i = (dock->type == WM_DOCK ? 0 : 1); i < dock->max_icons; i++) { WAppIcon *btn = dock->icon_array[i]; if (!btn || btn->attracted) continue; icon_info = make_icon_state(dock->icon_array[i]); if (icon_info != NULL) { WMAddToPLArray(list, icon_info); WMReleasePropList(icon_info); } } dock_state = WMCreatePLDictionary(dApplications, list, NULL); if (dock->type == WM_DOCK) { snprintf(buffer, sizeof(buffer), "Applications%i", dock->screen_ptr->scr_height); key = WMCreatePLString(buffer); WMPutInPLDictionary(dock_state, key, list); WMReleasePropList(key); snprintf(buffer, sizeof(buffer), "%i,%i", (dock->on_right_side ? -ICON_SIZE : 0), dock->y_pos); value = WMCreatePLString(buffer); WMPutInPLDictionary(dock_state, dPosition, value); WMReleasePropList(value); } WMReleasePropList(list); if (dock->type == WM_CLIP || dock->type == WM_DRAWER) { value = (dock->collapsed ? dYes : dNo); WMPutInPLDictionary(dock_state, dCollapsed, value); value = (dock->auto_collapse ? dYes : dNo); WMPutInPLDictionary(dock_state, dAutoCollapse, value); value = (dock->attract_icons ? dYes : dNo); WMPutInPLDictionary(dock_state, dAutoAttractIcons, value); } if (dock->type == WM_DOCK || dock->type == WM_CLIP) { value = (dock->lowered ? dYes : dNo); WMPutInPLDictionary(dock_state, dLowered, value); value = (dock->auto_raise_lower ? dYes : dNo); WMPutInPLDictionary(dock_state, dAutoRaiseLower, value); } return dock_state; } void wDockSaveState(WScreen *scr, WMPropList *old_state) { WMPropList *dock_state; WMPropList *keys; dock_state = dockSaveState(scr->dock); /* * Copy saved states of docks with different sizes. */ if (old_state) { int i; WMPropList *tmp; keys = WMGetPLDictionaryKeys(old_state); for (i = 0; i < WMGetPropListItemCount(keys); i++) { tmp = WMGetFromPLArray(keys, i); if (strncasecmp(WMGetFromPLString(tmp), "applications", 12) == 0 && !WMGetFromPLDictionary(dock_state, tmp)) { WMPutInPLDictionary(dock_state, tmp, WMGetFromPLDictionary(old_state, tmp)); } } WMReleasePropList(keys); } WMPutInPLDictionary(scr->session_state, dDock, dock_state); WMReleasePropList(dock_state); } void wClipSaveState(WScreen *scr) { WMPropList *clip_state; clip_state = make_icon_state(scr->clip_icon); WMPutInPLDictionary(scr->session_state, dClip, clip_state); WMReleasePropList(clip_state); } WMPropList *wClipSaveWorkspaceState(WScreen *scr, int workspace) { return dockSaveState(scr->workspaces[workspace]->clip); } static Bool getBooleanDockValue(WMPropList *value, WMPropList *key) { if (value) { if (WMIsPLString(value)) { if (strcasecmp(WMGetFromPLString(value), "YES") == 0) return True; } else { wwarning(_("bad value in docked icon state info %s"), WMGetFromPLString(key)); } } return False; } static WAppIcon *restore_icon_state(WScreen *scr, WMPropList *info, int type, int index) { WAppIcon *aicon; WMPropList *cmd, *value; char *wclass, *winstance, *command; cmd = WMGetFromPLDictionary(info, dCommand); if (!cmd || !WMIsPLString(cmd)) return NULL; /* parse window name */ value = WMGetFromPLDictionary(info, dName); if (!value) return NULL; ParseWindowName(value, &winstance, &wclass, "dock"); if (!winstance && !wclass) return NULL; /* get commands */ command = wstrdup(WMGetFromPLString(cmd)); if (strcmp(command, "-") == 0) { wfree(command); if (wclass) wfree(wclass); if (winstance) wfree(winstance); return NULL; } aicon = wAppIconCreateForDock(scr, command, winstance, wclass, TILE_NORMAL); if (wclass) wfree(wclass); if (winstance) wfree(winstance); wfree(command); aicon->icon->core->descriptor.handle_mousedown = iconMouseDown; aicon->icon->core->descriptor.handle_enternotify = clipEnterNotify; aicon->icon->core->descriptor.handle_leavenotify = clipLeaveNotify; aicon->icon->core->descriptor.parent_type = WCLASS_DOCK_ICON; aicon->icon->core->descriptor.parent = aicon; #ifdef USE_DOCK_XDND cmd = WMGetFromPLDictionary(info, dDropCommand); if (cmd) aicon->dnd_command = wstrdup(WMGetFromPLString(cmd)); #endif cmd = WMGetFromPLDictionary(info, dPasteCommand); if (cmd) aicon->paste_command = wstrdup(WMGetFromPLString(cmd)); /* check auto launch */ value = WMGetFromPLDictionary(info, dAutoLaunch); aicon->auto_launch = getBooleanDockValue(value, dAutoLaunch); /* check lock */ value = WMGetFromPLDictionary(info, dLock); aicon->lock = getBooleanDockValue(value, dLock); /* check if it wasn't normally docked */ value = WMGetFromPLDictionary(info, dForced); aicon->forced_dock = getBooleanDockValue(value, dForced); /* check if we can rely on the stuff in the app */ value = WMGetFromPLDictionary(info, dBuggyApplication); aicon->buggy_app = getBooleanDockValue(value, dBuggyApplication); /* get position in the dock */ value = WMGetFromPLDictionary(info, dPosition); if (value && WMIsPLString(value)) { if (sscanf(WMGetFromPLString(value), "%hi,%hi", &aicon->xindex, &aicon->yindex) != 2) wwarning(_("bad value in docked icon state info %s"), WMGetFromPLString(dPosition)); /* check position sanity */ /* *Very* incomplete section! */ if (type == WM_DOCK) { aicon->xindex = 0; } } else { aicon->yindex = index; aicon->xindex = 0; } /* check if icon is omnipresent */ value = WMGetFromPLDictionary(info, dOmnipresent); aicon->omnipresent = getBooleanDockValue(value, dOmnipresent); aicon->running = 0; aicon->docked = 1; return aicon; } #define COMPLAIN(key) wwarning(_("bad value in dock state info:%s"), key) WAppIcon *wClipRestoreState(WScreen *scr, WMPropList *clip_state) { WAppIcon *icon; WMPropList *value; icon = mainIconCreate(scr, WM_CLIP, NULL); if (!clip_state) return icon; WMRetainPropList(clip_state); /* restore position */ value = WMGetFromPLDictionary(clip_state, dPosition); if (value) { if (!WMIsPLString(value)) { COMPLAIN("Position"); } else { if (sscanf(WMGetFromPLString(value), "%i,%i", &icon->x_pos, &icon->y_pos) != 2) COMPLAIN("Position"); /* check position sanity */ if (!onScreen(scr, icon->x_pos, icon->y_pos)) wScreenKeepInside(scr, &icon->x_pos, &icon->y_pos, ICON_SIZE, ICON_SIZE); } } #ifdef USE_DOCK_XDND value = WMGetFromPLDictionary(clip_state, dDropCommand); if (value && WMIsPLString(value)) icon->dnd_command = wstrdup(WMGetFromPLString(value)); #endif value = WMGetFromPLDictionary(clip_state, dPasteCommand); if (value && WMIsPLString(value)) icon->paste_command = wstrdup(WMGetFromPLString(value)); WMReleasePropList(clip_state); return icon; } WDock *wDockRestoreState(WScreen *scr, WMPropList *dock_state, int type) { WDock *dock; WMPropList *apps; WMPropList *value; WAppIcon *aicon, *old_top; int count, i; dock = wDockCreate(scr, type, NULL); if (!dock_state) return dock; WMRetainPropList(dock_state); /* restore position */ value = WMGetFromPLDictionary(dock_state, dPosition); if (value) { if (!WMIsPLString(value)) { COMPLAIN("Position"); } else { if (sscanf(WMGetFromPLString(value), "%i,%i", &dock->x_pos, &dock->y_pos) != 2) COMPLAIN("Position"); /* check position sanity */ if (!onScreen(scr, dock->x_pos, dock->y_pos)) { int x = dock->x_pos; wScreenKeepInside(scr, &x, &dock->y_pos, ICON_SIZE, ICON_SIZE); } /* Is this needed any more? */ if (type == WM_CLIP) { if (dock->x_pos < 0) { dock->x_pos = 0; } else if (dock->x_pos > scr->scr_width - ICON_SIZE) { dock->x_pos = scr->scr_width - ICON_SIZE; } } else { if (dock->x_pos >= 0) { dock->x_pos = DOCK_EXTRA_SPACE; dock->on_right_side = 0; } else { dock->x_pos = scr->scr_width - DOCK_EXTRA_SPACE - ICON_SIZE; dock->on_right_side = 1; } } } } /* restore lowered/raised state */ dock->lowered = 0; value = WMGetFromPLDictionary(dock_state, dLowered); if (value) { if (!WMIsPLString(value)) { COMPLAIN("Lowered"); } else { if (strcasecmp(WMGetFromPLString(value), "YES") == 0) dock->lowered = 1; } } /* restore collapsed state */ dock->collapsed = 0; value = WMGetFromPLDictionary(dock_state, dCollapsed); if (value) { if (!WMIsPLString(value)) { COMPLAIN("Collapsed"); } else { if (strcasecmp(WMGetFromPLString(value), "YES") == 0) dock->collapsed = 1; } } /* restore auto-collapsed state */ value = WMGetFromPLDictionary(dock_state, dAutoCollapse); if (value) { if (!WMIsPLString(value)) { COMPLAIN("AutoCollapse"); } else { if (strcasecmp(WMGetFromPLString(value), "YES") == 0) { dock->auto_collapse = 1; dock->collapsed = 1; } } } /* restore auto-raise/lower state */ value = WMGetFromPLDictionary(dock_state, dAutoRaiseLower); if (value) { if (!WMIsPLString(value)) { COMPLAIN("AutoRaiseLower"); } else { if (strcasecmp(WMGetFromPLString(value), "YES") == 0) dock->auto_raise_lower = 1; } } /* restore attract icons state */ dock->attract_icons = 0; value = WMGetFromPLDictionary(dock_state, dAutoAttractIcons); if (value) { if (!WMIsPLString(value)) { COMPLAIN("AutoAttractIcons"); } else { if (strcasecmp(WMGetFromPLString(value), "YES") == 0) dock->attract_icons = 1; } } /* application list */ { WMPropList *tmp; char buffer[64]; /* * When saving, it saves the dock state in * Applications and Applicationsnnn * * When loading, it will first try Applicationsnnn. * If it does not exist, use Applications as default. */ snprintf(buffer, sizeof(buffer), "Applications%i", scr->scr_height);
roblillack/wmaker
41193bdacdf218e6176c2cc56e26714faacbd947
Fixed function-pointer compatibility.
diff --git a/src/dock.c b/src/dock.c index c26436a..86eef57 100644 --- a/src/dock.c +++ b/src/dock.c @@ -1,607 +1,607 @@ /* dock.c- built-in Dock module for WindowMaker * * Window Maker window manager * * Copyright (c) 1997-2003 Alfredo K. Kojima * Copyright (c) 1998-2003 Dan Pascu * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "wconfig.h" #include <X11/Xlib.h> #include <X11/Xutil.h> #include <stdio.h> #include <stdlib.h> #include <libgen.h> #include <string.h> #include <strings.h> #include <unistd.h> #include <math.h> #include <limits.h> #ifndef PATH_MAX #define PATH_MAX DEFAULT_PATH_MAX #endif #include "WindowMaker.h" #include "wcore.h" #include "window.h" #include "icon.h" #include "appicon.h" #include "actions.h" #include "stacking.h" #include "dock.h" #include "dockedapp.h" #include "dialog.h" #include "main.h" #include "properties.h" #include "menu.h" #include "client.h" #include "defaults.h" #include "workspace.h" #include "framewin.h" #include "superfluous.h" #include "xinerama.h" #include "placement.h" #include "misc.h" #include "event.h" /**** Local variables ****/ #define CLIP_REWIND 1 #define CLIP_IDLE 0 #define CLIP_FORWARD 2 #define MOD_MASK wPreferences.modifier_mask #define ICON_SIZE wPreferences.icon_size /***** Local variables ****/ static WMPropList *dCommand = NULL; static WMPropList *dPasteCommand = NULL; #ifdef USE_DOCK_XDND static WMPropList *dDropCommand = NULL; #endif static WMPropList *dAutoLaunch, *dLock; static WMPropList *dName, *dForced, *dBuggyApplication, *dYes, *dNo; static WMPropList *dHost, *dDock, *dClip; static WMPropList *dAutoAttractIcons; static WMPropList *dPosition, *dApplications, *dLowered, *dCollapsed; static WMPropList *dAutoCollapse, *dAutoRaiseLower, *dOmnipresent; static WMPropList *dDrawers = NULL; static void dockIconPaint(WAppIcon *btn); static void iconMouseDown(WObjDescriptor *desc, XEvent *event); static pid_t execCommand(WAppIcon *btn, const char *command, WSavedState *state); -static void trackDeadProcess(pid_t pid, unsigned char status, WDock *dock); +static void trackDeadProcess(pid_t pid, unsigned int status, void *cdata); static int getClipButton(int px, int py); static void toggleLowered(WDock *dock); static void toggleCollapsed(WDock *dock); static void clipIconExpose(WObjDescriptor *desc, XEvent *event); static void clipLeave(WDock *dock); static void handleClipChangeWorkspace(WScreen *scr, XEvent *event); static void clipEnterNotify(WObjDescriptor *desc, XEvent *event); static void clipLeaveNotify(WObjDescriptor *desc, XEvent *event); static void clipAutoCollapse(void *cdata); static void clipAutoExpand(void *cdata); static void launchDockedApplication(WAppIcon *btn, Bool withSelection); static void clipAutoLower(void *cdata); static void clipAutoRaise(void *cdata); static WAppIcon *mainIconCreate(WScreen *scr, int type, const char *name); static void drawerIconExpose(WObjDescriptor *desc, XEvent *event); static void removeDrawerCallback(WMenu *menu, WMenuEntry *entry); static void drawerAppendToChain(WScreen *scr, WDock *drawer); static char *findUniqueName(WScreen *scr, const char *instance_basename); static void addADrawerCallback(WMenu *menu, WMenuEntry *entry); static void swapDrawers(WScreen *scr, int new_x); static WDock* getDrawer(WScreen *scr, int y_index); static int indexOfHole(WDock *drawer, WAppIcon *moving_aicon, int redocking); static void drawerConsolidateIcons(WDock *drawer); static int onScreen(WScreen *scr, int x, int y); static void make_keys(void) { if (dCommand != NULL) return; dCommand = WMRetainPropList(WMCreatePLString("Command")); dPasteCommand = WMRetainPropList(WMCreatePLString("PasteCommand")); #ifdef USE_DOCK_XDND dDropCommand = WMRetainPropList(WMCreatePLString("DropCommand")); #endif dLock = WMRetainPropList(WMCreatePLString("Lock")); dAutoLaunch = WMRetainPropList(WMCreatePLString("AutoLaunch")); dName = WMRetainPropList(WMCreatePLString("Name")); dForced = WMRetainPropList(WMCreatePLString("Forced")); dBuggyApplication = WMRetainPropList(WMCreatePLString("BuggyApplication")); dYes = WMRetainPropList(WMCreatePLString("Yes")); dNo = WMRetainPropList(WMCreatePLString("No")); dHost = WMRetainPropList(WMCreatePLString("Host")); dPosition = WMCreatePLString("Position"); dApplications = WMCreatePLString("Applications"); dLowered = WMCreatePLString("Lowered"); dCollapsed = WMCreatePLString("Collapsed"); dAutoCollapse = WMCreatePLString("AutoCollapse"); dAutoRaiseLower = WMCreatePLString("AutoRaiseLower"); dAutoAttractIcons = WMCreatePLString("AutoAttractIcons"); dOmnipresent = WMCreatePLString("Omnipresent"); dDock = WMCreatePLString("Dock"); dClip = WMCreatePLString("Clip"); dDrawers = WMCreatePLString("Drawers"); } static void renameCallback(WMenu *menu, WMenuEntry *entry) { WDock *dock = entry->clientdata; char buffer[128]; int wspace; char *name; /* Parameter not used, but tell the compiler that it is ok */ (void) menu; assert(entry->clientdata != NULL); wspace = dock->screen_ptr->current_workspace; name = wstrdup(dock->screen_ptr->workspaces[wspace]->name); snprintf(buffer, sizeof(buffer), _("Type the name for workspace %i:"), wspace + 1); if (wInputDialog(dock->screen_ptr, _("Rename Workspace"), buffer, &name)) wWorkspaceRename(dock->screen_ptr, wspace, name); wfree(name); } static void toggleLoweredCallback(WMenu *menu, WMenuEntry *entry) { assert(entry->clientdata != NULL); toggleLowered(entry->clientdata); entry->flags.indicator_on = !(((WDock *) entry->clientdata)->lowered); wMenuPaint(menu); } static int matchWindow(const void *item, const void *cdata) { return (((WFakeGroupLeader *) item)->leader == (Window) cdata); } static void killCallback(WMenu *menu, WMenuEntry *entry) { WScreen *scr = menu->menu->screen_ptr; WAppIcon *icon; WFakeGroupLeader *fPtr; char *buffer, *shortname, **argv; int argc; if (!WCHECK_STATE(WSTATE_NORMAL)) return; assert(entry->clientdata != NULL); icon = (WAppIcon *) entry->clientdata; icon->editing = 1; WCHANGE_STATE(WSTATE_MODAL); /* strip away dir names */ shortname = basename(icon->command); /* separate out command options */ wtokensplit(shortname, &argv, &argc); buffer = wstrconcat(argv[0], _(" will be forcibly closed.\n" "Any unsaved changes will be lost.\n" "Please confirm.")); if (icon->icon && icon->icon->owner) { fPtr = icon->icon->owner->fake_group; } else { /* is this really necessary? can we kill a non-running dock icon? */ Window win = icon->main_window; int index; index = WMFindInArray(scr->fakeGroupLeaders, matchWindow, (void *)win); if (index != WANotFound) fPtr = WMGetFromArray(scr->fakeGroupLeaders, index); else fPtr = NULL; } if (wPreferences.dont_confirm_kill || wMessageDialog(menu->frame->screen_ptr, _("Kill Application"), buffer, _("Yes"), _("No"), NULL) == WAPRDefault) { if (fPtr != NULL) { WWindow *wwin, *twin; wwin = scr->focused_window; while (wwin) { twin = wwin->prev; if (wwin->fake_group == fPtr) wClientKill(wwin); wwin = twin; } } else if (icon->icon && icon->icon->owner) { wClientKill(icon->icon->owner); } } wfree(buffer); wtokenfree(argv, argc); icon->editing = 0; WCHANGE_STATE(WSTATE_NORMAL); } /* TODO: replace this function with a member of the dock struct */ static int numberOfSelectedIcons(WDock *dock) { WAppIcon *aicon; int i, n; n = 0; for (i = 1; i < dock->max_icons; i++) { aicon = dock->icon_array[i]; if (aicon && aicon->icon->selected) n++; } return n; } static WMArray *getSelected(WDock *dock) { WMArray *ret = WMCreateArray(8); WAppIcon *btn; int i; for (i = 1; i < dock->max_icons; i++) { btn = dock->icon_array[i]; if (btn && btn->icon->selected) WMAddToArray(ret, btn); } return ret; } static void paintClipButtons(WAppIcon *clipIcon, Bool lpushed, Bool rpushed) { Window win = clipIcon->icon->core->window; WScreen *scr = clipIcon->icon->core->screen_ptr; XPoint p[4]; int pt = CLIP_BUTTON_SIZE * ICON_SIZE / 64; int tp = ICON_SIZE - pt; int as = pt - 15; /* 15 = 5+5+5 */ GC gc = scr->draw_gc; /* maybe use WMColorGC() instead here? */ WMColor *color; color = scr->clip_title_color[CLIP_NORMAL]; XSetForeground(dpy, gc, WMColorPixel(color)); if (rpushed) { p[0].x = tp + 1; p[0].y = 1; p[1].x = ICON_SIZE - 2; p[1].y = 1; p[2].x = ICON_SIZE - 2; p[2].y = pt - 1; } else if (lpushed) { p[0].x = 1; p[0].y = tp; p[1].x = pt; p[1].y = ICON_SIZE - 2; p[2].x = 1; p[2].y = ICON_SIZE - 2; } if (lpushed || rpushed) { XSetForeground(dpy, scr->draw_gc, scr->white_pixel); XFillPolygon(dpy, win, scr->draw_gc, p, 3, Convex, CoordModeOrigin); XSetForeground(dpy, scr->draw_gc, scr->black_pixel); } /* top right arrow */ p[0].x = p[3].x = ICON_SIZE - 5 - as; p[0].y = p[3].y = 5; p[1].x = ICON_SIZE - 6; p[1].y = 5; p[2].x = ICON_SIZE - 6; p[2].y = 4 + as; if (rpushed) { XFillPolygon(dpy, win, scr->draw_gc, p, 3, Convex, CoordModeOrigin); XDrawLines(dpy, win, scr->draw_gc, p, 4, CoordModeOrigin); } else { XFillPolygon(dpy, win, gc, p, 3, Convex, CoordModeOrigin); XDrawLines(dpy, win, gc, p, 4, CoordModeOrigin); } /* bottom left arrow */ p[0].x = p[3].x = 5; p[0].y = p[3].y = ICON_SIZE - 5 - as; p[1].x = 5; p[1].y = ICON_SIZE - 6; p[2].x = 4 + as; p[2].y = ICON_SIZE - 6; if (lpushed) { XFillPolygon(dpy, win, scr->draw_gc, p, 3, Convex, CoordModeOrigin); XDrawLines(dpy, win, scr->draw_gc, p, 4, CoordModeOrigin); } else { XFillPolygon(dpy, win, gc, p, 3, Convex, CoordModeOrigin); XDrawLines(dpy, win, gc, p, 4, CoordModeOrigin); } } RImage *wClipMakeTile(RImage *normalTile) { RImage *tile = RCloneImage(normalTile); RColor black; RColor dark; RColor light; int pt, tp; int as; pt = CLIP_BUTTON_SIZE * wPreferences.icon_size / 64; tp = wPreferences.icon_size - 1 - pt; as = pt - 15; black.alpha = 255; black.red = black.green = black.blue = 0; dark.alpha = 0; dark.red = dark.green = dark.blue = 60; light.alpha = 0; light.red = light.green = light.blue = 80; /* top right */ ROperateLine(tile, RSubtractOperation, tp, 0, wPreferences.icon_size - 2, pt - 1, &dark); RDrawLine(tile, tp - 1, 0, wPreferences.icon_size - 1, pt + 1, &black); ROperateLine(tile, RAddOperation, tp, 2, wPreferences.icon_size - 3, pt, &light); /* arrow bevel */ ROperateLine(tile, RSubtractOperation, ICON_SIZE - 7 - as, 4, ICON_SIZE - 5, 4, &dark); ROperateLine(tile, RSubtractOperation, ICON_SIZE - 6 - as, 5, ICON_SIZE - 5, 6 + as, &dark); ROperateLine(tile, RAddOperation, ICON_SIZE - 5, 4, ICON_SIZE - 5, 6 + as, &light); /* bottom left */ ROperateLine(tile, RAddOperation, 2, tp + 2, pt - 2, wPreferences.icon_size - 3, &dark); RDrawLine(tile, 0, tp - 1, pt + 1, wPreferences.icon_size - 1, &black); ROperateLine(tile, RSubtractOperation, 0, tp - 2, pt + 1, wPreferences.icon_size - 2, &light); /* arrow bevel */ ROperateLine(tile, RSubtractOperation, 4, ICON_SIZE - 7 - as, 4, ICON_SIZE - 5, &dark); ROperateLine(tile, RSubtractOperation, 5, ICON_SIZE - 6 - as, 6 + as, ICON_SIZE - 5, &dark); ROperateLine(tile, RAddOperation, 4, ICON_SIZE - 5, 6 + as, ICON_SIZE - 5, &light); return tile; } static void omnipresentCallback(WMenu *menu, WMenuEntry *entry) { WAppIcon *clickedIcon = entry->clientdata; WAppIcon *aicon; WDock *dock; WMArray *selectedIcons; WMArrayIterator iter; int failed; /* Parameter not used, but tell the compiler that it is ok */ (void) menu; assert(entry->clientdata != NULL); dock = clickedIcon->dock; selectedIcons = getSelected(dock); if (!WMGetArrayItemCount(selectedIcons)) WMAddToArray(selectedIcons, clickedIcon); failed = 0; WM_ITERATE_ARRAY(selectedIcons, aicon, iter) { if (wClipMakeIconOmnipresent(aicon, !aicon->omnipresent) == WO_FAILED) failed++; else if (aicon->icon->selected) wIconSelect(aicon->icon); } WMFreeArray(selectedIcons); if (failed > 1) { wMessageDialog(dock->screen_ptr, _("Warning"), _("Some icons cannot be made omnipresent. " "Please make sure that no other icon is " "docked in the same positions on the other " "workspaces and the Clip is not full in " "some workspace."), _("OK"), NULL, NULL); } else if (failed == 1) { wMessageDialog(dock->screen_ptr, _("Warning"), _("Icon cannot be made omnipresent. " "Please make sure that no other icon is " "docked in the same position on the other " "workspaces and the Clip is not full in " "some workspace."), _("OK"), NULL, NULL); } } static void removeIcons(WMArray *icons, WDock *dock) { WAppIcon *aicon; int keepit; WMArrayIterator it; WM_ITERATE_ARRAY(icons, aicon, it) { keepit = aicon->running && wApplicationOf(aicon->main_window); wDockDetach(dock, aicon); if (keepit) { /* XXX: can: aicon->icon == NULL ? */ PlaceIcon(dock->screen_ptr, &aicon->x_pos, &aicon->y_pos, wGetHeadForWindow(aicon->icon->owner)); XMoveWindow(dpy, aicon->icon->core->window, aicon->x_pos, aicon->y_pos); if (!dock->mapped || dock->collapsed) XMapWindow(dpy, aicon->icon->core->window); } } WMFreeArray(icons); if (wPreferences.auto_arrange_icons) wArrangeIcons(dock->screen_ptr, True); } static void removeIconsCallback(WMenu *menu, WMenuEntry *entry) { WAppIcon *clickedIcon = (WAppIcon *) entry->clientdata; WDock *dock; WMArray *selectedIcons; /* Parameter not used, but tell the compiler that it is ok */ (void) menu; assert(clickedIcon != NULL); dock = clickedIcon->dock; selectedIcons = getSelected(dock); if (WMGetArrayItemCount(selectedIcons)) { if (wMessageDialog(dock->screen_ptr, dock->type == WM_CLIP ? _("Workspace Clip") : _("Drawer"), _("All selected icons will be removed!"), _("OK"), _("Cancel"), NULL) != WAPRDefault) { WMFreeArray(selectedIcons); return; } } else { if (clickedIcon->xindex == 0 && clickedIcon->yindex == 0) { WMFreeArray(selectedIcons); return; } WMAddToArray(selectedIcons, clickedIcon); } removeIcons(selectedIcons, dock); if (dock->type == WM_DRAWER) { drawerConsolidateIcons(dock); } } static void keepIconsCallback(WMenu *menu, WMenuEntry *entry) { WAppIcon *clickedIcon = (WAppIcon *) entry->clientdata; WDock *dock; WAppIcon *aicon; WMArray *selectedIcons; WMArrayIterator it; /* Parameter not used, but tell the compiler that it is ok */ (void) menu; assert(clickedIcon != NULL); dock = clickedIcon->dock; selectedIcons = getSelected(dock); if (!WMGetArrayItemCount(selectedIcons) && clickedIcon != dock->screen_ptr->clip_icon) { char *command = NULL; if (!clickedIcon->command && !clickedIcon->editing) { clickedIcon->editing = 1; if (wInputDialog(dock->screen_ptr, _("Keep Icon"), _("Type the command used to launch the application"), &command)) { if (command && (command[0] == 0 || (command[0] == '-' && command[1] == 0))) { wfree(command); command = NULL; } clickedIcon->command = command; clickedIcon->editing = 0; } else { clickedIcon->editing = 0; if (command) wfree(command); WMFreeArray(selectedIcons); return; } } WMAddToArray(selectedIcons, clickedIcon); } WM_ITERATE_ARRAY(selectedIcons, aicon, it) { if (aicon->icon->selected) wIconSelect(aicon->icon); if (aicon->attracted && aicon->command) { aicon->attracted = 0; if (aicon->icon->shadowed) { aicon->icon->shadowed = 0; /* * Update icon pixmap, RImage doesn't change, * so call wIconUpdate is not needed */ update_icon_pixmap(aicon->icon); /* Paint it */ wAppIconPaint(aicon); } } save_appicon(aicon); } WMFreeArray(selectedIcons); } static void toggleAutoAttractCallback(WMenu *menu, WMenuEntry *entry) { WDock *dock = (WDock *) entry->clientdata; WScreen *scr = dock->screen_ptr; assert(entry->clientdata != NULL); dock->attract_icons = !dock->attract_icons; entry->flags.indicator_on = dock->attract_icons; wMenuPaint(menu); if (dock->attract_icons) { if (dock->type == WM_DRAWER) { /* The newly auto-attracting dock is a drawer: disable any clip and * previously attracting drawer */ @@ -2582,1269 +2582,1270 @@ Bool wDockSnapIcon(WDock *dock, WAppIcon *icon, int req_x, int req_y, int *ret_x done = 0; sig = -sig; } if (done && ((ex_y >= closest && ex_y - closest < DOCK_DETTACH_THRESHOLD + 1) || (ex_y < closest && closest - ex_y <= DOCK_DETTACH_THRESHOLD + 1))) { *ret_x = 0; *ret_y = closest; return True; } } else { /* !redocking */ /* if slot is free and the icon is close enough, return it */ if (!aicon && ex_x == 0) { *ret_x = 0; *ret_y = ex_y; return True; } } break; case WM_CLIP: { int neighbours = 0; int start, stop, k; start = icon->omnipresent ? 0 : scr->current_workspace; stop = icon->omnipresent ? scr->workspace_count : start + 1; aicon = NULL; for (k = start; k < stop; k++) { WDock *tmp = scr->workspaces[k]->clip; if (!tmp) continue; for (i = 0; i < tmp->max_icons; i++) { nicon = tmp->icon_array[i]; if (nicon && nicon->xindex == ex_x && nicon->yindex == ex_y) { aicon = nicon; break; } } if (aicon) break; } for (k = start; k < stop; k++) { WDock *tmp = scr->workspaces[k]->clip; if (!tmp) continue; for (i = 0; i < tmp->max_icons; i++) { nicon = tmp->icon_array[i]; if (nicon && nicon != icon && /* Icon can't be it's own neighbour */ (abs(nicon->xindex - ex_x) <= CLIP_ATTACH_VICINITY && abs(nicon->yindex - ex_y) <= CLIP_ATTACH_VICINITY)) { neighbours = 1; break; } } if (neighbours) break; } if (neighbours && (aicon == NULL || (redocking && aicon == icon))) { *ret_x = ex_x; *ret_y = ex_y; return True; } break; } case WM_DRAWER: { WAppIcon *aicons_to_shift[ dock->icon_count ]; int index_of_hole, j; if (ex_y != 0 || abs(ex_x) - dock->icon_count > DOCK_DETTACH_THRESHOLD || (ex_x < 0 && !dock->on_right_side) || (ex_x > 0 && dock->on_right_side)) { return False; } if (ex_x == 0) ex_x = (dock->on_right_side ? -1 : 1); /* "Reduce" ex_x but keep its sign */ if (redocking) { if (abs(ex_x) > dock->icon_count - 1) /* minus 1: do not take icon_array[0] into account */ ex_x = ex_x * (dock->icon_count - 1) / abs(ex_x); /* don't use *= ! */ } else { if (abs(ex_x) > dock->icon_count) ex_x = ex_x * dock->icon_count / abs(ex_x); } index_of_hole = indexOfHole(dock, icon, redocking); /* Find the appicons between where icon was (index_of_hole) and where * it wants to be (ex_x) and slide them. */ j = 0; for (i = 1; i < dock->max_icons; i++) { aicon = dock->icon_array[i]; if ((aicon != NULL) && (aicon != icon) && ((ex_x <= aicon->xindex && aicon->xindex < index_of_hole) || (index_of_hole < aicon->xindex && aicon->xindex <= ex_x))) aicons_to_shift[ j++ ] = aicon; } assert(j == abs(ex_x - index_of_hole)); wSlideAppicons(aicons_to_shift, j, (index_of_hole < ex_x)); *ret_x = ex_x; *ret_y = ex_y; return True; } } return False; } static int onScreen(WScreen *scr, int x, int y) { WMRect rect; int flags; rect.pos.x = x; rect.pos.y = y; rect.size.width = rect.size.height = ICON_SIZE; wGetRectPlacementInfo(scr, rect, &flags); return !(flags & (XFLAG_DEAD | XFLAG_PARTIAL)); } /* * returns true if it can find a free slot in the dock, * in which case it changes x_pos and y_pos accordingly. * Else returns false. */ Bool wDockFindFreeSlot(WDock *dock, int *x_pos, int *y_pos) { WScreen *scr = dock->screen_ptr; WAppIcon *btn; WAppIconChain *chain; unsigned char *slot_map; int mwidth; int r; int x, y; int i, done = False; int corner; int ex = scr->scr_width, ey = scr->scr_height; int extra_count = 0; if (dock->type == WM_DRAWER) { if (dock->icon_count >= dock->max_icons) { /* drawer is full */ return False; } *x_pos = dock->icon_count * (dock->on_right_side ? -1 : 1); *y_pos = 0; return True; } if (dock->type == WM_CLIP && dock != scr->workspaces[scr->current_workspace]->clip) extra_count = scr->global_icon_count; /* if the dock is full */ if (dock->icon_count + extra_count >= dock->max_icons) return False; if (!wPreferences.flags.nodock && scr->dock && scr->dock->on_right_side) { ex -= ICON_SIZE + DOCK_EXTRA_SPACE; } if (ex < dock->x_pos) ex = dock->x_pos; #define C_NONE 0 #define C_NW 1 #define C_NE 2 #define C_SW 3 #define C_SE 4 /* check if clip is in a corner */ if (dock->type == WM_CLIP) { if (dock->x_pos < 1 && dock->y_pos < 1) corner = C_NE; else if (dock->x_pos < 1 && dock->y_pos >= (ey - ICON_SIZE)) corner = C_SE; else if (dock->x_pos >= (ex - ICON_SIZE) && dock->y_pos >= (ey - ICON_SIZE)) corner = C_SW; else if (dock->x_pos >= (ex - ICON_SIZE) && dock->y_pos < 1) corner = C_NW; else corner = C_NONE; } else { corner = C_NONE; } /* If the clip is in the corner, use only slots that are in the border * of the screen */ if (corner != C_NONE) { char *hmap, *vmap; int hcount, vcount; hcount = WMIN(dock->max_icons, scr->scr_width / ICON_SIZE); vcount = WMIN(dock->max_icons, scr->scr_height / ICON_SIZE); hmap = wmalloc(hcount + 1); vmap = wmalloc(vcount + 1); /* mark used positions */ switch (corner) { case C_NE: for (i = 0; i < dock->max_icons; i++) { btn = dock->icon_array[i]; if (!btn) continue; if (btn->xindex == 0 && btn->yindex > 0 && btn->yindex < vcount) vmap[btn->yindex] = 1; else if (btn->yindex == 0 && btn->xindex > 0 && btn->xindex < hcount) hmap[btn->xindex] = 1; } for (chain = scr->global_icons; chain != NULL; chain = chain->next) { btn = chain->aicon; if (btn->xindex == 0 && btn->yindex > 0 && btn->yindex < vcount) vmap[btn->yindex] = 1; else if (btn->yindex == 0 && btn->xindex > 0 && btn->xindex < hcount) hmap[btn->xindex] = 1; } break; case C_NW: for (i = 0; i < dock->max_icons; i++) { btn = dock->icon_array[i]; if (!btn) continue; if (btn->xindex == 0 && btn->yindex > 0 && btn->yindex < vcount) vmap[btn->yindex] = 1; else if (btn->yindex == 0 && btn->xindex < 0 && btn->xindex > -hcount) hmap[-btn->xindex] = 1; } for (chain = scr->global_icons; chain != NULL; chain = chain->next) { btn = chain->aicon; if (btn->xindex == 0 && btn->yindex > 0 && btn->yindex < vcount) vmap[btn->yindex] = 1; else if (btn->yindex == 0 && btn->xindex < 0 && btn->xindex > -hcount) hmap[-btn->xindex] = 1; } break; case C_SE: for (i = 0; i < dock->max_icons; i++) { btn = dock->icon_array[i]; if (!btn) continue; if (btn->xindex == 0 && btn->yindex < 0 && btn->yindex > -vcount) vmap[-btn->yindex] = 1; else if (btn->yindex == 0 && btn->xindex > 0 && btn->xindex < hcount) hmap[btn->xindex] = 1; } for (chain = scr->global_icons; chain != NULL; chain = chain->next) { btn = chain->aicon; if (btn->xindex == 0 && btn->yindex < 0 && btn->yindex > -vcount) vmap[-btn->yindex] = 1; else if (btn->yindex == 0 && btn->xindex > 0 && btn->xindex < hcount) hmap[btn->xindex] = 1; } break; case C_SW: default: for (i = 0; i < dock->max_icons; i++) { btn = dock->icon_array[i]; if (!btn) continue; if (btn->xindex == 0 && btn->yindex < 0 && btn->yindex > -vcount) vmap[-btn->yindex] = 1; else if (btn->yindex == 0 && btn->xindex < 0 && btn->xindex > -hcount) hmap[-btn->xindex] = 1; } for (chain = scr->global_icons; chain != NULL; chain = chain->next) { btn = chain->aicon; if (btn->xindex == 0 && btn->yindex < 0 && btn->yindex > -vcount) vmap[-btn->yindex] = 1; else if (btn->yindex == 0 && btn->xindex < 0 && btn->xindex > -hcount) hmap[-btn->xindex] = 1; } } x = 0; y = 0; done = 0; /* search a vacant slot */ for (i = 1; i < WMAX(vcount, hcount); i++) { if (i < vcount && vmap[i] == 0) { /* found a slot */ x = 0; y = i; done = 1; break; } else if (i < hcount && hmap[i] == 0) { /* found a slot */ x = i; y = 0; done = 1; break; } } wfree(vmap); wfree(hmap); /* If found a slot, translate and return */ if (done) { if (corner == C_NW || corner == C_NE) *y_pos = y; else *y_pos = -y; if (corner == C_NE || corner == C_SE) *x_pos = x; else *x_pos = -x; return True; } /* else, try to find a slot somewhere else */ } /* a map of mwidth x mwidth would be enough if we allowed icons to be * placed outside of screen */ mwidth = (int)ceil(sqrt(dock->max_icons)); /* In the worst case (the clip is in the corner of the screen), * the amount of icons that fit in the clip is smaller. * Double the map to get a safe value. */ mwidth += mwidth; r = (mwidth - 1) / 2; slot_map = wmalloc(mwidth * mwidth); #define XY2OFS(x,y) (WMAX(abs(x),abs(y)) > r) ? 0 : (((y)+r)*(mwidth)+(x)+r) /* mark used slots in the map. If the slot falls outside the map * (for example, when all icons are placed in line), ignore them. */ for (i = 0; i < dock->max_icons; i++) { btn = dock->icon_array[i]; if (btn) slot_map[XY2OFS(btn->xindex, btn->yindex)] = 1; } for (chain = scr->global_icons; chain != NULL; chain = chain->next) slot_map[XY2OFS(chain->aicon->xindex, chain->aicon->yindex)] = 1; /* Find closest slot from the center that is free by scanning the * map from the center to outward in circular passes. * This will not result in a neat layout, but will be optimal * in the sense that there will not be holes left. */ done = 0; for (i = 1; i <= r && !done; i++) { int tx, ty; /* top and bottom parts of the ring */ for (x = -i; x <= i && !done; x++) { tx = dock->x_pos + x * ICON_SIZE; y = -i; ty = dock->y_pos + y * ICON_SIZE; if (slot_map[XY2OFS(x, y)] == 0 && onScreen(scr, tx, ty)) { *x_pos = x; *y_pos = y; done = 1; break; } y = i; ty = dock->y_pos + y * ICON_SIZE; if (slot_map[XY2OFS(x, y)] == 0 && onScreen(scr, tx, ty)) { *x_pos = x; *y_pos = y; done = 1; break; } } /* left and right parts of the ring */ for (y = -i + 1; y <= i - 1; y++) { ty = dock->y_pos + y * ICON_SIZE; x = -i; tx = dock->x_pos + x * ICON_SIZE; if (slot_map[XY2OFS(x, y)] == 0 && onScreen(scr, tx, ty)) { *x_pos = x; *y_pos = y; done = 1; break; } x = i; tx = dock->x_pos + x * ICON_SIZE; if (slot_map[XY2OFS(x, y)] == 0 && onScreen(scr, tx, ty)) { *x_pos = x; *y_pos = y; done = 1; break; } } } wfree(slot_map); #undef XY2OFS return done; } static void moveDock(WDock *dock, int new_x, int new_y) { WAppIcon *btn; WDrawerChain *dc; int i; if (dock->type == WM_DOCK) { for (dc = dock->screen_ptr->drawers; dc != NULL; dc = dc->next) moveDock(dc->adrawer, new_x, dc->adrawer->y_pos - dock->y_pos + new_y); } dock->x_pos = new_x; dock->y_pos = new_y; for (i = 0; i < dock->max_icons; i++) { btn = dock->icon_array[i]; if (btn) { btn->x_pos = new_x + btn->xindex * ICON_SIZE; btn->y_pos = new_y + btn->yindex * ICON_SIZE; XMoveWindow(dpy, btn->icon->core->window, btn->x_pos, btn->y_pos); } } } static void swapDock(WDock *dock) { WScreen *scr = dock->screen_ptr; WAppIcon *btn; int x, i; if (dock->on_right_side) x = dock->x_pos = scr->scr_width - ICON_SIZE - DOCK_EXTRA_SPACE; else x = dock->x_pos = DOCK_EXTRA_SPACE; swapDrawers(scr, x); for (i = 0; i < dock->max_icons; i++) { btn = dock->icon_array[i]; if (btn) { btn->x_pos = x; XMoveWindow(dpy, btn->icon->core->window, btn->x_pos, btn->y_pos); } } wScreenUpdateUsableArea(scr); } static pid_t execCommand(WAppIcon *btn, const char *command, WSavedState *state) { WScreen *scr = btn->icon->core->screen_ptr; pid_t pid; char **argv; int argc; char *cmdline; cmdline = ExpandOptions(scr, command); if (scr->flags.dnd_data_convertion_status || !cmdline) { if (cmdline) wfree(cmdline); if (state) wfree(state); return 0; } wtokensplit(cmdline, &argv, &argc); if (!argc) { if (cmdline) wfree(cmdline); if (state) wfree(state); return 0; } pid = fork(); if (pid == 0) { char **args; int i; SetupEnvironment(scr); #ifdef HAVE_SETSID setsid(); #endif args = malloc(sizeof(char *) * (argc + 1)); if (!args) exit(111); for (i = 0; i < argc; i++) args[i] = argv[i]; args[argc] = NULL; execvp(argv[0], args); exit(111); } wtokenfree(argv, argc); if (pid > 0) { if (!state) { state = wmalloc(sizeof(WSavedState)); state->hidden = -1; state->miniaturized = -1; state->shaded = -1; if (btn->dock == scr->dock || btn->dock->type == WM_DRAWER || btn->omnipresent) state->workspace = -1; else state->workspace = scr->current_workspace; } wWindowAddSavedState(btn->wm_instance, btn->wm_class, cmdline, pid, state); - wAddDeathHandler(pid, (WDeathHandler *) trackDeadProcess, btn->dock); + wAddDeathHandler(pid, trackDeadProcess, btn->dock); } else if (state) { wfree(state); } wfree(cmdline); return pid; } void wDockHideIcons(WDock *dock) { int i; if (dock == NULL) return; for (i = 1; i < dock->max_icons; i++) { if (dock->icon_array[i]) XUnmapWindow(dpy, dock->icon_array[i]->icon->core->window); } dock->mapped = 0; dockIconPaint(dock->icon_array[0]); } void wDockShowIcons(WDock *dock) { int i; WAppIcon *btn; if (dock == NULL) return; btn = dock->icon_array[0]; moveDock(dock, btn->x_pos, btn->y_pos); /* Deleting any change in stacking level, this function is now only about mapping icons */ if (!dock->collapsed) { for (i = 1; i < dock->max_icons; i++) { if (dock->icon_array[i]) XMapWindow(dpy, dock->icon_array[i]->icon->core->window); } } dock->mapped = 1; dockIconPaint(btn); } void wDockLower(WDock *dock) { int i; WDrawerChain *dc; if (dock->type == WM_DOCK) { for (dc = dock->screen_ptr->drawers; dc != NULL; dc = dc->next) wDockLower(dc->adrawer); } for (i = 0; i < dock->max_icons; i++) { if (dock->icon_array[i]) wLowerFrame(dock->icon_array[i]->icon->core); } } void wDockRaise(WDock *dock) { int i; WDrawerChain *dc; for (i = dock->max_icons - 1; i >= 0; i--) { if (dock->icon_array[i]) wRaiseFrame(dock->icon_array[i]->icon->core); } if (dock->type == WM_DOCK) { for (dc = dock->screen_ptr->drawers; dc != NULL; dc = dc->next) wDockRaise(dc->adrawer); } } void wDockRaiseLower(WDock *dock) { if (!dock->icon_array[0]->icon->core->stacking->above || (dock->icon_array[0]->icon->core->stacking->window_level != dock->icon_array[0]->icon->core->stacking->above->stacking->window_level)) wDockLower(dock); else wDockRaise(dock); } void wDockFinishLaunch(WAppIcon *icon) { icon->launching = 0; icon->relaunching = 0; dockIconPaint(icon); } WAppIcon *wDockFindIconForWindow(WDock *dock, Window window) { WAppIcon *icon; int i; for (i = 0; i < dock->max_icons; i++) { icon = dock->icon_array[i]; if (icon && icon->main_window == window) return icon; } return NULL; } void wDockTrackWindowLaunch(WDock *dock, Window window) { WAppIcon *icon; char *wm_class, *wm_instance; int i; Bool firstPass = True; Bool found = False; char *command = NULL; if (!PropGetWMClass(window, &wm_class, &wm_instance)) { free(wm_class); free(wm_instance); return; } command = GetCommandForWindow(window); retry: for (i = 0; i < dock->max_icons; i++) { icon = dock->icon_array[i]; if (!icon) continue; /* app is already attached to icon */ if (icon->main_window == window) { found = True; break; } if ((icon->wm_instance || icon->wm_class) && (icon->launching || !icon->running)) { if (icon->wm_instance && wm_instance && strcmp(icon->wm_instance, wm_instance) != 0) continue; if (icon->wm_class && wm_class && strcmp(icon->wm_class, wm_class) != 0) continue; if (firstPass && command && strcmp(icon->command, command) != 0) continue; if (!icon->relaunching) { WApplication *wapp; /* Possibly an application that was docked with dockit, * but the user did not update WMState to indicate that * it was docked by force */ wapp = wApplicationOf(window); if (!wapp) { icon->forced_dock = 1; icon->running = 0; } if (!icon->forced_dock) icon->main_window = window; } found = True; if (!wPreferences.no_animations && !icon->launching && !dock->screen_ptr->flags.startup && !dock->collapsed) { WAppIcon *aicon; int x0, y0; icon->launching = 1; dockIconPaint(icon); aicon = wAppIconCreateForDock(dock->screen_ptr, NULL, wm_instance, wm_class, TILE_NORMAL); /* XXX: can: aicon->icon == NULL ? */ PlaceIcon(dock->screen_ptr, &x0, &y0, wGetHeadForWindow(aicon->icon->owner)); wAppIconMove(aicon, x0, y0); /* Should this always be lowered? -Dan */ if (dock->lowered) wLowerFrame(aicon->icon->core); XMapWindow(dpy, aicon->icon->core->window); aicon->launching = 1; wAppIconPaint(aicon); slide_window(aicon->icon->core->window, x0, y0, icon->x_pos, icon->y_pos); XUnmapWindow(dpy, aicon->icon->core->window); wAppIconDestroy(aicon); } wDockFinishLaunch(icon); break; } } if (firstPass && !found) { firstPass = False; goto retry; } if (command) wfree(command); if (wm_class) free(wm_class); if (wm_instance) free(wm_instance); } void wClipUpdateForWorkspaceChange(WScreen *scr, int workspace) { if (!wPreferences.flags.noclip) { scr->clip_icon->dock = scr->workspaces[workspace]->clip; if (scr->current_workspace != workspace) { WDock *old_clip = scr->workspaces[scr->current_workspace]->clip; WAppIconChain *chain = scr->global_icons; while (chain) { wDockMoveIconBetweenDocks(chain->aicon->dock, scr->workspaces[workspace]->clip, chain->aicon, chain->aicon->xindex, chain->aicon->yindex); if (scr->workspaces[workspace]->clip->collapsed) XUnmapWindow(dpy, chain->aicon->icon->core->window); chain = chain->next; } wDockHideIcons(old_clip); if (old_clip->auto_raise_lower) { if (old_clip->auto_raise_magic) { WMDeleteTimerHandler(old_clip->auto_raise_magic); old_clip->auto_raise_magic = NULL; } wDockLower(old_clip); } if (old_clip->auto_collapse) { if (old_clip->auto_expand_magic) { WMDeleteTimerHandler(old_clip->auto_expand_magic); old_clip->auto_expand_magic = NULL; } old_clip->collapsed = 1; } wDockShowIcons(scr->workspaces[workspace]->clip); } } } -static void trackDeadProcess(pid_t pid, unsigned char status, WDock *dock) +static void trackDeadProcess(pid_t pid, unsigned int status, void *cdata) { + WDock *dock = cdata; WAppIcon *icon; int i; for (i = 0; i < dock->max_icons; i++) { icon = dock->icon_array[i]; if (!icon) continue; if (icon->launching && icon->pid == pid) { if (!icon->relaunching) { icon->running = 0; icon->main_window = None; } wDockFinishLaunch(icon); icon->pid = 0; if (status == 111) { char msg[PATH_MAX]; char *cmd; #ifdef USE_DOCK_XDND if (icon->drop_launch) cmd = icon->dnd_command; else #endif if (icon->paste_launch) cmd = icon->paste_command; else cmd = icon->command; snprintf(msg, sizeof(msg), _("Could not execute command \"%s\""), cmd); wMessageDialog(dock->screen_ptr, _("Error"), msg, _("OK"), NULL, NULL); } break; } } } /* This function is called when the dock switches state between * "normal" (including auto-raise/lower) and "keep on top". It is * therefore clearly distinct from wDockLower/Raise, which are called * each time a not-kept-on-top dock is lowered/raised. */ static void toggleLowered(WDock *dock) { WAppIcon *tmp; WDrawerChain *dc; int newlevel, i; if (!dock->lowered) { newlevel = WMNormalLevel; dock->lowered = 1; } else { newlevel = WMDockLevel; dock->lowered = 0; } for (i = 0; i < dock->max_icons; i++) { tmp = dock->icon_array[i]; if (!tmp) continue; ChangeStackingLevel(tmp->icon->core, newlevel); /* When the dock is no longer "on top", explicitly lower it as well. * It saves some CPU cycles (probably) to do it ourselves here * rather than calling wDockLower at the end of toggleLowered */ if (dock->lowered) wLowerFrame(tmp->icon->core); } if (dock->type == WM_DOCK) { for (dc = dock->screen_ptr->drawers; dc != NULL; dc = dc->next) { toggleLowered(dc->adrawer); } wScreenUpdateUsableArea(dock->screen_ptr); } } static void toggleCollapsed(WDock *dock) { if (dock->collapsed) { dock->collapsed = 0; wDockShowIcons(dock); } else { dock->collapsed = 1; wDockHideIcons(dock); } } static void openDockMenu(WDock *dock, WAppIcon *aicon, XEvent *event) { WScreen *scr = dock->screen_ptr; WObjDescriptor *desc; WMenuEntry *entry; WApplication *wapp = NULL; int index = 0; int x_pos; int n_selected; int appIsRunning = aicon->running && aicon->icon && aicon->icon->owner; if (dock->type == WM_DOCK) { /* Dock position menu */ updateDockPositionMenu(scr->dock_pos_menu, dock); dock->menu->flags.realized = 0; if (!wPreferences.flags.nodrawer) { /* add a drawer */ entry = dock->menu->entries[++index]; entry->clientdata = aicon; wMenuSetEnabled(dock->menu, index, True); } } else { /* clip/drawer options */ if (scr->clip_options) updateClipOptionsMenu(scr->clip_options, dock); n_selected = numberOfSelectedIcons(dock); if (dock->type == WM_CLIP) { /* Rename Workspace */ entry = dock->menu->entries[++index]; if (aicon == scr->clip_icon) { entry->callback = renameCallback; entry->clientdata = dock; entry->flags.indicator = 0; entry->text = _("Rename Workspace"); } else { entry->callback = omnipresentCallback; entry->clientdata = aicon; if (n_selected > 0) { entry->flags.indicator = 0; entry->text = _("Toggle Omnipresent"); } else { entry->flags.indicator = 1; entry->flags.indicator_on = aicon->omnipresent; entry->flags.indicator_type = MI_CHECK; entry->text = _("Omnipresent"); } } } /* select/unselect icon */ entry = dock->menu->entries[++index]; entry->clientdata = aicon; entry->flags.indicator_on = aicon->icon->selected; wMenuSetEnabled(dock->menu, index, aicon != scr->clip_icon && !wIsADrawer(aicon)); /* select/unselect all icons */ entry = dock->menu->entries[++index]; entry->clientdata = aicon; if (n_selected > 0) entry->text = _("Unselect All Icons"); else entry->text = _("Select All Icons"); wMenuSetEnabled(dock->menu, index, dock->icon_count > 1); /* keep icon(s) */ entry = dock->menu->entries[++index]; entry->clientdata = aicon; if (n_selected > 1) entry->text = _("Keep Icons"); else entry->text = _("Keep Icon"); wMenuSetEnabled(dock->menu, index, dock->icon_count > 1); if (dock->type == WM_CLIP) { /* this is the workspace submenu part */ entry = dock->menu->entries[++index]; if (n_selected > 1) entry->text = _("Move Icons To"); else entry->text = _("Move Icon To"); if (scr->clip_submenu) updateWorkspaceMenu(scr->clip_submenu, aicon); wMenuSetEnabled(dock->menu, index, !aicon->omnipresent); } /* remove icon(s) */ entry = dock->menu->entries[++index]; entry->clientdata = aicon; if (n_selected > 1) entry->text = _("Remove Icons"); else entry->text = _("Remove Icon"); wMenuSetEnabled(dock->menu, index, dock->icon_count > 1); /* attract icon(s) */ entry = dock->menu->entries[++index]; entry->clientdata = aicon; dock->menu->flags.realized = 0; wMenuRealize(dock->menu); } if (aicon->icon->owner) wapp = wApplicationOf(aicon->icon->owner->main_window); else wapp = NULL; /* launch */ entry = dock->menu->entries[++index]; entry->clientdata = aicon; wMenuSetEnabled(dock->menu, index, aicon->command != NULL); /* unhide here */ entry = dock->menu->entries[++index]; entry->clientdata = aicon; if (wapp && wapp->flags.hidden) entry->text = _("Unhide Here"); else entry->text = _("Bring Here"); wMenuSetEnabled(dock->menu, index, appIsRunning); /* hide */ entry = dock->menu->entries[++index]; entry->clientdata = aicon; if (wapp && wapp->flags.hidden) entry->text = _("Unhide"); else entry->text = _("Hide"); wMenuSetEnabled(dock->menu, index, appIsRunning); /* settings */ entry = dock->menu->entries[++index]; entry->clientdata = aicon; wMenuSetEnabled(dock->menu, index, !aicon->editing && !wPreferences.flags.noupdates); /* kill or remove drawer */ entry = dock->menu->entries[++index]; entry->clientdata = aicon; if (wIsADrawer(aicon)) { entry->callback = removeDrawerCallback; entry->text = _("Remove drawer"); wMenuSetEnabled(dock->menu, index, True); } else { entry->callback = killCallback; entry->text = _("Kill"); wMenuSetEnabled(dock->menu, index, appIsRunning); } if (!dock->menu->flags.realized) wMenuRealize(dock->menu); if (dock->type == WM_CLIP || dock->type == WM_DRAWER) { /*x_pos = event->xbutton.x_root+2; */ x_pos = event->xbutton.x_root - dock->menu->frame->core->width / 2 - 1; if (x_pos < 0) { x_pos = 0; } else if (x_pos + dock->menu->frame->core->width > scr->scr_width - 2) { x_pos = scr->scr_width - dock->menu->frame->core->width - 4; } } else { x_pos = dock->on_right_side ? scr->scr_width - dock->menu->frame->core->width - 3 : 0; } wMenuMapAt(dock->menu, x_pos, event->xbutton.y_root + 2, False); /* allow drag select */ event->xany.send_event = True; desc = &dock->menu->menu->descriptor; (*desc->handle_mousedown) (desc, event); } /******************************************************************/ static void iconDblClick(WObjDescriptor *desc, XEvent *event) { WAppIcon *btn = desc->parent; WDock *dock = btn->dock; WApplication *wapp = NULL; int unhideHere = 0; if (btn->icon->owner && !(event->xbutton.state & ControlMask)) { wapp = wApplicationOf(btn->icon->owner->main_window); assert(wapp != NULL); unhideHere = (event->xbutton.state & ShiftMask); /* go to the last workspace that the user worked on the app */ if (wapp->last_workspace != dock->screen_ptr->current_workspace && !unhideHere) wWorkspaceChange(dock->screen_ptr, wapp->last_workspace); wUnhideApplication(wapp, event->xbutton.button == Button2, unhideHere); if (event->xbutton.state & MOD_MASK) wHideOtherApplications(btn->icon->owner); } else { if (event->xbutton.button == Button1) { if (event->xbutton.state & MOD_MASK) { /* raise/lower dock */ toggleLowered(dock); } else if (btn == dock->screen_ptr->clip_icon) { if (getClipButton(event->xbutton.x, event->xbutton.y) != CLIP_IDLE) handleClipChangeWorkspace(dock->screen_ptr, event); else if (wPreferences.flags.clip_merged_in_dock) { // Is actually the dock if (btn->command) { if (!btn->launching && (!btn->running || (event->xbutton.state & ControlMask))) launchDockedApplication(btn, False); } else { wShowInfoPanel(dock->screen_ptr); } } else toggleCollapsed(dock); } else if (wIsADrawer(btn)) { toggleCollapsed(dock); } else if (btn->command) { if (!btn->launching && (!btn->running || (event->xbutton.state & ControlMask))) launchDockedApplication(btn, False); } else if (btn->xindex == 0 && btn->yindex == 0 && btn->dock->type == WM_DOCK) { wShowInfoPanel(dock->screen_ptr); } } } } static void handleDockMove(WDock *dock, WAppIcon *aicon, XEvent *event) { WScreen *scr = dock->screen_ptr; int ofs_x = event->xbutton.x, ofs_y = event->xbutton.y; WIcon *icon = aicon->icon; WAppIcon *tmpaicon; WDrawerChain *dc; int x = aicon->x_pos, y = aicon->y_pos;; int shad_x = x, shad_y = y; XEvent ev; int grabbed = 0, done, previously_on_right, now_on_right, previous_x_pos, i; Pixmap ghost = None; int superfluous = wPreferences.superfluous; /* we catch it to avoid problems */ if (XGrabPointer(dpy, aicon->icon->core->window, True, ButtonMotionMask | ButtonReleaseMask | ButtonPressMask, GrabModeAsync, GrabModeAsync, None, None, CurrentTime) != GrabSuccess) wwarning("pointer grab failed for dock move"); if (dock->type == WM_DRAWER) { Window wins[2]; wins[0] = icon->core->window; wins[1] = scr->dock_shadow; XRestackWindows(dpy, wins, 2); XMoveResizeWindow(dpy, scr->dock_shadow, aicon->x_pos, aicon->y_pos, ICON_SIZE, ICON_SIZE); if (superfluous) { if (icon->pixmap!=None) ghost = MakeGhostIcon(scr, icon->pixmap); else ghost = MakeGhostIcon(scr, icon->core->window); XSetWindowBackgroundPixmap(dpy, scr->dock_shadow, ghost); XClearWindow(dpy, scr->dock_shadow); } XMapWindow(dpy, scr->dock_shadow); } previously_on_right = now_on_right = dock->on_right_side; previous_x_pos = dock->x_pos; done = 0; while (!done) { WMMaskEvent(dpy, PointerMotionMask | ButtonReleaseMask | ButtonPressMask | ButtonMotionMask | ExposureMask | EnterWindowMask, &ev); switch (ev.type) { case Expose: WMHandleEvent(&ev); break; case EnterNotify: /* It means the cursor moved so fast that it entered * something else (if moving slowly, it would have * stayed in the dock that is being moved. Ignore such * "spurious" EnterNotifiy's */ break; case MotionNotify: if (!grabbed) { if (abs(ofs_x - ev.xmotion.x) >= MOVE_THRESHOLD || abs(ofs_y - ev.xmotion.y) >= MOVE_THRESHOLD) { XChangeActivePointerGrab(dpy, ButtonMotionMask | ButtonReleaseMask | ButtonPressMask, wPreferences.cursor[WCUR_MOVE], CurrentTime); grabbed = 1; } break; } switch (dock->type) { case WM_CLIP: x = ev.xmotion.x_root - ofs_x; y = ev.xmotion.y_root - ofs_y; wScreenKeepInside(scr, &x, &y, ICON_SIZE, ICON_SIZE); moveDock(dock, x, y); break; case WM_DOCK: x = ev.xmotion.x_root - ofs_x; y = ev.xmotion.y_root - ofs_y; if (previously_on_right) { now_on_right = (ev.xmotion.x_root >= previous_x_pos - ICON_SIZE); } else { now_on_right = (ev.xmotion.x_root > previous_x_pos + ICON_SIZE * 2); } if (now_on_right != dock->on_right_side) { dock->on_right_side = now_on_right; swapDock(dock); wArrangeIcons(scr, False); } // Also perform the vertical move wScreenKeepInside(scr, &x, &y, ICON_SIZE, ICON_SIZE); moveDock(dock, dock->x_pos, y); if (wPreferences.flags.wrap_appicons_in_dock) { for (i = 0; i < dock->max_icons; i++) { int new_y, new_index, j, ok; tmpaicon = dock->icon_array[i]; if (tmpaicon == NULL) continue; if (onScreen(scr, tmpaicon->x_pos, tmpaicon->y_pos)) continue; new_y = (tmpaicon->y_pos + ICON_SIZE * dock->max_icons) % (ICON_SIZE * dock->max_icons); new_index = (new_y - dock->y_pos) / ICON_SIZE; if (!onScreen(scr, tmpaicon->x_pos, new_y)) continue; ok = 1; for (j = 0; j < dock->max_icons; j++) { if (dock->icon_array[j] != NULL && dock->icon_array[j]->yindex == new_index) { ok = 0; break; } } if (!ok || getDrawer(scr, new_index) != NULL) continue; wDockReattachIcon(dock, tmpaicon, tmpaicon->xindex, new_index); } for (dc = scr->drawers; dc != NULL; dc = dc->next) { int new_y, new_index, j, ok; tmpaicon = dc->adrawer->icon_array[0]; if (onScreen(scr, tmpaicon->x_pos, tmpaicon->y_pos)) continue; new_y = (tmpaicon->y_pos + ICON_SIZE * dock->max_icons) % (ICON_SIZE * dock->max_icons); new_index = (new_y - dock->y_pos) / ICON_SIZE; if (!onScreen(scr, tmpaicon->x_pos, new_y)) continue; ok = 1; for (j = 0; j < dock->max_icons; j++) { if (dock->icon_array[j] != NULL && dock->icon_array[j]->yindex == new_index) { ok = 0; break; } } if (!ok || getDrawer(scr, new_index) != NULL) continue; moveDock(dc->adrawer, tmpaicon->x_pos, new_y); } } break; case WM_DRAWER: { WDock *real_dock = dock->screen_ptr->dock; Bool snapped; int ix, iy; x = ev.xmotion.x_root - ofs_x; y = ev.xmotion.y_root - ofs_y; snapped = wDockSnapIcon(real_dock, aicon, x, y, &ix, &iy, True); if (snapped) { shad_x = real_dock->x_pos + ix * wPreferences.icon_size; shad_y = real_dock->y_pos + iy * wPreferences.icon_size; XMoveWindow(dpy, scr->dock_shadow, shad_x, shad_y); } moveDock(dock, x, y); break; } } break; case ButtonPress: break; case ButtonRelease: if (ev.xbutton.button != event->xbutton.button) break; XUngrabPointer(dpy, CurrentTime); if (dock->type == WM_DRAWER) { Window wins[dock->icon_count]; int offset_index; /* * When the dock is on the Right side, the index of the icons are negative to * reflect the fact that they are placed on the other side of the dock; we use * an offset here so we can have an always positive index for the storage in * the 'wins' array. */ if (dock->on_right_side) offset_index = dock->icon_count - 1;
roblillack/wmaker
a7f8e990dbaf7d41186b523ad842a60a46322d8e
Added explicit fall-through comments to pacify GCC.
diff --git a/src/defaults.c b/src/defaults.c index e20cc46..31efa3f 100644 --- a/src/defaults.c +++ b/src/defaults.c @@ -2869,611 +2869,613 @@ static int setMenuDisabledColor(WScreen * scr, WDefaultEntry * entry, void *tdat /* Parameter not used, but tell the compiler that it is ok */ (void) entry; (void) foo; if (scr->dtext_color) WMReleaseColor(scr->dtext_color); scr->dtext_color = WMCreateRGBColor(scr->wmscreen, color->red, color->green, color->blue, True); if (WMColorPixel(scr->dtext_color) == WMColorPixel(scr->mtext_color)) { WMSetColorAlpha(scr->dtext_color, 0x7fff); } else { WMSetColorAlpha(scr->dtext_color, 0xffff); } wFreeColor(scr, color->pixel); return REFRESH_MENU_COLOR; } static int setIconTitleColor(WScreen * scr, WDefaultEntry * entry, void *tdata, void *foo) { XColor *color = tdata; /* Parameter not used, but tell the compiler that it is ok */ (void) entry; (void) foo; if (scr->icon_title_color) WMReleaseColor(scr->icon_title_color); scr->icon_title_color = WMCreateRGBColor(scr->wmscreen, color->red, color->green, color->blue, True); wFreeColor(scr, color->pixel); return REFRESH_ICON_TITLE_COLOR; } static int setIconTitleBack(WScreen * scr, WDefaultEntry * entry, void *tdata, void *foo) { XColor *color = tdata; /* Parameter not used, but tell the compiler that it is ok */ (void) entry; (void) foo; if (scr->icon_title_texture) { wTextureDestroy(scr, (WTexture *) scr->icon_title_texture); } scr->icon_title_texture = wTextureMakeSolid(scr, color); return REFRESH_ICON_TITLE_BACK; } static int setFrameBorderWidth(WScreen * scr, WDefaultEntry * entry, void *tdata, void *foo) { int *value = tdata; /* Parameter not used, but tell the compiler that it is ok */ (void) entry; (void) foo; scr->frame_border_width = *value; return REFRESH_FRAME_BORDER; } static int setFrameBorderColor(WScreen * scr, WDefaultEntry * entry, void *tdata, void *foo) { XColor *color = tdata; /* Parameter not used, but tell the compiler that it is ok */ (void) entry; (void) foo; if (scr->frame_border_color) WMReleaseColor(scr->frame_border_color); scr->frame_border_color = WMCreateRGBColor(scr->wmscreen, color->red, color->green, color->blue, True); wFreeColor(scr, color->pixel); return REFRESH_FRAME_BORDER; } static int setFrameFocusedBorderColor(WScreen *scr, WDefaultEntry *entry, void *tdata, void *foo) { XColor *color = tdata; /* Parameter not used, but tell the compiler that it is ok */ (void) entry; (void) foo; if (scr->frame_focused_border_color) WMReleaseColor(scr->frame_focused_border_color); scr->frame_focused_border_color = WMCreateRGBColor(scr->wmscreen, color->red, color->green, color->blue, True); wFreeColor(scr, color->pixel); return REFRESH_FRAME_BORDER; } static int setFrameSelectedBorderColor(WScreen * scr, WDefaultEntry * entry, void *tdata, void *foo) { XColor *color = tdata; /* Parameter not used, but tell the compiler that it is ok */ (void) entry; (void) foo; if (scr->frame_selected_border_color) WMReleaseColor(scr->frame_selected_border_color); scr->frame_selected_border_color = WMCreateRGBColor(scr->wmscreen, color->red, color->green, color->blue, True); wFreeColor(scr, color->pixel); return REFRESH_FRAME_BORDER; } static int setWorkspaceSpecificBack(WScreen * scr, WDefaultEntry * entry, void *tdata, void *bar) { WMPropList *value = tdata; WMPropList *val; char *str; int i; /* Parameter not used, but tell the compiler that it is ok */ (void) entry; (void) bar; if (scr->flags.backimage_helper_launched) { if (WMGetPropListItemCount(value) == 0) { SendHelperMessage(scr, 'C', 0, NULL); SendHelperMessage(scr, 'K', 0, NULL); WMReleasePropList(value); return 0; } } else { if (WMGetPropListItemCount(value) == 0) return 0; if (!start_bg_helper(scr)) { WMReleasePropList(value); return 0; } SendHelperMessage(scr, 'P', -1, wPreferences.pixmap_path); } for (i = 0; i < WMGetPropListItemCount(value); i++) { val = WMGetFromPLArray(value, i); if (val && WMIsPLArray(val) && WMGetPropListItemCount(val) > 0) { str = WMGetPropListDescription(val, False); SendHelperMessage(scr, 'S', i + 1, str); wfree(str); } else { SendHelperMessage(scr, 'U', i + 1, NULL); } } sleep(1); WMReleasePropList(value); return 0; } static int setWorkspaceBack(WScreen * scr, WDefaultEntry * entry, void *tdata, void *bar) { WMPropList *value = tdata; /* Parameter not used, but tell the compiler that it is ok */ (void) entry; (void) bar; if (scr->flags.backimage_helper_launched) { char *str; if (WMGetPropListItemCount(value) == 0) { SendHelperMessage(scr, 'U', 0, NULL); } else { /* set the default workspace background to this one */ str = WMGetPropListDescription(value, False); if (str) { SendHelperMessage(scr, 'S', 0, str); wfree(str); SendHelperMessage(scr, 'C', scr->current_workspace + 1, NULL); } else { SendHelperMessage(scr, 'U', 0, NULL); } } } else if (WMGetPropListItemCount(value) > 0) { char *text; char *dither; int len; text = WMGetPropListDescription(value, False); len = strlen(text) + 40; dither = wPreferences.no_dithering ? "-m" : "-d"; if (!strchr(text, '\'') && !strchr(text, '\\')) { char command[len]; if (wPreferences.smooth_workspace_back) snprintf(command, len, "wmsetbg %s -S -p '%s' &", dither, text); else snprintf(command, len, "wmsetbg %s -p '%s' &", dither, text); ExecuteShellCommand(scr, command); } else wwarning(_("Invalid arguments for background \"%s\""), text); wfree(text); } WMReleasePropList(value); return 0; } static int setWidgetColor(WScreen * scr, WDefaultEntry * entry, void *tdata, void *foo) { WTexture **texture = tdata; /* Parameter not used, but tell the compiler that it is ok */ (void) entry; (void) foo; if (scr->widget_texture) { wTextureDestroy(scr, (WTexture *) scr->widget_texture); } scr->widget_texture = *(WTexSolid **) texture; return 0; } static int setFTitleBack(WScreen * scr, WDefaultEntry * entry, void *tdata, void *foo) { WTexture **texture = tdata; /* Parameter not used, but tell the compiler that it is ok */ (void) entry; (void) foo; if (scr->window_title_texture[WS_FOCUSED]) { wTextureDestroy(scr, scr->window_title_texture[WS_FOCUSED]); } scr->window_title_texture[WS_FOCUSED] = *texture; return REFRESH_WINDOW_TEXTURES; } static int setPTitleBack(WScreen * scr, WDefaultEntry * entry, void *tdata, void *foo) { WTexture **texture = tdata; /* Parameter not used, but tell the compiler that it is ok */ (void) entry; (void) foo; if (scr->window_title_texture[WS_PFOCUSED]) { wTextureDestroy(scr, scr->window_title_texture[WS_PFOCUSED]); } scr->window_title_texture[WS_PFOCUSED] = *texture; return REFRESH_WINDOW_TEXTURES; } static int setUTitleBack(WScreen * scr, WDefaultEntry * entry, void *tdata, void *foo) { WTexture **texture = tdata; /* Parameter not used, but tell the compiler that it is ok */ (void) entry; (void) foo; if (scr->window_title_texture[WS_UNFOCUSED]) { wTextureDestroy(scr, scr->window_title_texture[WS_UNFOCUSED]); } scr->window_title_texture[WS_UNFOCUSED] = *texture; return REFRESH_WINDOW_TEXTURES; } static int setResizebarBack(WScreen * scr, WDefaultEntry * entry, void *tdata, void *foo) { WTexture **texture = tdata; /* Parameter not used, but tell the compiler that it is ok */ (void) entry; (void) foo; if (scr->resizebar_texture[0]) { wTextureDestroy(scr, scr->resizebar_texture[0]); } scr->resizebar_texture[0] = *texture; return REFRESH_WINDOW_TEXTURES; } static int setMenuTitleBack(WScreen * scr, WDefaultEntry * entry, void *tdata, void *foo) { WTexture **texture = tdata; /* Parameter not used, but tell the compiler that it is ok */ (void) entry; (void) foo; if (scr->menu_title_texture[0]) { wTextureDestroy(scr, scr->menu_title_texture[0]); } scr->menu_title_texture[0] = *texture; return REFRESH_MENU_TITLE_TEXTURE; } static int setMenuTextBack(WScreen * scr, WDefaultEntry * entry, void *tdata, void *foo) { WTexture **texture = tdata; /* Parameter not used, but tell the compiler that it is ok */ (void) entry; (void) foo; if (scr->menu_item_texture) { wTextureDestroy(scr, scr->menu_item_texture); wTextureDestroy(scr, (WTexture *) scr->menu_item_auxtexture); } scr->menu_item_texture = *texture; scr->menu_item_auxtexture = wTextureMakeSolid(scr, &scr->menu_item_texture->any.color); return REFRESH_MENU_TEXTURE; } static int setKeyGrab(WScreen * scr, WDefaultEntry * entry, void *tdata, void *extra_data) { WShortKey *shortcut = tdata; WWindow *wwin; long widx = (long) extra_data; /* Parameter not used, but tell the compiler that it is ok */ (void) entry; wKeyBindings[widx] = *shortcut; wwin = scr->focused_window; while (wwin != NULL) { XUngrabKey(dpy, AnyKey, AnyModifier, wwin->frame->core->window); if (!WFLAGP(wwin, no_bind_keys)) { wWindowSetKeyGrabs(wwin); } wwin = wwin->prev; } /* do we need to update window menus? */ if (widx >= WKBD_WORKSPACE1 && widx <= WKBD_WORKSPACE10) return REFRESH_WORKSPACE_MENU; if (widx == WKBD_LASTWORKSPACE) return REFRESH_WORKSPACE_MENU; if (widx >= WKBD_MOVE_WORKSPACE1 && widx <= WKBD_MOVE_WORKSPACE10) return REFRESH_WORKSPACE_MENU; return 0; } static int setIconPosition(WScreen * scr, WDefaultEntry * entry, void *bar, void *foo) { /* Parameter not used, but tell the compiler that it is ok */ (void) entry; (void) bar; (void) foo; wScreenUpdateUsableArea(scr); wArrangeIcons(scr, True); return 0; } static int updateUsableArea(WScreen * scr, WDefaultEntry * entry, void *bar, void *foo) { /* Parameter not used, but tell the compiler that it is ok */ (void) entry; (void) bar; (void) foo; wScreenUpdateUsableArea(scr); return 0; } static int setWorkspaceMapBackground(WScreen *scr, WDefaultEntry *entry, void *tdata, void *foo) { WTexture **texture = tdata; /* Parameter not used, but tell the compiler that it is ok */ (void) entry; (void) foo; if (wPreferences.wsmbackTexture) wTextureDestroy(scr, wPreferences.wsmbackTexture); wPreferences.wsmbackTexture = *texture; return REFRESH_WINDOW_TEXTURES; } static int setMenuStyle(WScreen * scr, WDefaultEntry * entry, void *tdata, void *foo) { /* Parameter not used, but tell the compiler that it is ok */ (void) scr; (void) entry; (void) tdata; (void) foo; return REFRESH_MENU_TEXTURE; } static RImage *chopOffImage(RImage * image, int x, int y, int w, int h) { RImage *img = RCreateImage(w, h, image->format == RRGBAFormat); RCopyArea(img, image, x, y, w, h, 0, 0); return img; } static int setSwPOptions(WScreen * scr, WDefaultEntry * entry, void *tdata, void *foo) { WMPropList *array = tdata; char *path; RImage *bgimage; int cwidth, cheight; struct WPreferences *prefs = foo; if (!WMIsPLArray(array) || WMGetPropListItemCount(array) == 0) { if (prefs->swtileImage) RReleaseImage(prefs->swtileImage); prefs->swtileImage = NULL; WMReleasePropList(array); return 0; } switch (WMGetPropListItemCount(array)) { case 4: if (!WMIsPLString(WMGetFromPLArray(array, 1))) { wwarning(_("Invalid arguments for option \"%s\""), entry->key); break; } else path = FindImage(wPreferences.pixmap_path, WMGetFromPLString(WMGetFromPLArray(array, 1))); if (!path) { wwarning(_("Could not find image \"%s\" for option \"%s\""), WMGetFromPLString(WMGetFromPLArray(array, 1)), entry->key); } else { bgimage = RLoadImage(scr->rcontext, path, 0); if (!bgimage) { wwarning(_("Could not load image \"%s\" for option \"%s\""), path, entry->key); wfree(path); } else { wfree(path); cwidth = atoi(WMGetFromPLString(WMGetFromPLArray(array, 2))); cheight = atoi(WMGetFromPLString(WMGetFromPLArray(array, 3))); if (cwidth <= 0 || cheight <= 0 || cwidth >= bgimage->width - 2 || cheight >= bgimage->height - 2) wwarning(_("Invalid split sizes for switch panel back image.")); else { int i; int swidth, theight; for (i = 0; i < 9; i++) { if (prefs->swbackImage[i]) RReleaseImage(prefs->swbackImage[i]); prefs->swbackImage[i] = NULL; } swidth = (bgimage->width - cwidth) / 2; theight = (bgimage->height - cheight) / 2; prefs->swbackImage[0] = chopOffImage(bgimage, 0, 0, swidth, theight); prefs->swbackImage[1] = chopOffImage(bgimage, swidth, 0, cwidth, theight); prefs->swbackImage[2] = chopOffImage(bgimage, swidth + cwidth, 0, swidth, theight); prefs->swbackImage[3] = chopOffImage(bgimage, 0, theight, swidth, cheight); prefs->swbackImage[4] = chopOffImage(bgimage, swidth, theight, cwidth, cheight); prefs->swbackImage[5] = chopOffImage(bgimage, swidth + cwidth, theight, swidth, cheight); prefs->swbackImage[6] = chopOffImage(bgimage, 0, theight + cheight, swidth, theight); prefs->swbackImage[7] = chopOffImage(bgimage, swidth, theight + cheight, cwidth, theight); prefs->swbackImage[8] = chopOffImage(bgimage, swidth + cwidth, theight + cheight, swidth, theight); // check if anything failed for (i = 0; i < 9; i++) { if (!prefs->swbackImage[i]) { for (; i >= 0; --i) { RReleaseImage(prefs->swbackImage[i]); prefs->swbackImage[i] = NULL; } break; } } } RReleaseImage(bgimage); } } + /* Fall through. */ + case 1: if (!WMIsPLString(WMGetFromPLArray(array, 0))) { wwarning(_("Invalid arguments for option \"%s\""), entry->key); break; } else path = FindImage(wPreferences.pixmap_path, WMGetFromPLString(WMGetFromPLArray(array, 0))); if (!path) { wwarning(_("Could not find image \"%s\" for option \"%s\""), WMGetFromPLString(WMGetFromPLArray(array, 0)), entry->key); } else { if (prefs->swtileImage) RReleaseImage(prefs->swtileImage); prefs->swtileImage = RLoadImage(scr->rcontext, path, 0); if (!prefs->swtileImage) { wwarning(_("Could not load image \"%s\" for option \"%s\""), path, entry->key); } wfree(path); } break; default: wwarning(_("Invalid number of arguments for option \"%s\""), entry->key); break; } WMReleasePropList(array); return 0; } static int setModifierKeyLabels(WScreen * scr, WDefaultEntry * entry, void *tdata, void *foo) { WMPropList *array = tdata; int i; struct WPreferences *prefs = foo; if (!WMIsPLArray(array) || WMGetPropListItemCount(array) != 7) { wwarning(_("Value for option \"%s\" must be an array of 7 strings"), entry->key); WMReleasePropList(array); return 0; } DestroyWindowMenu(scr); for (i = 0; i < 7; i++) { if (prefs->modifier_labels[i]) wfree(prefs->modifier_labels[i]); if (WMIsPLString(WMGetFromPLArray(array, i))) { prefs->modifier_labels[i] = wstrdup(WMGetFromPLString(WMGetFromPLArray(array, i))); } else { wwarning(_("Invalid argument for option \"%s\" item %d"), entry->key, i); prefs->modifier_labels[i] = NULL; } } WMReleasePropList(array); return 0; } static int setDoubleClick(WScreen *scr, WDefaultEntry *entry, void *tdata, void *foo) { int *value = tdata; /* Parameter not used, but tell the compiler that it is ok */ (void) entry; (void) scr; if (*value <= 0) *(int *)foo = 1; W_setconf_doubleClickDelay(*value); return 0; } static int setCursor(WScreen * scr, WDefaultEntry * entry, void *tdata, void *extra_data) { Cursor *cursor = tdata; long widx = (long) extra_data; /* Parameter not used, but tell the compiler that it is ok */ (void) entry; if (wPreferences.cursor[widx] != None) { XFreeCursor(dpy, wPreferences.cursor[widx]); } wPreferences.cursor[widx] = *cursor; if (widx == WCUR_ROOT && *cursor != None) { XDefineCursor(dpy, scr->root_win, *cursor); } return 0; } diff --git a/src/menu.c b/src/menu.c index cc4d737..130fe13 100644 --- a/src/menu.c +++ b/src/menu.c @@ -1082,1077 +1082,1079 @@ void wMenuMapAt(WMenu * menu, int x, int y, int keyboard) } else { selectEntry(menu, 0); } if (keyboard) keyboardMenu(menu); } void wMenuMap(WMenu * menu) { if (!menu->flags.realized) { menu->flags.realized = 1; wMenuRealize(menu); } if (menu->flags.app_menu && menu->parent == NULL) { menu->frame_x = menu->frame->screen_ptr->app_menu_x; menu->frame_y = menu->frame->screen_ptr->app_menu_y; XMoveWindow(dpy, menu->frame->core->window, menu->frame_x, menu->frame_y); } XMapWindow(dpy, menu->frame->core->window); wRaiseFrame(menu->frame->core); menu->flags.mapped = 1; } void wMenuUnmap(WMenu * menu) { int i; XUnmapWindow(dpy, menu->frame->core->window); if (menu->flags.titled && menu->flags.buttoned) { wFrameWindowHideButton(menu->frame, WFF_RIGHT_BUTTON); } menu->flags.buttoned = 0; menu->flags.mapped = 0; menu->flags.open_to_left = 0; if (menu->flags.shaded) { wFrameWindowResize(menu->frame, menu->frame->core->width, menu->frame->top_width + menu->entry_height*menu->entry_no + menu->frame->bottom_width - 1); menu->flags.shaded = 0; } for (i = 0; i < menu->cascade_no; i++) { if (menu->cascades[i] != NULL && menu->cascades[i]->flags.mapped && !menu->cascades[i]->flags.buttoned) { wMenuUnmap(menu->cascades[i]); } } menu->selected_entry = -1; } void wMenuPaint(WMenu * menu) { int i; if (!menu->flags.mapped) { return; } /* paint entries */ for (i = 0; i < menu->entry_no; i++) { paintEntry(menu, i, i == menu->selected_entry); } } void wMenuSetEnabled(WMenu * menu, int index, int enable) { if (index >= menu->entry_no) return; menu->entries[index]->flags.enabled = enable; paintEntry(menu, index, index == menu->selected_entry); paintEntry(menu->brother, index, index == menu->selected_entry); } static void selectEntry(WMenu * menu, int entry_no) { WMenuEntry *entry; WMenu *submenu; int old_entry; if (menu->entries == NULL) return; if (entry_no >= menu->entry_no) return; old_entry = menu->selected_entry; menu->selected_entry = entry_no; if (old_entry != entry_no) { /* unselect previous entry */ if (old_entry >= 0) { paintEntry(menu, old_entry, False); entry = menu->entries[old_entry]; /* unmap cascade */ if (entry->cascade >= 0 && menu->cascades) { if (!menu->cascades[entry->cascade]->flags.buttoned) { wMenuUnmap(menu->cascades[entry->cascade]); } } } if (entry_no < 0) { menu->selected_entry = -1; return; } entry = menu->entries[entry_no]; if (entry->cascade >= 0 && menu->cascades && entry->flags.enabled) { /* Callback for when the submenu is opened. */ submenu = menu->cascades[entry->cascade]; if (submenu && submenu->flags.brother) submenu = submenu->brother; if (entry->callback) { /* Only call the callback if the submenu is not yet mapped. */ if (menu->flags.brother) { if (!submenu || !submenu->flags.mapped) (*entry->callback) (menu->brother, entry); } else { if (!submenu || !submenu->flags.buttoned) (*entry->callback) (menu, entry); } } /* the submenu menu might have changed */ submenu = menu->cascades[entry->cascade]; /* map cascade */ if (!submenu->flags.mapped) { int x, y; if (!submenu->flags.realized) wMenuRealize(submenu); if (wPreferences.wrap_menus) { if (menu->flags.open_to_left) submenu->flags.open_to_left = 1; if (submenu->flags.open_to_left) { x = menu->frame_x - MENUW(submenu); if (x < 0) { x = 0; submenu->flags.open_to_left = 0; } } else { x = menu->frame_x + MENUW(menu); if (x + MENUW(submenu) >= menu->frame->screen_ptr->scr_width) { x = menu->frame_x - MENUW(submenu); submenu->flags.open_to_left = 1; } } } else { x = menu->frame_x + MENUW(menu); } if (wPreferences.align_menus) { y = menu->frame_y; } else { y = menu->frame_y + menu->entry_height * entry_no; if (menu->flags.titled) y += menu->frame->top_width; if (menu->cascades[entry->cascade]->flags.titled) y -= menu->cascades[entry->cascade]->frame->top_width; } wMenuMapAt(menu->cascades[entry->cascade], x, y, False); menu->cascades[entry->cascade]->parent = menu; } else { return; } } paintEntry(menu, entry_no, True); } } static WMenu *findMenu(WScreen * scr, int *x_ret, int *y_ret) { WMenu *menu; WObjDescriptor *desc; Window root_ret, win, junk_win; int x, y, wx, wy; unsigned int mask; XQueryPointer(dpy, scr->root_win, &root_ret, &win, &x, &y, &wx, &wy, &mask); if (win == None) return NULL; if (XFindContext(dpy, win, w_global.context.client_win, (XPointer *) & desc) == XCNOENT) return NULL; if (desc->parent_type == WCLASS_MENU) { menu = (WMenu *) desc->parent; XTranslateCoordinates(dpy, root_ret, menu->menu->window, wx, wy, x_ret, y_ret, &junk_win); return menu; } return NULL; } static void closeCascade(WMenu * menu) { WMenu *parent = menu->parent; if (menu->flags.brother || (!menu->flags.buttoned && (!menu->flags.app_menu || menu->parent != NULL))) { selectEntry(menu, -1); XSync(dpy, 0); #if (MENU_BLINK_DELAY > 2) wusleep(MENU_BLINK_DELAY / 2); #endif wMenuUnmap(menu); while (parent != NULL && (parent->parent != NULL || !parent->flags.app_menu || parent->flags.brother) && !parent->flags.buttoned) { selectEntry(parent, -1); wMenuUnmap(parent); parent = parent->parent; } if (parent) selectEntry(parent, -1); } } static void closeBrotherCascadesOf(WMenu * menu) { WMenu *tmp; int i; for (i = 0; i < menu->cascade_no; i++) { if (menu->cascades[i]->flags.brother) { tmp = menu->cascades[i]; } else { tmp = menu->cascades[i]->brother; } if (tmp->flags.mapped) { selectEntry(tmp->parent, -1); closeBrotherCascadesOf(tmp); break; } } } #define getEntryAt(menu, x, y) ((y)<0 ? -1 : (y)/(menu->entry_height)) static WMenu *parentMenu(WMenu * menu) { WMenu *parent; WMenuEntry *entry; if (menu->flags.buttoned) return menu; while (menu->parent && menu->parent->flags.mapped) { parent = menu->parent; if (parent->selected_entry < 0) break; entry = parent->entries[parent->selected_entry]; if (!entry->flags.enabled || entry->cascade < 0 || !parent->cascades || parent->cascades[entry->cascade] != menu) break; menu = parent; if (menu->flags.buttoned) break; } return menu; } /* * Will raise the passed menu, if submenu = 0 * If submenu > 0 will also raise all mapped submenus * until the first buttoned one * If submenu < 0 will also raise all mapped parent menus * until the first buttoned one */ static void raiseMenus(WMenu * menu, int submenus) { WMenu *submenu; int i; if (!menu) return; wRaiseFrame(menu->frame->core); if (submenus > 0 && menu->selected_entry >= 0) { i = menu->entries[menu->selected_entry]->cascade; if (i >= 0 && menu->cascades) { submenu = menu->cascades[i]; if (submenu->flags.mapped && !submenu->flags.buttoned) raiseMenus(submenu, submenus); } } if (submenus < 0 && !menu->flags.buttoned && menu->parent && menu->parent->flags.mapped) raiseMenus(menu->parent, submenus); } WMenu *wMenuUnderPointer(WScreen * screen) { WObjDescriptor *desc; Window root_ret, win; int dummy; unsigned int mask; XQueryPointer(dpy, screen->root_win, &root_ret, &win, &dummy, &dummy, &dummy, &dummy, &mask); if (win == None) return NULL; if (XFindContext(dpy, win, w_global.context.client_win, (XPointer *) & desc) == XCNOENT) return NULL; if (desc->parent_type == WCLASS_MENU) return (WMenu *) desc->parent; return NULL; } static void getPointerPosition(WScreen * scr, int *x, int *y) { Window root_ret, win; int wx, wy; unsigned int mask; XQueryPointer(dpy, scr->root_win, &root_ret, &win, x, y, &wx, &wy, &mask); } static void getScrollAmount(WMenu * menu, int *hamount, int *vamount) { WScreen *scr = menu->menu->screen_ptr; int menuX1 = menu->frame_x; int menuY1 = menu->frame_y; int menuX2 = menu->frame_x + MENUW(menu); int menuY2 = menu->frame_y + MENUH(menu); int xroot, yroot; WMRect rect = wGetRectForHead(scr, wGetHeadForPointerLocation(scr)); *hamount = 0; *vamount = 0; getPointerPosition(scr, &xroot, &yroot); if (xroot <= (rect.pos.x + 1) && menuX1 < rect.pos.x) { /* scroll to the right */ *hamount = WMIN(MENU_SCROLL_STEP, abs(menuX1)); } else if (xroot >= (rect.pos.x + rect.size.width - 2) && menuX2 > (rect.pos.x + rect.size.width - 1)) { /* scroll to the left */ *hamount = WMIN(MENU_SCROLL_STEP, abs(menuX2 - rect.pos.x - rect.size.width - 1)); if (*hamount == 0) *hamount = 1; *hamount = -*hamount; } if (yroot <= (rect.pos.y + 1) && menuY1 < rect.pos.y) { /* scroll down */ *vamount = WMIN(MENU_SCROLL_STEP, abs(menuY1)); } else if (yroot >= (rect.pos.y + rect.size.height - 2) && menuY2 > (rect.pos.y + rect.size.height - 1)) { /* scroll up */ *vamount = WMIN(MENU_SCROLL_STEP, abs(menuY2 - rect.pos.y - rect.size.height - 2)); *vamount = -*vamount; } } static void dragScrollMenuCallback(void *data) { WMenu *menu = (WMenu *) data; WScreen *scr = menu->menu->screen_ptr; WMenu *parent = parentMenu(menu); int hamount, vamount; int x, y; int newSelectedEntry; getScrollAmount(menu, &hamount, &vamount); if (hamount != 0 || vamount != 0) { wMenuMove(parent, parent->frame_x + hamount, parent->frame_y + vamount, True); if (findMenu(scr, &x, &y)) { newSelectedEntry = getEntryAt(menu, x, y); selectEntry(menu, newSelectedEntry); } else { /* Pointer fell outside of menu. If the selected entry is * not a submenu, unselect it */ if (menu->selected_entry >= 0 && menu->entries[menu->selected_entry]->cascade < 0) selectEntry(menu, -1); newSelectedEntry = 0; } /* paranoid check */ if (newSelectedEntry >= 0) { /* keep scrolling */ menu->timer = WMAddTimerHandler(MENU_SCROLL_DELAY, dragScrollMenuCallback, menu); } else { menu->timer = NULL; } } else { /* don't need to scroll anymore */ menu->timer = NULL; if (findMenu(scr, &x, &y)) { newSelectedEntry = getEntryAt(menu, x, y); selectEntry(menu, newSelectedEntry); } } } static void scrollMenuCallback(void *data) { WMenu *menu = (WMenu *) data; WMenu *parent = parentMenu(menu); int hamount = 0; /* amount to scroll */ int vamount = 0; getScrollAmount(menu, &hamount, &vamount); if (hamount != 0 || vamount != 0) { wMenuMove(parent, parent->frame_x + hamount, parent->frame_y + vamount, True); /* keep scrolling */ menu->timer = WMAddTimerHandler(MENU_SCROLL_DELAY, scrollMenuCallback, menu); } else { /* don't need to scroll anymore */ menu->timer = NULL; } } #define MENU_SCROLL_BORDER 5 static int isPointNearBoder(WMenu * menu, int x, int y) { int menuX1 = menu->frame_x; int menuY1 = menu->frame_y; int menuX2 = menu->frame_x + MENUW(menu); int menuY2 = menu->frame_y + MENUH(menu); int flag = 0; int head = wGetHeadForPoint(menu->frame->screen_ptr, wmkpoint(x, y)); WMRect rect = wGetRectForHead(menu->frame->screen_ptr, head); /* XXX: handle screen joins properly !! */ if (x >= menuX1 && x <= menuX2 && (y < rect.pos.y + MENU_SCROLL_BORDER || y >= rect.pos.y + rect.size.height - MENU_SCROLL_BORDER)) flag = 1; else if (y >= menuY1 && y <= menuY2 && (x < rect.pos.x + MENU_SCROLL_BORDER || x >= rect.pos.x + rect.size.width - MENU_SCROLL_BORDER)) flag = 1; return flag; } typedef struct _delay { WMenu *menu; int ox, oy; } _delay; static void callback_leaving(void *user_param) { _delay *dl = (_delay *) user_param; wMenuMove(dl->menu, dl->ox, dl->oy, True); dl->menu->jump_back = NULL; dl->menu->menu->screen_ptr->flags.jump_back_pending = 0; wfree(dl); } void wMenuScroll(WMenu *menu) { WMenu *smenu; WMenu *omenu = parentMenu(menu); WScreen *scr = menu->frame->screen_ptr; int done = 0; int jump_back = 0; int old_frame_x = omenu->frame_x; int old_frame_y = omenu->frame_y; XEvent ev; if (omenu->jump_back) WMDeleteTimerWithClientData(omenu->jump_back); if (( /*omenu->flags.buttoned && */ !wPreferences.wrap_menus) || omenu->flags.app_menu) { jump_back = 1; } if (!wPreferences.wrap_menus) raiseMenus(omenu, True); else raiseMenus(menu, False); if (!menu->timer) scrollMenuCallback(menu); while (!done) { int x, y, on_border, on_x_edge, on_y_edge, on_title; WMRect rect; WMNextEvent(dpy, &ev); switch (ev.type) { case EnterNotify: WMHandleEvent(&ev); + /* Fall through. */ case MotionNotify: x = (ev.type == MotionNotify) ? ev.xmotion.x_root : ev.xcrossing.x_root; y = (ev.type == MotionNotify) ? ev.xmotion.y_root : ev.xcrossing.y_root; /* on_border is != 0 if the pointer is between the menu * and the screen border and is close enough to the border */ on_border = isPointNearBoder(menu, x, y); smenu = wMenuUnderPointer(scr); if ((smenu == NULL && !on_border) || (smenu && parentMenu(smenu) != omenu)) { done = 1; break; } rect = wGetRectForHead(scr, wGetHeadForPoint(scr, wmkpoint(x, y))); on_x_edge = x <= rect.pos.x + 1 || x >= rect.pos.x + rect.size.width - 2; on_y_edge = y <= rect.pos.y + 1 || y >= rect.pos.y + rect.size.height - 2; on_border = on_x_edge || on_y_edge; if (!on_border && !jump_back) { done = 1; break; } if (menu->timer && (smenu != menu || (!on_y_edge && !on_x_edge))) { WMDeleteTimerHandler(menu->timer); menu->timer = NULL; } if (smenu != NULL) menu = smenu; if (!menu->timer) scrollMenuCallback(menu); break; case ButtonPress: /* True if we push on title, or drag the omenu to other position */ on_title = ev.xbutton.x_root >= omenu->frame_x && ev.xbutton.x_root <= omenu->frame_x + MENUW(omenu) && ev.xbutton.y_root >= omenu->frame_y && ev.xbutton.y_root <= omenu->frame_y + omenu->frame->top_width; WMHandleEvent(&ev); smenu = wMenuUnderPointer(scr); if (smenu == NULL || (smenu && smenu->flags.buttoned && smenu != omenu)) done = 1; else if (smenu == omenu && on_title) { jump_back = 0; done = 1; } break; case KeyPress: done = 1; + /* Fall through. */ default: WMHandleEvent(&ev); break; } } if (menu->timer) { WMDeleteTimerHandler(menu->timer); menu->timer = NULL; } if (jump_back) { _delay *delayer; if (!omenu->jump_back) { delayer = wmalloc(sizeof(_delay)); delayer->menu = omenu; delayer->ox = old_frame_x; delayer->oy = old_frame_y; omenu->jump_back = delayer; scr->flags.jump_back_pending = 1; } else delayer = omenu->jump_back; WMAddTimerHandler(MENU_JUMP_BACK_DELAY, callback_leaving, delayer); } } static void menuExpose(WObjDescriptor * desc, XEvent * event) { /* Parameter not used, but tell the compiler that it is ok */ (void) event; wMenuPaint(desc->parent); } typedef struct { int *delayed_select; WMenu *menu; WMHandlerID magic; } delay_data; static void delaySelection(void *data) { delay_data *d = (delay_data *) data; int x, y, entry_no; WMenu *menu; d->magic = NULL; menu = findMenu(d->menu->menu->screen_ptr, &x, &y); if (menu && (d->menu == menu || d->delayed_select)) { entry_no = getEntryAt(menu, x, y); selectEntry(menu, entry_no); } if (d->delayed_select) *(d->delayed_select) = 0; } static void menuMouseDown(WObjDescriptor * desc, XEvent * event) { WWindow *wwin; XButtonEvent *bev = &event->xbutton; WMenu *menu = desc->parent; WMenu *smenu; WScreen *scr = menu->frame->screen_ptr; WMenuEntry *entry = NULL; XEvent ev; int close_on_exit = 0; int done = 0; int delayed_select = 0; int entry_no; int x, y; int prevx, prevy; int old_frame_x = 0; int old_frame_y = 0; delay_data d_data = { NULL, NULL, NULL }; /* Doesn't seem to be needed anymore (if delayed selection handler is * added only if not present). there seem to be no other side effects * from removing this and it is also possible that it was only added * to avoid problems with adding the delayed selection timer handler * multiple times */ /*if (menu->flags.inside_handler) { return; } */ menu->flags.inside_handler = 1; if (!wPreferences.wrap_menus) { smenu = parentMenu(menu); old_frame_x = smenu->frame_x; old_frame_y = smenu->frame_y; } else if (event->xbutton.window == menu->frame->core->window) { /* This is true if the menu was launched with right click on root window */ if (!d_data.magic) { delayed_select = 1; d_data.delayed_select = &delayed_select; d_data.menu = menu; d_data.magic = WMAddTimerHandler(wPreferences.dblclick_time, delaySelection, &d_data); } } wRaiseFrame(menu->frame->core); close_on_exit = (bev->send_event || menu->flags.brother); smenu = findMenu(scr, &x, &y); if (!smenu) { x = -1; y = -1; } else { menu = smenu; } if (menu->flags.editing) { goto byebye; } entry_no = getEntryAt(menu, x, y); if (entry_no >= 0) { entry = menu->entries[entry_no]; if (!close_on_exit && (bev->state & ControlMask) && smenu && entry->flags.editable) { char buffer[128]; char *name; int number = entry_no - 3; /* Entries "New", "Destroy Last" and "Last Used" appear before workspaces */ name = wstrdup(scr->workspaces[number]->name); snprintf(buffer, sizeof(buffer), _("Type the name for workspace %i:"), number + 1); wMenuUnmap(scr->root_menu); if (wInputDialog(scr, _("Rename Workspace"), buffer, &name)) wWorkspaceRename(scr, number, name); if (name) wfree(name); goto byebye; } else if (bev->state & ControlMask) { goto byebye; } if (entry->flags.enabled && entry->cascade >= 0 && menu->cascades) { WMenu *submenu = menu->cascades[entry->cascade]; /* map cascade */ if (submenu->flags.mapped && !submenu->flags.buttoned && menu->selected_entry != entry_no) { wMenuUnmap(submenu); } if (!submenu->flags.mapped && !delayed_select) { selectEntry(menu, entry_no); } else if (!submenu->flags.buttoned) { selectEntry(menu, -1); } } else if (!delayed_select) { if (menu == scr->switch_menu && event->xbutton.button == Button3) { selectEntry(menu, entry_no); OpenWindowMenu2((WWindow *)entry->clientdata, event->xbutton.x_root, event->xbutton.y_root, False); wwin = (WWindow *)entry->clientdata; desc = &wwin->screen_ptr->window_menu->menu->descriptor; event->xany.send_event = True; (*desc->handle_mousedown)(desc, event); XUngrabPointer(dpy, CurrentTime); selectEntry(menu, -1); return; } else { selectEntry(menu, entry_no); } } if (!wPreferences.wrap_menus && !wPreferences.scrollable_menus) { if (!menu->timer) dragScrollMenuCallback(menu); } } prevx = bev->x_root; prevy = bev->y_root; while (!done) { int x, y; XAllowEvents(dpy, AsyncPointer | SyncPointer, CurrentTime); WMMaskEvent(dpy, ExposureMask | ButtonMotionMask | ButtonReleaseMask | ButtonPressMask, &ev); switch (ev.type) { case MotionNotify: smenu = findMenu(scr, &x, &y); if (smenu == NULL) { /* moved mouse out of menu */ if (!delayed_select && d_data.magic) { WMDeleteTimerHandler(d_data.magic); d_data.magic = NULL; } if (menu == NULL || (menu->selected_entry >= 0 && menu->entries[menu->selected_entry]->cascade >= 0)) { prevx = ev.xmotion.x_root; prevy = ev.xmotion.y_root; break; } selectEntry(menu, -1); menu = smenu; prevx = ev.xmotion.x_root; prevy = ev.xmotion.y_root; break; } else if (menu && menu != smenu && (menu->selected_entry < 0 || menu->entries[menu->selected_entry]->cascade < 0)) { selectEntry(menu, -1); if (!delayed_select && d_data.magic) { WMDeleteTimerHandler(d_data.magic); d_data.magic = NULL; } } else { /* hysteresis for item selection */ /* check if the motion was to the side, indicating that * the user may want to cross to a submenu */ if (!delayed_select && menu) { int dx; Bool moved_to_submenu; /* moved to direction of submenu */ dx = abs(prevx - ev.xmotion.x_root); moved_to_submenu = False; if (dx > 0 /* if moved enough to the side */ /* maybe a open submenu */ && menu->selected_entry >= 0 /* moving to the right direction */ && (wPreferences.align_menus || ev.xmotion.y_root >= prevy)) { int index; index = menu->entries[menu->selected_entry]->cascade; if (index >= 0) { if (menu->cascades[index]->frame_x > menu->frame_x) { if (prevx < ev.xmotion.x_root) moved_to_submenu = True; } else { if (prevx > ev.xmotion.x_root) moved_to_submenu = True; } } } if (menu != smenu) { if (d_data.magic) { WMDeleteTimerHandler(d_data.magic); d_data.magic = NULL; } } else if (moved_to_submenu) { /* while we are moving, postpone the selection */ if (d_data.magic) { WMDeleteTimerHandler(d_data.magic); } d_data.delayed_select = NULL; d_data.menu = menu; d_data.magic = WMAddTimerHandler(MENU_SELECT_DELAY, delaySelection, &d_data); prevx = ev.xmotion.x_root; prevy = ev.xmotion.y_root; break; } else { if (d_data.magic) { WMDeleteTimerHandler(d_data.magic); d_data.magic = NULL; } } } } prevx = ev.xmotion.x_root; prevy = ev.xmotion.y_root; if (menu != smenu) { /* pointer crossed menus */ if (menu && menu->timer) { WMDeleteTimerHandler(menu->timer); menu->timer = NULL; } if (smenu) dragScrollMenuCallback(smenu); } menu = smenu; if (!menu->timer) dragScrollMenuCallback(menu); if (!delayed_select) { entry_no = getEntryAt(menu, x, y); if (entry_no >= 0) { entry = menu->entries[entry_no]; if (entry->flags.enabled && entry->cascade >= 0 && menu->cascades) { WMenu *submenu = menu->cascades[entry->cascade]; if (submenu->flags.mapped && !submenu->flags.buttoned && menu->selected_entry != entry_no) { wMenuUnmap(submenu); } } } selectEntry(menu, entry_no); } break; case ButtonPress: break; case ButtonRelease: if (ev.xbutton.button == event->xbutton.button) done = 1; break; case Expose: WMHandleEvent(&ev); break; } } if (menu && menu->timer) { WMDeleteTimerHandler(menu->timer); menu->timer = NULL; } if (d_data.magic != NULL) { WMDeleteTimerHandler(d_data.magic); d_data.magic = NULL; } if (menu && menu->selected_entry >= 0) { entry = menu->entries[menu->selected_entry]; if (entry->callback != NULL && entry->flags.enabled && entry->cascade < 0) { /* blink and erase menu selection */ #if (MENU_BLINK_DELAY > 0) int sel = menu->selected_entry; int i; for (i = 0; i < MENU_BLINK_COUNT; i++) { paintEntry(menu, sel, False); XSync(dpy, 0); wusleep(MENU_BLINK_DELAY); paintEntry(menu, sel, True); XSync(dpy, 0); wusleep(MENU_BLINK_DELAY); } #endif /* unmap the menu, it's parents and call the callback */ if (!menu->flags.buttoned && (!menu->flags.app_menu || menu->parent != NULL)) { closeCascade(menu); } else { selectEntry(menu, -1); } (*entry->callback) (menu, entry); /* If the user double clicks an entry, the entry will * be executed twice, which is not good for things like * the root menu. So, ignore any clicks that were generated * while the entry was being executed */ while (XCheckTypedWindowEvent(dpy, menu->menu->window, ButtonPress, &ev)) ; } else if (entry->callback != NULL && entry->cascade < 0) { selectEntry(menu, -1); } else { if (entry->cascade >= 0 && menu->cascades && menu->cascades[entry->cascade]->flags.brother) { selectEntry(menu, -1); } } } if (((WMenu *) desc->parent)->flags.brother || close_on_exit || !smenu) closeCascade(desc->parent); /* close the cascade windows that should not remain opened */ closeBrotherCascadesOf(desc->parent); if (!wPreferences.wrap_menus) wMenuMove(parentMenu(desc->parent), old_frame_x, old_frame_y, True); byebye: /* Just to be sure in case we skip the 2 above because of a goto byebye */ if (menu && menu->timer) { WMDeleteTimerHandler(menu->timer); menu->timer = NULL; } if (d_data.magic != NULL) { WMDeleteTimerHandler(d_data.magic); d_data.magic = NULL; } ((WMenu *) desc->parent)->flags.inside_handler = 0; } void wMenuMove(WMenu * menu, int x, int y, int submenus) { WMenu *submenu; int i; if (!menu) return; menu->frame_x = x; menu->frame_y = y; XMoveWindow(dpy, menu->frame->core->window, x, y); if (submenus > 0 && menu->selected_entry >= 0) { i = menu->entries[menu->selected_entry]->cascade; if (i >= 0 && menu->cascades) { submenu = menu->cascades[i]; if (submenu->flags.mapped && !submenu->flags.buttoned) { if (wPreferences.align_menus) { wMenuMove(submenu, x + MENUW(menu), y, submenus); } else { wMenuMove(submenu, x + MENUW(menu), y + submenu->entry_height * menu->selected_entry, submenus); } } } } if (submenus < 0 && menu->parent != NULL && menu->parent->flags.mapped && !menu->parent->flags.buttoned) { if (wPreferences.align_menus) { wMenuMove(menu->parent, x - MENUW(menu->parent), y, submenus); } else { wMenuMove(menu->parent, x - MENUW(menu->parent), menu->frame_y - menu->parent->entry_height * menu->parent->selected_entry, submenus); } } } static void changeMenuLevels(WMenu * menu, int lower) { int i; if (!lower) { ChangeStackingLevel(menu->frame->core, (!menu->parent ? WMMainMenuLevel : WMSubmenuLevel)); wRaiseFrame(menu->frame->core); menu->flags.lowered = 0; } else { ChangeStackingLevel(menu->frame->core, WMNormalLevel); wLowerFrame(menu->frame->core); menu->flags.lowered = 1; } for (i = 0; i < menu->cascade_no; i++) { if (menu->cascades[i] && !menu->cascades[i]->flags.buttoned && menu->cascades[i]->flags.lowered != lower) { changeMenuLevels(menu->cascades[i], lower); } } } static void menuTitleDoubleClick(WCoreWindow * sender, void *data, XEvent * event) { WMenu *menu = data; int lower; /* Parameter not used, but tell the compiler that it is ok */ (void) sender; if (event->xbutton.state & MOD_MASK) { if (menu->flags.lowered) { lower = 0; } else { lower = 1; } changeMenuLevels(menu, lower); } else { if (menu->flags.shaded) { wFrameWindowResize(menu->frame, menu->frame->core->width, menu->frame->top_width + menu->entry_height*menu->entry_no + menu->frame->bottom_width - 1); menu->flags.shaded = 0; } else { wFrameWindowResize(menu->frame, menu->frame->core->width, menu->frame->top_width - 1); menu->flags.shaded = 1; } } } static void menuTitleMouseDown(WCoreWindow * sender, void *data, XEvent * event) { WMenu *menu = data; WMenu *tmp; XEvent ev; int x = menu->frame_x, y = menu->frame_y; int dx = event->xbutton.x_root, dy = event->xbutton.y_root; int i, lower; Bool started; /* Parameter not used, but tell the compiler that it is ok */ (void) sender; /* can't touch the menu copy */ if (menu->flags.brother) return; if (event->xbutton.button != Button1 && event->xbutton.button != Button2) return; if (event->xbutton.state & MOD_MASK) { wLowerFrame(menu->frame->core); lower = 1; } else { wRaiseFrame(menu->frame->core); lower = 0; } tmp = menu; /* lower/raise all submenus */ while (1) { if (tmp->selected_entry >= 0 && tmp->cascades && tmp->entries[tmp->selected_entry]->cascade >= 0) { tmp = tmp->cascades[tmp->entries[tmp->selected_entry]->cascade]; if (!tmp || !tmp->flags.mapped) diff --git a/src/placement.c b/src/placement.c index 14fe226..29ee695 100644 --- a/src/placement.c +++ b/src/placement.c @@ -18,553 +18,556 @@ * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "wconfig.h" #include <X11/Xlib.h> #include <stdlib.h> #include <stdio.h> #include <string.h> #include <limits.h> #include "WindowMaker.h" #include "wcore.h" #include "framewin.h" #include "window.h" #include "icon.h" #include "appicon.h" #include "actions.h" #include "application.h" #include "dock.h" #include "xinerama.h" #include "placement.h" #define X_ORIGIN WMAX(usableArea.x1,\ wPreferences.window_place_origin.x) #define Y_ORIGIN WMAX(usableArea.y1,\ wPreferences.window_place_origin.y) /* Returns True if it is an icon and is in this workspace */ static Bool iconPosition(WCoreWindow *wcore, int sx1, int sy1, int sx2, int sy2, int workspace, int *retX, int *retY) { void *parent; int ok = 0; parent = wcore->descriptor.parent; /* if it is an application icon */ if (wcore->descriptor.parent_type == WCLASS_APPICON && !((WAppIcon *) parent)->docked) { *retX = ((WAppIcon *) parent)->x_pos; *retY = ((WAppIcon *) parent)->y_pos; ok = 1; } else if (wcore->descriptor.parent_type == WCLASS_MINIWINDOW && (((WIcon *) parent)->owner->frame->workspace == workspace || IS_OMNIPRESENT(((WIcon *) parent)->owner) || wPreferences.sticky_icons) && ((WIcon *) parent)->mapped) { *retX = ((WIcon *) parent)->owner->icon_x; *retY = ((WIcon *) parent)->owner->icon_y; ok = 1; } else if (wcore->descriptor.parent_type == WCLASS_WINDOW && ((WWindow *) parent)->flags.icon_moved && (((WWindow *) parent)->frame->workspace == workspace || IS_OMNIPRESENT((WWindow *) parent) || wPreferences.sticky_icons)) { *retX = ((WWindow *) parent)->icon_x; *retY = ((WWindow *) parent)->icon_y; ok = 1; } /* Check if it is inside the screen */ if (ok) { if (*retX < sx1 - wPreferences.icon_size) ok = 0; else if (*retX > sx2) ok = 0; if (*retY < sy1 - wPreferences.icon_size) ok = 0; else if (*retY > sy2) ok = 0; } return ok; } void PlaceIcon(WScreen *scr, int *x_ret, int *y_ret, int head) { int pf; /* primary axis */ int sf; /* secondary axis */ int fullW; int fullH; char *map; int pi, si; WCoreWindow *obj; int sx1, sx2, sy1, sy2; /* screen boundary */ int sw, sh; int xo, yo; int xs, ys; int x, y; int isize = wPreferences.icon_size; int done = 0; WMBagIterator iter; WArea area = wGetUsableAreaForHead(scr, head, NULL, False); /* Do not place icons under the dock. */ if (scr->dock) { int offset = wPreferences.icon_size + DOCK_EXTRA_SPACE; if (scr->dock->on_right_side) area.x2 -= offset; else area.x1 += offset; } /* Find out screen boundaries. */ /* Allows each head to have miniwindows */ sx1 = area.x1; sy1 = area.y1; sx2 = area.x2; sy2 = area.y2; sw = sx2 - sx1; sh = sy2 - sy1; sw = isize * (sw / isize); sh = isize * (sh / isize); fullW = (sx2 - sx1) / isize; fullH = (sy2 - sy1) / isize; /* icon yard boundaries */ if (wPreferences.icon_yard & IY_VERT) { pf = fullH; sf = fullW; } else { pf = fullW; sf = fullH; } if (wPreferences.icon_yard & IY_RIGHT) { xo = sx2 - isize; xs = -1; } else { xo = sx1; xs = 1; } if (wPreferences.icon_yard & IY_TOP) { yo = sy1; ys = 1; } else { yo = sy2 - isize; ys = -1; } /* * Create a map with the occupied slots. 1 means the slot is used * or at least partially used. * The slot usage can be optimized by only marking fully used slots * or slots that have most of it covered. * Space usage is worse than the fvwm algorithm (used in the old version) * but complexity is much better (faster) than it. */ map = wmalloc((sw + 2) * (sh + 2)); #define INDEX(x,y) (((y)+1)*(sw+2) + (x) + 1) WM_ETARETI_BAG(scr->stacking_list, obj, iter) { while (obj) { int x, y; if (iconPosition(obj, sx1, sy1, sx2, sy2, scr->current_workspace, &x, &y)) { int xdi, ydi; /* rounded down */ int xui, yui; /* rounded up */ xdi = x / isize; ydi = y / isize; xui = (x + isize / 2) / isize; yui = (y + isize / 2) / isize; map[INDEX(xdi, ydi)] = 1; map[INDEX(xdi, yui)] = 1; map[INDEX(xui, ydi)] = 1; map[INDEX(xui, yui)] = 1; } obj = obj->stacking->under; } } /* Default position */ *x_ret = 0; *y_ret = 0; /* Look for an empty slot */ for (si = 0; si < sf; si++) { for (pi = 0; pi < pf; pi++) { if (wPreferences.icon_yard & IY_VERT) { x = xo + xs * (si * isize); y = yo + ys * (pi * isize); } else { x = xo + xs * (pi * isize); y = yo + ys * (si * isize); } if (!map[INDEX(x / isize, y / isize)]) { *x_ret = x; *y_ret = y; done = 1; break; } } if (done) break; } wfree(map); } /* Computes the intersecting length of two line sections */ int calcIntersectionLength(int p1, int l1, int p2, int l2) { int isect; int tmp; if (p1 > p2) { tmp = p1; p1 = p2; p2 = tmp; tmp = l1; l1 = l2; l2 = tmp; } if (p1 + l1 < p2) isect = 0; else if (p2 + l2 < p1 + l1) isect = l2; else isect = p1 + l1 - p2; return isect; } /* Computes the intersecting area of two rectangles */ int calcIntersectionArea(int x1, int y1, int w1, int h1, int x2, int y2, int w2, int h2) { return calcIntersectionLength(x1, w1, x2, w2) * calcIntersectionLength(y1, h1, y2, h2); } static int calcSumOfCoveredAreas(WWindow *wwin, int x, int y, int w, int h) { int sum_isect = 0; WWindow *test_window; int tw, tx, ty, th; test_window = wwin->screen_ptr->focused_window; for (; test_window != NULL && test_window->prev != NULL;) test_window = test_window->prev; for (; test_window != NULL; test_window = test_window->next) { if (test_window->frame->core->stacking->window_level < WMNormalLevel) { continue; } tw = test_window->frame->core->width; th = test_window->frame->core->height; tx = test_window->frame_x; ty = test_window->frame_y; if (test_window->flags.mapped || (test_window->flags.shaded && test_window->frame->workspace == wwin->screen_ptr->current_workspace && !(test_window->flags.miniaturized || test_window->flags.hidden))) { sum_isect += calcIntersectionArea(tx, ty, tw, th, x, y, w, h); } } return sum_isect; } static void set_width_height(WWindow *wwin, unsigned int *width, unsigned int *height) { if (wwin->frame) { *height += wwin->frame->top_width + wwin->frame->bottom_width; } else { if (HAS_TITLEBAR(wwin)) *height += TITLEBAR_HEIGHT; if (HAS_RESIZEBAR(wwin)) *height += RESIZEBAR_HEIGHT; } if (HAS_BORDER(wwin)) { *height += 2 * wwin->screen_ptr->frame_border_width; *width += 2 * wwin->screen_ptr->frame_border_width; } } static Bool window_overlaps(WWindow *win, int x, int y, int w, int h, Bool ignore_sunken) { int tw, th, tx, ty; if (ignore_sunken && win->frame->core->stacking->window_level < WMNormalLevel) { return False; } tw = win->frame->core->width; th = win->frame->core->height; tx = win->frame_x; ty = win->frame_y; if ((tx < (x + w)) && ((tx + tw) > x) && (ty < (y + h)) && ((ty + th) > y) && (win->flags.mapped || (win->flags.shaded && win->frame->workspace == win->screen_ptr->current_workspace && !(win->flags.miniaturized || win->flags.hidden)))) { return True; } return False; } static Bool screen_has_space(WScreen *scr, int x, int y, int w, int h, Bool ignore_sunken) { WWindow *focused = scr->focused_window, *i; for (i = focused; i; i = i->next) { if (window_overlaps(i, x, y, w, h, ignore_sunken)) { return False; } } for (i = focused; i; i = i->prev) { if (window_overlaps(i, x, y, w, h, ignore_sunken)) { return False; } } return True; } static void smartPlaceWindow(WWindow *wwin, int *x_ret, int *y_ret, unsigned int width, unsigned int height, WArea usableArea) { int test_x = 0, test_y = Y_ORIGIN; int from_x, to_x, from_y, to_y; int sx; int min_isect, min_isect_x, min_isect_y; int sum_isect; set_width_height(wwin, &width, &height); sx = X_ORIGIN; min_isect = INT_MAX; min_isect_x = sx; min_isect_y = test_y; while (((test_y + height) < usableArea.y2)) { test_x = sx; while ((test_x + width) < usableArea.x2) { sum_isect = calcSumOfCoveredAreas(wwin, test_x, test_y, width, height); if (sum_isect < min_isect) { min_isect = sum_isect; min_isect_x = test_x; min_isect_y = test_y; } test_x += PLACETEST_HSTEP; } test_y += PLACETEST_VSTEP; } from_x = min_isect_x - PLACETEST_HSTEP + 1; from_x = WMAX(from_x, X_ORIGIN); to_x = min_isect_x + PLACETEST_HSTEP; if (to_x + width > usableArea.x2) to_x = usableArea.x2 - width; from_y = min_isect_y - PLACETEST_VSTEP + 1; from_y = WMAX(from_y, Y_ORIGIN); to_y = min_isect_y + PLACETEST_VSTEP; if (to_y + height > usableArea.y2) to_y = usableArea.y2 - height; for (test_x = from_x; test_x < to_x; test_x++) { for (test_y = from_y; test_y < to_y; test_y++) { sum_isect = calcSumOfCoveredAreas(wwin, test_x, test_y, width, height); if (sum_isect < min_isect) { min_isect = sum_isect; min_isect_x = test_x; min_isect_y = test_y; } } } *x_ret = min_isect_x; *y_ret = min_isect_y; } static Bool center_place_window(WWindow *wwin, int *x_ret, int *y_ret, unsigned int width, unsigned int height, WArea usableArea) { int swidth, sheight; set_width_height(wwin, &width, &height); swidth = usableArea.x2 - usableArea.x1; sheight = usableArea.y2 - usableArea.y1; if (width > swidth || height > sheight) return False; *x_ret = (usableArea.x1 + usableArea.x2 - width) / 2; *y_ret = (usableArea.y1 + usableArea.y2 - height) / 2; return True; } static Bool autoPlaceWindow(WWindow *wwin, int *x_ret, int *y_ret, unsigned int width, unsigned int height, Bool ignore_sunken, WArea usableArea) { WScreen *scr = wwin->screen_ptr; int x, y; int sw, sh; set_width_height(wwin, &width, &height); sw = usableArea.x2 - usableArea.x1; sh = usableArea.y2 - usableArea.y1; /* try placing at center first */ if (center_place_window(wwin, &x, &y, width, height, usableArea) && screen_has_space(scr, x, y, width, height, False)) { *x_ret = x; *y_ret = y; return True; } /* this was based on fvwm2's smart placement */ for (y = Y_ORIGIN; (y + height) < sh; y += PLACETEST_VSTEP) { for (x = X_ORIGIN; (x + width) < sw; x += PLACETEST_HSTEP) { if (screen_has_space(scr, x, y, width, height, ignore_sunken)) { *x_ret = x; *y_ret = y; return True; } } } return False; } static void cascadeWindow(WScreen *scr, WWindow *wwin, int *x_ret, int *y_ret, unsigned int width, unsigned int height, int h, WArea usableArea) { set_width_height(wwin, &width, &height); *x_ret = h * scr->cascade_index + X_ORIGIN; *y_ret = h * scr->cascade_index + Y_ORIGIN; if (width + *x_ret > usableArea.x2 || height + *y_ret > usableArea.y2) { scr->cascade_index = 0; *x_ret = X_ORIGIN; *y_ret = Y_ORIGIN; } } static void randomPlaceWindow(WWindow *wwin, int *x_ret, int *y_ret, unsigned int width, unsigned int height, WArea usableArea) { int w, h; set_width_height(wwin, &width, &height); w = ((usableArea.x2 - X_ORIGIN) - width); h = ((usableArea.y2 - Y_ORIGIN) - height); if (w < 1) w = 1; if (h < 1) h = 1; *x_ret = X_ORIGIN + rand() % w; *y_ret = Y_ORIGIN + rand() % h; } void PlaceWindow(WWindow *wwin, int *x_ret, int *y_ret, unsigned width, unsigned height) { WScreen *scr = wwin->screen_ptr; int h = WMFontHeight(scr->title_font) + (wPreferences.window_title_clearance + TITLEBAR_EXTEND_SPACE) * 2; if (h > wPreferences.window_title_max_height) h = wPreferences.window_title_max_height; if (h < wPreferences.window_title_min_height) h = wPreferences.window_title_min_height; WArea usableArea = wGetUsableAreaForHead(scr, wGetHeadForPointerLocation(scr), NULL, True); switch (wPreferences.window_placement) { case WPM_MANUAL: InteractivePlaceWindow(wwin, x_ret, y_ret, width, height); break; case WPM_SMART: smartPlaceWindow(wwin, x_ret, y_ret, width, height, usableArea); break; case WPM_CENTER: if (center_place_window(wwin, x_ret, y_ret, width, height, usableArea)) break; + /* Fall through. */ case WPM_AUTO: if (autoPlaceWindow(wwin, x_ret, y_ret, width, height, False, usableArea)) { break; } else if (autoPlaceWindow(wwin, x_ret, y_ret, width, height, True, usableArea)) { break; } /* there isn't a break here, because if we fail, it should fall through to cascade placement, as people who want tiling want automagicness aren't going to want to place their window */ + /* Fall through. */ + case WPM_CASCADE: if (wPreferences.window_placement == WPM_AUTO || wPreferences.window_placement == WPM_CENTER) scr->cascade_index++; cascadeWindow(scr, wwin, x_ret, y_ret, width, height, h, usableArea); if (wPreferences.window_placement == WPM_CASCADE) scr->cascade_index++; break; case WPM_RANDOM: randomPlaceWindow(wwin, x_ret, y_ret, width, height, usableArea); break; } /* * clip to usableArea instead of full screen * this will also take dock/clip etc.. into account * as well as being xinerama friendly */ if (*x_ret + width > usableArea.x2) *x_ret = usableArea.x2 - width; if (*x_ret < usableArea.x1) *x_ret = usableArea.x1; if (*y_ret + height > usableArea.y2) *y_ret = usableArea.y2 - height; if (*y_ret < usableArea.y1) *y_ret = usableArea.y1; }
roblillack/wmaker
b59273f199ee194ae1157bc41e9a8d65eeededca
Added missing function declaration.
diff --git a/src/actions.h b/src/actions.h index 210e53e..1ef40b4 100644 --- a/src/actions.h +++ b/src/actions.h @@ -1,87 +1,88 @@ /* * Window Maker window manager * * Copyright (c) 1997-2003 Alfredo K. Kojima * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef WMACTIONS_H_ #define WMACTIONS_H_ #include "window.h" #define MAX_HORIZONTAL (1 << 0) #define MAX_VERTICAL (1 << 1) #define MAX_LEFTHALF (1 << 2) #define MAX_RIGHTHALF (1 << 3) #define MAX_TOPHALF (1 << 4) #define MAX_BOTTOMHALF (1 << 5) #define MAX_MAXIMUS (1 << 6) #define MAX_IGNORE_XINERAMA (1 << 7) #define MAX_KEYBOARD (1 << 8) #define SAVE_GEOMETRY_X (1 << 0) #define SAVE_GEOMETRY_Y (1 << 1) #define SAVE_GEOMETRY_WIDTH (1 << 2) #define SAVE_GEOMETRY_HEIGHT (1 << 3) #define SAVE_GEOMETRY_ALL SAVE_GEOMETRY_X | SAVE_GEOMETRY_Y | SAVE_GEOMETRY_WIDTH | SAVE_GEOMETRY_HEIGHT void wSetFocusTo(WScreen *scr, WWindow *wwin); int wMouseMoveWindow(WWindow *wwin, XEvent *ev); int wKeyboardMoveResizeWindow(WWindow *wwin); void wMouseResizeWindow(WWindow *wwin, XEvent *ev); void wShadeWindow(WWindow *wwin); void wUnshadeWindow(WWindow *wwin); void wIconifyWindow(WWindow *wwin); void wDeiconifyWindow(WWindow *wwin); void wSelectWindows(WScreen *scr, XEvent *ev); void wSelectWindow(WWindow *wwin, Bool flag); void wUnselectWindows(WScreen *scr); void wMaximizeWindow(WWindow *wwin, int directions, int head); void wUnmaximizeWindow(WWindow *wwin); void handleMaximize(WWindow *wwin, int directions); void wHideAll(WScreen *src); void wHideOtherApplications(WWindow *wwin); void wShowAllWindows(WScreen *scr); void wHideApplication(WApplication *wapp); void wUnhideApplication(WApplication *wapp, Bool miniwindows, Bool bringToCurrentWS); void wRefreshDesktop(WScreen *scr); void wArrangeIcons(WScreen *scr, Bool arrangeAll); void wMakeWindowVisible(WWindow *wwin); void wFullscreenWindow(WWindow *wwin); void wUnfullscreenWindow(WWindow *wwin); void animateResize(WScreen *scr, int x, int y, int w, int h, int fx, int fy, int fw, int fh); void update_saved_geometry(WWindow *wwin); void movePionterToWindowCenter(WWindow *wwin); +void moveBetweenHeads(WWindow *wwin, int direction); #endif
roblillack/wmaker
be922384ac82ae155a3d7678475c3861c1110680
slight increase in default switch panel icon size to improve border view
diff --git a/src/defaults.c b/src/defaults.c index 440376b..e20cc46 100644 --- a/src/defaults.c +++ b/src/defaults.c @@ -1,865 +1,865 @@ /* defaults.c - manage configuration through defaults db * * Window Maker window manager * * Copyright (c) 1997-2003 Alfredo K. Kojima * Copyright (c) 1998-2003 Dan Pascu * Copyright (c) 2014 Window Maker Team * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "wconfig.h" #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <strings.h> #include <ctype.h> #include <time.h> #include <sys/types.h> #include <sys/stat.h> #include <limits.h> #include <signal.h> #ifndef PATH_MAX #define PATH_MAX DEFAULT_PATH_MAX #endif #include <X11/Xlib.h> #include <X11/Xutil.h> #include <X11/keysym.h> #include <wraster.h> #include "WindowMaker.h" #include "framewin.h" #include "window.h" #include "texture.h" #include "screen.h" #include "resources.h" #include "defaults.h" #include "keybind.h" #include "xmodifier.h" #include "icon.h" #include "main.h" #include "actions.h" #include "dock.h" #include "workspace.h" #include "properties.h" #include "misc.h" #include "winmenu.h" #define MAX_SHORTCUT_LENGTH 32 typedef struct _WDefaultEntry WDefaultEntry; typedef int (WDECallbackConvert) (WScreen *scr, WDefaultEntry *entry, WMPropList *plvalue, void *addr, void **tdata); typedef int (WDECallbackUpdate) (WScreen *scr, WDefaultEntry *entry, void *tdata, void *extra_data); struct _WDefaultEntry { const char *key; const char *default_value; void *extra_data; void *addr; WDECallbackConvert *convert; WDECallbackUpdate *update; WMPropList *plkey; WMPropList *plvalue; /* default value */ }; /* used to map strings to integers */ typedef struct { const char *string; short value; char is_alias; } WOptionEnumeration; /* type converters */ static WDECallbackConvert getBool; static WDECallbackConvert getInt; static WDECallbackConvert getCoord; static WDECallbackConvert getPathList; static WDECallbackConvert getEnum; static WDECallbackConvert getTexture; static WDECallbackConvert getWSBackground; static WDECallbackConvert getWSSpecificBackground; static WDECallbackConvert getFont; static WDECallbackConvert getColor; static WDECallbackConvert getKeybind; static WDECallbackConvert getModMask; static WDECallbackConvert getPropList; /* value setting functions */ static WDECallbackUpdate setJustify; static WDECallbackUpdate setClearance; static WDECallbackUpdate setIfDockPresent; static WDECallbackUpdate setClipMergedInDock; static WDECallbackUpdate setWrapAppiconsInDock; static WDECallbackUpdate setStickyIcons; static WDECallbackUpdate setWidgetColor; static WDECallbackUpdate setIconTile; static WDECallbackUpdate setWinTitleFont; static WDECallbackUpdate setMenuTitleFont; static WDECallbackUpdate setMenuTextFont; static WDECallbackUpdate setIconTitleFont; static WDECallbackUpdate setIconTitleColor; static WDECallbackUpdate setIconTitleBack; static WDECallbackUpdate setFrameBorderWidth; static WDECallbackUpdate setFrameBorderColor; static WDECallbackUpdate setFrameFocusedBorderColor; static WDECallbackUpdate setFrameSelectedBorderColor; static WDECallbackUpdate setLargeDisplayFont; static WDECallbackUpdate setWTitleColor; static WDECallbackUpdate setFTitleBack; static WDECallbackUpdate setPTitleBack; static WDECallbackUpdate setUTitleBack; static WDECallbackUpdate setResizebarBack; static WDECallbackUpdate setWorkspaceBack; static WDECallbackUpdate setWorkspaceSpecificBack; static WDECallbackUpdate setMenuTitleColor; static WDECallbackUpdate setMenuTextColor; static WDECallbackUpdate setMenuDisabledColor; static WDECallbackUpdate setMenuTitleBack; static WDECallbackUpdate setMenuTextBack; static WDECallbackUpdate setHightlight; static WDECallbackUpdate setHightlightText; static WDECallbackUpdate setKeyGrab; static WDECallbackUpdate setDoubleClick; static WDECallbackUpdate setIconPosition; static WDECallbackUpdate setWorkspaceMapBackground; static WDECallbackUpdate setClipTitleFont; static WDECallbackUpdate setClipTitleColor; static WDECallbackUpdate setMenuStyle; static WDECallbackUpdate setSwPOptions; static WDECallbackUpdate updateUsableArea; static WDECallbackUpdate setModifierKeyLabels; static WDECallbackConvert getCursor; static WDECallbackUpdate setCursor; /* * Tables to convert strings to enumeration values. * Values stored are char */ /* WARNING: sum of length of all value strings must not exceed * this value */ #define TOTAL_VALUES_LENGTH 80 #define REFRESH_WINDOW_TEXTURES (1<<0) #define REFRESH_MENU_TEXTURE (1<<1) #define REFRESH_MENU_FONT (1<<2) #define REFRESH_MENU_COLOR (1<<3) #define REFRESH_MENU_TITLE_TEXTURE (1<<4) #define REFRESH_MENU_TITLE_FONT (1<<5) #define REFRESH_MENU_TITLE_COLOR (1<<6) #define REFRESH_WINDOW_TITLE_COLOR (1<<7) #define REFRESH_WINDOW_FONT (1<<8) #define REFRESH_ICON_TILE (1<<9) #define REFRESH_ICON_FONT (1<<10) #define REFRESH_BUTTON_IMAGES (1<<11) #define REFRESH_ICON_TITLE_COLOR (1<<12) #define REFRESH_ICON_TITLE_BACK (1<<13) #define REFRESH_WORKSPACE_MENU (1<<14) #define REFRESH_FRAME_BORDER REFRESH_MENU_FONT|REFRESH_WINDOW_FONT static WOptionEnumeration seFocusModes[] = { {"Manual", WKF_CLICK, 0}, {"ClickToFocus", WKF_CLICK, 1}, {"Sloppy", WKF_SLOPPY, 0}, {"SemiAuto", WKF_SLOPPY, 1}, {"Auto", WKF_SLOPPY, 1}, {NULL, 0, 0} }; static WOptionEnumeration seTitlebarModes[] = { {"new", TS_NEW, 0}, {"old", TS_OLD, 0}, {"next", TS_NEXT, 0}, {NULL, 0, 0} }; static WOptionEnumeration seColormapModes[] = { {"Manual", WCM_CLICK, 0}, {"ClickToFocus", WCM_CLICK, 1}, {"Auto", WCM_POINTER, 0}, {"FocusFollowMouse", WCM_POINTER, 1}, {NULL, 0, 0} }; static WOptionEnumeration sePlacements[] = { {"Auto", WPM_AUTO, 0}, {"Smart", WPM_SMART, 0}, {"Cascade", WPM_CASCADE, 0}, {"Random", WPM_RANDOM, 0}, {"Manual", WPM_MANUAL, 0}, {"Center", WPM_CENTER, 0}, {NULL, 0, 0} }; static WOptionEnumeration seGeomDisplays[] = { {"None", WDIS_NONE, 0}, {"Center", WDIS_CENTER, 0}, {"Corner", WDIS_TOPLEFT, 0}, {"Floating", WDIS_FRAME_CENTER, 0}, {"Line", WDIS_NEW, 0}, {NULL, 0, 0} }; static WOptionEnumeration seSpeeds[] = { {"UltraFast", SPEED_ULTRAFAST, 0}, {"Fast", SPEED_FAST, 0}, {"Medium", SPEED_MEDIUM, 0}, {"Slow", SPEED_SLOW, 0}, {"UltraSlow", SPEED_ULTRASLOW, 0}, {NULL, 0, 0} }; static WOptionEnumeration seMouseButtonActions[] = { {"None", WA_NONE, 0}, {"SelectWindows", WA_SELECT_WINDOWS, 0}, {"OpenApplicationsMenu", WA_OPEN_APPMENU, 0}, {"OpenWindowListMenu", WA_OPEN_WINLISTMENU, 0}, {"MoveToPrevWorkspace", WA_MOVE_PREVWORKSPACE, 0}, {"MoveToNextWorkspace", WA_MOVE_NEXTWORKSPACE, 0}, {"MoveToPrevWindow", WA_MOVE_PREVWINDOW, 0}, {"MoveToNextWindow", WA_MOVE_NEXTWINDOW, 0}, {NULL, 0, 0} }; static WOptionEnumeration seMouseWheelActions[] = { {"None", WA_NONE, 0}, {"SwitchWorkspaces", WA_SWITCH_WORKSPACES, 0}, {"SwitchWindows", WA_SWITCH_WINDOWS, 0}, {NULL, 0, 0} }; static WOptionEnumeration seIconificationStyles[] = { {"Zoom", WIS_ZOOM, 0}, {"Twist", WIS_TWIST, 0}, {"Flip", WIS_FLIP, 0}, {"None", WIS_NONE, 0}, {"random", WIS_RANDOM, 0}, {NULL, 0, 0} }; static WOptionEnumeration seJustifications[] = { {"Left", WTJ_LEFT, 0}, {"Center", WTJ_CENTER, 0}, {"Right", WTJ_RIGHT, 0}, {NULL, 0, 0} }; static WOptionEnumeration seIconPositions[] = { {"blv", IY_BOTTOM | IY_LEFT | IY_VERT, 0}, {"blh", IY_BOTTOM | IY_LEFT | IY_HORIZ, 0}, {"brv", IY_BOTTOM | IY_RIGHT | IY_VERT, 0}, {"brh", IY_BOTTOM | IY_RIGHT | IY_HORIZ, 0}, {"tlv", IY_TOP | IY_LEFT | IY_VERT, 0}, {"tlh", IY_TOP | IY_LEFT | IY_HORIZ, 0}, {"trv", IY_TOP | IY_RIGHT | IY_VERT, 0}, {"trh", IY_TOP | IY_RIGHT | IY_HORIZ, 0}, {NULL, 0, 0} }; static WOptionEnumeration seMenuStyles[] = { {"normal", MS_NORMAL, 0}, {"singletexture", MS_SINGLE_TEXTURE, 0}, {"flat", MS_FLAT, 0}, {NULL, 0, 0} }; static WOptionEnumeration seDisplayPositions[] = { {"none", WD_NONE, 0}, {"center", WD_CENTER, 0}, {"top", WD_TOP, 0}, {"bottom", WD_BOTTOM, 0}, {"topleft", WD_TOPLEFT, 0}, {"topright", WD_TOPRIGHT, 0}, {"bottomleft", WD_BOTTOMLEFT, 0}, {"bottomright", WD_BOTTOMRIGHT, 0}, {NULL, 0, 0} }; static WOptionEnumeration seWorkspaceBorder[] = { {"None", WB_NONE, 0}, {"LeftRight", WB_LEFTRIGHT, 0}, {"TopBottom", WB_TOPBOTTOM, 0}, {"AllDirections", WB_ALLDIRS, 0}, {NULL, 0, 0} }; static WOptionEnumeration seDragMaximizedWindow[] = { {"Move", DRAGMAX_MOVE, 0}, {"RestoreGeometry", DRAGMAX_RESTORE, 0}, {"Unmaximize", DRAGMAX_UNMAXIMIZE, 0}, {"NoMove", DRAGMAX_NOMOVE, 0}, {NULL, 0, 0} }; /* * ALL entries in the tables below NEED to have a default value * defined, and this value needs to be correct. * * Also add the default key/value pair to WindowMaker/Defaults/WindowMaker.in */ /* these options will only affect the window manager on startup * * static defaults can't access the screen data, because it is * created after these defaults are read */ WDefaultEntry staticOptionList[] = { {"ColormapSize", "4", NULL, &wPreferences.cmap_size, getInt, NULL, NULL, NULL}, {"DisableDithering", "NO", NULL, &wPreferences.no_dithering, getBool, NULL, NULL, NULL}, {"IconSize", "64", NULL, &wPreferences.icon_size, getInt, NULL, NULL, NULL}, {"ModifierKey", "Mod1", NULL, &wPreferences.modifier_mask, getModMask, NULL, NULL, NULL}, {"FocusMode", "manual", seFocusModes, /* have a problem when switching from */ &wPreferences.focus_mode, getEnum, NULL, NULL, NULL}, /* manual to sloppy without restart */ {"NewStyle", "new", seTitlebarModes, &wPreferences.new_style, getEnum, NULL, NULL, NULL}, {"DisableDock", "NO", (void *)WM_DOCK, NULL, getBool, setIfDockPresent, NULL, NULL}, {"DisableClip", "NO", (void *)WM_CLIP, NULL, getBool, setIfDockPresent, NULL, NULL}, {"DisableDrawers", "NO", (void *)WM_DRAWER, NULL, getBool, setIfDockPresent, NULL, NULL}, {"ClipMergedInDock", "NO", NULL, NULL, getBool, setClipMergedInDock, NULL, NULL}, {"DisableMiniwindows", "NO", NULL, &wPreferences.disable_miniwindows, getBool, NULL, NULL, NULL}, {"EnableWorkspacePager", "NO", NULL, &wPreferences.enable_workspace_pager, getBool, NULL, NULL, NULL}, - {"SwitchPanelIconSize", "48", NULL, + {"SwitchPanelIconSize", "64", NULL, &wPreferences.switch_panel_icon_size, getInt, NULL, NULL, NULL}, }; #define NUM2STRING_(x) #x #define NUM2STRING(x) NUM2STRING_(x) WDefaultEntry optionList[] = { /* dynamic options */ {"IconPosition", "blh", seIconPositions, &wPreferences.icon_yard, getEnum, setIconPosition, NULL, NULL}, {"IconificationStyle", "Zoom", seIconificationStyles, &wPreferences.iconification_style, getEnum, NULL, NULL, NULL}, {"EnforceIconMargin", "NO", NULL, &wPreferences.enforce_icon_margin, getBool, NULL, NULL, NULL}, {"DisableWSMouseActions", "NO", NULL, &wPreferences.disable_root_mouse, getBool, NULL, NULL, NULL}, {"MouseLeftButtonAction", "SelectWindows", seMouseButtonActions, &wPreferences.mouse_button1, getEnum, NULL, NULL, NULL}, {"MouseMiddleButtonAction", "OpenWindowListMenu", seMouseButtonActions, &wPreferences.mouse_button2, getEnum, NULL, NULL, NULL}, {"MouseRightButtonAction", "OpenApplicationsMenu", seMouseButtonActions, &wPreferences.mouse_button3, getEnum, NULL, NULL, NULL}, {"MouseBackwardButtonAction", "None", seMouseButtonActions, &wPreferences.mouse_button8, getEnum, NULL, NULL, NULL}, {"MouseForwardButtonAction", "None", seMouseButtonActions, &wPreferences.mouse_button9, getEnum, NULL, NULL, NULL}, {"MouseWheelAction", "None", seMouseWheelActions, &wPreferences.mouse_wheel_scroll, getEnum, NULL, NULL, NULL}, {"MouseWheelTiltAction", "None", seMouseWheelActions, &wPreferences.mouse_wheel_tilt, getEnum, NULL, NULL, NULL}, {"PixmapPath", DEF_PIXMAP_PATHS, NULL, &wPreferences.pixmap_path, getPathList, NULL, NULL, NULL}, {"IconPath", DEF_ICON_PATHS, NULL, &wPreferences.icon_path, getPathList, NULL, NULL, NULL}, {"ColormapMode", "auto", seColormapModes, &wPreferences.colormap_mode, getEnum, NULL, NULL, NULL}, {"AutoFocus", "YES", NULL, &wPreferences.auto_focus, getBool, NULL, NULL, NULL}, {"RaiseDelay", "0", NULL, &wPreferences.raise_delay, getInt, NULL, NULL, NULL}, {"CirculateRaise", "NO", NULL, &wPreferences.circ_raise, getBool, NULL, NULL, NULL}, {"Superfluous", "YES", NULL, &wPreferences.superfluous, getBool, NULL, NULL, NULL}, {"AdvanceToNewWorkspace", "NO", NULL, &wPreferences.ws_advance, getBool, NULL, NULL, NULL}, {"CycleWorkspaces", "NO", NULL, &wPreferences.ws_cycle, getBool, NULL, NULL, NULL}, {"WorkspaceNameDisplayPosition", "center", seDisplayPositions, &wPreferences.workspace_name_display_position, getEnum, NULL, NULL, NULL}, {"WorkspaceBorder", "None", seWorkspaceBorder, &wPreferences.workspace_border_position, getEnum, updateUsableArea, NULL, NULL}, {"WorkspaceBorderSize", "0", NULL, &wPreferences.workspace_border_size, getInt, updateUsableArea, NULL, NULL}, {"StickyIcons", "NO", NULL, &wPreferences.sticky_icons, getBool, setStickyIcons, NULL, NULL}, {"SaveSessionOnExit", "NO", NULL, &wPreferences.save_session_on_exit, getBool, NULL, NULL, NULL}, {"WrapMenus", "NO", NULL, &wPreferences.wrap_menus, getBool, NULL, NULL, NULL}, {"ScrollableMenus", "YES", NULL, &wPreferences.scrollable_menus, getBool, NULL, NULL, NULL}, {"MenuScrollSpeed", "fast", seSpeeds, &wPreferences.menu_scroll_speed, getEnum, NULL, NULL, NULL}, {"IconSlideSpeed", "fast", seSpeeds, &wPreferences.icon_slide_speed, getEnum, NULL, NULL, NULL}, {"ShadeSpeed", "fast", seSpeeds, &wPreferences.shade_speed, getEnum, NULL, NULL, NULL}, {"BounceAppIconsWhenUrgent", "YES", NULL, &wPreferences.bounce_appicons_when_urgent, getBool, NULL, NULL, NULL}, {"RaiseAppIconsWhenBouncing", "NO", NULL, &wPreferences.raise_appicons_when_bouncing, getBool, NULL, NULL, NULL}, {"DoNotMakeAppIconsBounce", "NO", NULL, &wPreferences.do_not_make_appicons_bounce, getBool, NULL, NULL, NULL}, {"DoubleClickTime", "250", (void *)&wPreferences.dblclick_time, &wPreferences.dblclick_time, getInt, setDoubleClick, NULL, NULL}, {"ClipAutoraiseDelay", "600", NULL, &wPreferences.clip_auto_raise_delay, getInt, NULL, NULL, NULL}, {"ClipAutolowerDelay", "1000", NULL, &wPreferences.clip_auto_lower_delay, getInt, NULL, NULL, NULL}, {"ClipAutoexpandDelay", "600", NULL, &wPreferences.clip_auto_expand_delay, getInt, NULL, NULL, NULL}, {"ClipAutocollapseDelay", "1000", NULL, &wPreferences.clip_auto_collapse_delay, getInt, NULL, NULL, NULL}, {"WrapAppiconsInDock", "YES", NULL, NULL, getBool, setWrapAppiconsInDock, NULL, NULL}, {"AlignSubmenus", "NO", NULL, &wPreferences.align_menus, getBool, NULL, NULL, NULL}, {"ViKeyMenus", "NO", NULL, &wPreferences.vi_key_menus, getBool, NULL, NULL, NULL}, {"OpenTransientOnOwnerWorkspace", "NO", NULL, &wPreferences.open_transients_with_parent, getBool, NULL, NULL, NULL}, {"WindowPlacement", "auto", sePlacements, &wPreferences.window_placement, getEnum, NULL, NULL, NULL}, {"IgnoreFocusClick", "NO", NULL, &wPreferences.ignore_focus_click, getBool, NULL, NULL, NULL}, {"UseSaveUnders", "NO", NULL, &wPreferences.use_saveunders, getBool, NULL, NULL, NULL}, {"OpaqueMove", "YES", NULL, &wPreferences.opaque_move, getBool, NULL, NULL, NULL}, {"OpaqueResize", "NO", NULL, &wPreferences.opaque_resize, getBool, NULL, NULL, NULL}, {"OpaqueMoveResizeKeyboard", "NO", NULL, &wPreferences.opaque_move_resize_keyboard, getBool, NULL, NULL, NULL}, {"DisableAnimations", "NO", NULL, &wPreferences.no_animations, getBool, NULL, NULL, NULL}, {"DontLinkWorkspaces", "YES", NULL, &wPreferences.no_autowrap, getBool, NULL, NULL, NULL}, {"WindowSnapping", "NO", NULL, &wPreferences.window_snapping, getBool, NULL, NULL, NULL}, {"SnapEdgeDetect", "1", NULL, &wPreferences.snap_edge_detect, getInt, NULL, NULL, NULL}, {"SnapCornerDetect", "10", NULL, &wPreferences.snap_corner_detect, getInt, NULL, NULL, NULL}, {"SnapToTopMaximizesFullscreen", "NO", NULL, &wPreferences.snap_to_top_maximizes_fullscreen, getBool, NULL, NULL, NULL}, {"DragMaximizedWindow", "Move", seDragMaximizedWindow, &wPreferences.drag_maximized_window, getEnum, NULL, NULL, NULL}, {"MoveHalfMaximizedWindowsBetweenScreens", "NO", NULL, &wPreferences.move_half_max_between_heads, getBool, NULL, NULL, NULL}, {"AlternativeHalfMaximized", "NO", NULL, &wPreferences.alt_half_maximize, getBool, NULL, NULL, NULL}, {"PointerWithHalfMaxWindows", "NO", NULL, &wPreferences.pointer_with_half_max_windows, getBool, NULL, NULL, NULL}, {"HighlightActiveApp", "YES", NULL, &wPreferences.highlight_active_app, getBool, NULL, NULL, NULL}, {"AutoArrangeIcons", "NO", NULL, &wPreferences.auto_arrange_icons, getBool, NULL, NULL, NULL}, {"NoWindowOverDock", "NO", NULL, &wPreferences.no_window_over_dock, getBool, updateUsableArea, NULL, NULL}, {"NoWindowOverIcons", "NO", NULL, &wPreferences.no_window_over_icons, getBool, updateUsableArea, NULL, NULL}, {"WindowPlaceOrigin", "(64, 0)", NULL, &wPreferences.window_place_origin, getCoord, NULL, NULL, NULL}, {"ResizeDisplay", "center", seGeomDisplays, &wPreferences.size_display, getEnum, NULL, NULL, NULL}, {"MoveDisplay", "floating", seGeomDisplays, &wPreferences.move_display, getEnum, NULL, NULL, NULL}, {"DontConfirmKill", "NO", NULL, &wPreferences.dont_confirm_kill, getBool, NULL, NULL, NULL}, {"WindowTitleBalloons", "YES", NULL, &wPreferences.window_balloon, getBool, NULL, NULL, NULL}, {"MiniwindowTitleBalloons", "NO", NULL, &wPreferences.miniwin_title_balloon, getBool, NULL, NULL, NULL}, {"MiniwindowPreviewBalloons", "NO", NULL, &wPreferences.miniwin_preview_balloon, getBool, NULL, NULL, NULL}, {"AppIconBalloons", "NO", NULL, &wPreferences.appicon_balloon, getBool, NULL, NULL, NULL}, {"HelpBalloons", "NO", NULL, &wPreferences.help_balloon, getBool, NULL, NULL, NULL}, {"EdgeResistance", "30", NULL, &wPreferences.edge_resistance, getInt, NULL, NULL, NULL}, {"ResizeIncrement", "0", NULL, &wPreferences.resize_increment, getInt, NULL, NULL, NULL}, {"Attraction", "NO", NULL, &wPreferences.attract, getBool, NULL, NULL, NULL}, {"DisableBlinking", "NO", NULL, &wPreferences.dont_blink, getBool, NULL, NULL, NULL}, {"SingleClickLaunch", "NO", NULL, &wPreferences.single_click, getBool, NULL, NULL, NULL}, {"StrictWindozeCycle", "YES", NULL, &wPreferences.strict_windoze_cycle, getBool, NULL, NULL, NULL}, {"SwitchPanelOnlyOpen", "NO", NULL, &wPreferences.panel_only_open, getBool, NULL, NULL, NULL}, {"MiniPreviewSize", "128", NULL, &wPreferences.minipreview_size, getInt, NULL, NULL, NULL}, {"IgnoreGtkHints", "NO", NULL, &wPreferences.ignore_gtk_decoration_hints, getBool, NULL, NULL, NULL}, /* style options */ {"MenuStyle", "normal", seMenuStyles, &wPreferences.menu_style, getEnum, setMenuStyle, NULL, NULL}, {"WidgetColor", "(solid, gray)", NULL, NULL, getTexture, setWidgetColor, NULL, NULL}, {"WorkspaceSpecificBack", "()", NULL, NULL, getWSSpecificBackground, setWorkspaceSpecificBack, NULL, NULL}, /* WorkspaceBack must come after WorkspaceSpecificBack or * WorkspaceBack won't know WorkspaceSpecificBack was also * specified and 2 copies of wmsetbg will be launched */ {"WorkspaceBack", "(solid, \"rgb:50/50/75\")", NULL, NULL, getWSBackground, setWorkspaceBack, NULL, NULL}, {"SmoothWorkspaceBack", "NO", NULL, NULL, getBool, NULL, NULL, NULL}, {"IconBack", "(dgradient, \"rgb:a6/a6/b6\", \"rgb:51/55/61\")", NULL, NULL, getTexture, setIconTile, NULL, NULL}, {"TitleJustify", "center", seJustifications, &wPreferences.title_justification, getEnum, setJustify, NULL, NULL}, {"WindowTitleFont", DEF_TITLE_FONT, NULL, NULL, getFont, setWinTitleFont, NULL, NULL}, {"WindowTitleExtendSpace", DEF_WINDOW_TITLE_EXTEND_SPACE, NULL, &wPreferences.window_title_clearance, getInt, setClearance, NULL, NULL}, {"WindowTitleMinHeight", "0", NULL, &wPreferences.window_title_min_height, getInt, setClearance, NULL, NULL}, {"WindowTitleMaxHeight", NUM2STRING(INT_MAX), NULL, &wPreferences.window_title_max_height, getInt, setClearance, NULL, NULL}, {"MenuTitleExtendSpace", DEF_MENU_TITLE_EXTEND_SPACE, NULL, &wPreferences.menu_title_clearance, getInt, setClearance, NULL, NULL}, {"MenuTitleMinHeight", "0", NULL, &wPreferences.menu_title_min_height, getInt, setClearance, NULL, NULL}, {"MenuTitleMaxHeight", NUM2STRING(INT_MAX), NULL, &wPreferences.menu_title_max_height, getInt, setClearance, NULL, NULL}, {"MenuTextExtendSpace", DEF_MENU_TEXT_EXTEND_SPACE, NULL, &wPreferences.menu_text_clearance, getInt, setClearance, NULL, NULL}, {"MenuTitleFont", DEF_MENU_TITLE_FONT, NULL, NULL, getFont, setMenuTitleFont, NULL, NULL}, {"MenuTextFont", DEF_MENU_ENTRY_FONT, NULL, NULL, getFont, setMenuTextFont, NULL, NULL}, {"IconTitleFont", DEF_ICON_TITLE_FONT, NULL, NULL, getFont, setIconTitleFont, NULL, NULL}, {"ClipTitleFont", DEF_CLIP_TITLE_FONT, NULL, NULL, getFont, setClipTitleFont, NULL, NULL}, {"ShowClipTitle", "YES", NULL, &wPreferences.show_clip_title, getBool, NULL, NULL, NULL}, {"LargeDisplayFont", DEF_WORKSPACE_NAME_FONT, NULL, NULL, getFont, setLargeDisplayFont, NULL, NULL}, {"HighlightColor", "white", NULL, NULL, getColor, setHightlight, NULL, NULL}, {"HighlightTextColor", "black", NULL, NULL, getColor, setHightlightText, NULL, NULL}, {"ClipTitleColor", "black", (void *)CLIP_NORMAL, NULL, getColor, setClipTitleColor, NULL, NULL}, {"CClipTitleColor", "\"rgb:61/61/61\"", (void *)CLIP_COLLAPSED, NULL, getColor, setClipTitleColor, NULL, NULL}, {"FTitleColor", "white", (void *)WS_FOCUSED, NULL, getColor, setWTitleColor, NULL, NULL}, {"PTitleColor", "white", (void *)WS_PFOCUSED, NULL, getColor, setWTitleColor, NULL, NULL}, {"UTitleColor", "black", (void *)WS_UNFOCUSED, NULL, getColor, setWTitleColor, NULL, NULL}, {"FTitleBack", "(solid, black)", NULL, NULL, getTexture, setFTitleBack, NULL, NULL}, {"PTitleBack", "(solid, gray40)", NULL, NULL, getTexture, setPTitleBack, NULL, NULL}, {"UTitleBack", "(solid, \"rgb:aa/aa/aa\")", NULL, NULL, getTexture, setUTitleBack, NULL, NULL}, {"ResizebarBack", "(solid, \"rgb:aa/aa/aa\")", NULL, NULL, getTexture, setResizebarBack, NULL, NULL}, {"MenuTitleColor", "white", NULL, NULL, getColor, setMenuTitleColor, NULL, NULL}, {"MenuTextColor", "black", NULL, NULL, getColor, setMenuTextColor, NULL, NULL}, {"MenuDisabledColor", "gray50", NULL, NULL, getColor, setMenuDisabledColor, NULL, NULL}, {"MenuTitleBack", "(solid, black)", NULL, NULL, getTexture, setMenuTitleBack, NULL, NULL}, {"MenuTextBack", "(solid, \"rgb:aa/aa/aa\")", NULL, NULL, getTexture, setMenuTextBack, NULL, NULL}, {"IconTitleColor", "white", NULL, NULL, getColor, setIconTitleColor, NULL, NULL}, {"IconTitleBack", "black", NULL, NULL, getColor, setIconTitleBack, NULL, NULL}, {"SwitchPanelImages", "(swtile.png, swback.png, 30, 40)", &wPreferences, NULL, getPropList, setSwPOptions, NULL, NULL}, {"ModifierKeyLabels", "(\"Shift+\", \"Control+\", \"Mod1+\", \"Mod2+\", \"Mod3+\", \"Mod4+\", \"Mod5+\")", &wPreferences, NULL, getPropList, setModifierKeyLabels, NULL, NULL}, {"FrameBorderWidth", "1", NULL, NULL, getInt, setFrameBorderWidth, NULL, NULL}, {"FrameBorderColor", "black", NULL, NULL, getColor, setFrameBorderColor, NULL, NULL}, {"FrameFocusedBorderColor", "black", NULL, NULL, getColor, setFrameFocusedBorderColor, NULL, NULL}, {"FrameSelectedBorderColor", "white", NULL, NULL, getColor, setFrameSelectedBorderColor, NULL, NULL}, {"WorkspaceMapBack", "(solid, black)", NULL, NULL, getTexture, setWorkspaceMapBackground, NULL, NULL}, /* keybindings */ {"RootMenuKey", "F12", (void *)WKBD_ROOTMENU, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowListKey", "F11", (void *)WKBD_WINDOWLIST, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowMenuKey", "Control+Escape", (void *)WKBD_WINDOWMENU, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"DockRaiseLowerKey", "None", (void*)WKBD_DOCKRAISELOWER, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"ClipRaiseLowerKey", "None", (void *)WKBD_CLIPRAISELOWER, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MiniaturizeKey", "Mod1+M", (void *)WKBD_MINIATURIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MinimizeAllKey", "None", (void *)WKBD_MINIMIZEALL, NULL, getKeybind, setKeyGrab, NULL, NULL }, {"HideKey", "Mod1+H", (void *)WKBD_HIDE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"HideOthersKey", "None", (void *)WKBD_HIDE_OTHERS, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveResizeKey", "None", (void *)WKBD_MOVERESIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"CloseKey", "None", (void *)WKBD_CLOSE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MaximizeKey", "None", (void *)WKBD_MAXIMIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"VMaximizeKey", "None", (void *)WKBD_VMAXIMIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"HMaximizeKey", "None", (void *)WKBD_HMAXIMIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"LHMaximizeKey", "None", (void*)WKBD_LHMAXIMIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"RHMaximizeKey", "None", (void*)WKBD_RHMAXIMIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"THMaximizeKey", "None", (void*)WKBD_THMAXIMIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"BHMaximizeKey", "None", (void*)WKBD_BHMAXIMIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"LTCMaximizeKey", "None", (void*)WKBD_LTCMAXIMIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"RTCMaximizeKey", "None", (void*)WKBD_RTCMAXIMIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"LBCMaximizeKey", "None", (void*)WKBD_LBCMAXIMIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"RBCMaximizeKey", "None", (void*)WKBD_RBCMAXIMIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MaximusKey", "None", (void*)WKBD_MAXIMUS, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"KeepOnTopKey", "None", (void *)WKBD_KEEP_ON_TOP, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"KeepAtBottomKey", "None", (void *)WKBD_KEEP_AT_BOTTOM, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"OmnipresentKey", "None", (void *)WKBD_OMNIPRESENT, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"RaiseKey", "Mod1+Up", (void *)WKBD_RAISE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"LowerKey", "Mod1+Down", (void *)WKBD_LOWER, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"RaiseLowerKey", "None", (void *)WKBD_RAISELOWER, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"ShadeKey", "None", (void *)WKBD_SHADE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"SelectKey", "None", (void *)WKBD_SELECT, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WorkspaceMapKey", "None", (void *)WKBD_WORKSPACEMAP, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"FocusNextKey", "Mod1+Tab", (void *)WKBD_FOCUSNEXT, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"FocusPrevKey", "Mod1+Shift+Tab", (void *)WKBD_FOCUSPREV, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"GroupNextKey", "None", (void *)WKBD_GROUPNEXT, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"GroupPrevKey", "None", (void *)WKBD_GROUPPREV, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"NextWorkspaceKey", "Mod1+Control+Right", (void *)WKBD_NEXTWORKSPACE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"PrevWorkspaceKey", "Mod1+Control+Left", (void *)WKBD_PREVWORKSPACE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"LastWorkspaceKey", "None", (void *)WKBD_LASTWORKSPACE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"NextWorkspaceLayerKey", "None", (void *)WKBD_NEXTWSLAYER, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"PrevWorkspaceLayerKey", "None", (void *)WKBD_PREVWSLAYER, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"Workspace1Key", "Mod1+1", (void *)WKBD_WORKSPACE1, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"Workspace2Key", "Mod1+2", (void *)WKBD_WORKSPACE2, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"Workspace3Key", "Mod1+3", (void *)WKBD_WORKSPACE3, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"Workspace4Key", "Mod1+4", (void *)WKBD_WORKSPACE4, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"Workspace5Key", "Mod1+5", (void *)WKBD_WORKSPACE5, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"Workspace6Key", "Mod1+6", (void *)WKBD_WORKSPACE6, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"Workspace7Key", "Mod1+7", (void *)WKBD_WORKSPACE7, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"Workspace8Key", "Mod1+8", (void *)WKBD_WORKSPACE8, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"Workspace9Key", "Mod1+9", (void *)WKBD_WORKSPACE9, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"Workspace10Key", "Mod1+0", (void *)WKBD_WORKSPACE10, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToWorkspace1Key", "None", (void *)WKBD_MOVE_WORKSPACE1, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToWorkspace2Key", "None", (void *)WKBD_MOVE_WORKSPACE2, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToWorkspace3Key", "None", (void *)WKBD_MOVE_WORKSPACE3, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToWorkspace4Key", "None", (void *)WKBD_MOVE_WORKSPACE4, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToWorkspace5Key", "None", (void *)WKBD_MOVE_WORKSPACE5, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToWorkspace6Key", "None", (void *)WKBD_MOVE_WORKSPACE6, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToWorkspace7Key", "None", (void *)WKBD_MOVE_WORKSPACE7, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToWorkspace8Key", "None", (void *)WKBD_MOVE_WORKSPACE8, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToWorkspace9Key", "None", (void *)WKBD_MOVE_WORKSPACE9, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToWorkspace10Key", "None", (void *)WKBD_MOVE_WORKSPACE10, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToNextWorkspaceKey", "None", (void *)WKBD_MOVE_NEXTWORKSPACE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToPrevWorkspaceKey", "None", (void *)WKBD_MOVE_PREVWORKSPACE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToLastWorkspaceKey", "None", (void *)WKBD_MOVE_LASTWORKSPACE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToNextWorkspaceLayerKey", "None", (void *)WKBD_MOVE_NEXTWSLAYER, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToPrevWorkspaceLayerKey", "None", (void *)WKBD_MOVE_PREVWSLAYER, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowShortcut1Key", "None", (void *)WKBD_WINDOW1, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowShortcut2Key", "None", (void *)WKBD_WINDOW2, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowShortcut3Key", "None", (void *)WKBD_WINDOW3, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowShortcut4Key", "None", (void *)WKBD_WINDOW4, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowShortcut5Key", "None", (void *)WKBD_WINDOW5, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowShortcut6Key", "None", (void *)WKBD_WINDOW6, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowShortcut7Key", "None", (void *)WKBD_WINDOW7, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowShortcut8Key", "None", (void *)WKBD_WINDOW8, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowShortcut9Key", "None", (void *)WKBD_WINDOW9, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowShortcut10Key", "None", (void *)WKBD_WINDOW10, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveTo12to6Head", "None", (void *)WKBD_MOVE_12_TO_6_HEAD, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveTo6to12Head", "None", (void *)WKBD_MOVE_6_TO_12_HEAD, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowRelaunchKey", "None", (void *)WKBD_RELAUNCH, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"ScreenSwitchKey", "None", (void *)WKBD_SWITCH_SCREEN, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"RunKey", "None", (void *)WKBD_RUN, NULL, getKeybind, setKeyGrab, NULL, NULL}, #ifdef KEEP_XKB_LOCK_STATUS {"ToggleKbdModeKey", "None", (void *)WKBD_TOGGLE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"KbdModeLock", "NO", NULL, &wPreferences.modelock, getBool, NULL, NULL, NULL}, #endif /* KEEP_XKB_LOCK_STATUS */ {"NormalCursor", "(builtin, left_ptr)", (void *)WCUR_ROOT, NULL, getCursor, setCursor, NULL, NULL}, {"ArrowCursor", "(builtin, top_left_arrow)", (void *)WCUR_ARROW, NULL, getCursor, setCursor, NULL, NULL}, {"MoveCursor", "(builtin, fleur)", (void *)WCUR_MOVE, NULL, getCursor, setCursor, NULL, NULL}, {"ResizeCursor", "(builtin, sizing)", (void *)WCUR_RESIZE, NULL, getCursor, setCursor, NULL, NULL}, {"TopLeftResizeCursor", "(builtin, top_left_corner)", (void *)WCUR_TOPLEFTRESIZE, NULL, getCursor, setCursor, NULL, NULL}, {"TopRightResizeCursor", "(builtin, top_right_corner)", (void *)WCUR_TOPRIGHTRESIZE, NULL, getCursor, setCursor, NULL, NULL}, {"BottomLeftResizeCursor", "(builtin, bottom_left_corner)", (void *)WCUR_BOTTOMLEFTRESIZE, NULL, getCursor, setCursor, NULL, NULL}, {"BottomRightResizeCursor", "(builtin, bottom_right_corner)", (void *)WCUR_BOTTOMRIGHTRESIZE, NULL, getCursor, setCursor, NULL, NULL}, {"VerticalResizeCursor", "(builtin, sb_v_double_arrow)", (void *)WCUR_VERTICALRESIZE, NULL, getCursor, setCursor, NULL, NULL}, {"HorizontalResizeCursor", "(builtin, sb_h_double_arrow)", (void *)WCUR_HORIZONRESIZE, NULL, getCursor, setCursor, NULL, NULL}, {"WaitCursor", "(builtin, watch)", (void *)WCUR_WAIT, NULL, getCursor, setCursor, NULL, NULL}, {"QuestionCursor", "(builtin, question_arrow)", (void *)WCUR_QUESTION, NULL, getCursor, setCursor, NULL, NULL}, {"TextCursor", "(builtin, xterm)", (void *)WCUR_TEXT, NULL, getCursor, setCursor, NULL, NULL}, {"SelectCursor", "(builtin, cross)", (void *)WCUR_SELECT, NULL, getCursor, setCursor, NULL, NULL}, {"DialogHistoryLines", "500", NULL, &wPreferences.history_lines, getInt, NULL, NULL, NULL}, {"CycleActiveHeadOnly", "NO", NULL, &wPreferences.cycle_active_head_only, getBool, NULL, NULL, NULL}, {"CycleIgnoreMinimized", "NO", NULL, &wPreferences.cycle_ignore_minimized, getBool, NULL, NULL, NULL} }; static void initDefaults(void) { unsigned int i; WDefaultEntry *entry; WMPLSetCaseSensitive(False); for (i = 0; i < wlengthof(optionList); i++) { entry = &optionList[i]; entry->plkey = WMCreatePLString(entry->key); if (entry->default_value) entry->plvalue = WMCreatePropListFromDescription(entry->default_value); else entry->plvalue = NULL; } for (i = 0; i < wlengthof(staticOptionList); i++) { entry = &staticOptionList[i]; entry->plkey = WMCreatePLString(entry->key); if (entry->default_value) entry->plvalue = WMCreatePropListFromDescription(entry->default_value); else entry->plvalue = NULL; } } static WMPropList *readGlobalDomain(const char *domainName, Bool requireDictionary) { WMPropList *globalDict = NULL; char path[PATH_MAX]; struct stat stbuf; snprintf(path, sizeof(path), "%s/%s", DEFSDATADIR, domainName);
roblillack/wmaker
31f16b65a33632c8345b150baa7bf79fa0a4a8c6
higher resolution images for switch panel
diff --git a/WindowMaker/Pixmaps/swback.png b/WindowMaker/Pixmaps/swback.png index cd9633a..2b6d7ef 100644 Binary files a/WindowMaker/Pixmaps/swback.png and b/WindowMaker/Pixmaps/swback.png differ diff --git a/WindowMaker/Pixmaps/swback2.png b/WindowMaker/Pixmaps/swback2.png index c4b267d..2c1503b 100644 Binary files a/WindowMaker/Pixmaps/swback2.png and b/WindowMaker/Pixmaps/swback2.png differ diff --git a/WindowMaker/Pixmaps/swtile.png b/WindowMaker/Pixmaps/swtile.png index 0b2509a..41e178f 100644 Binary files a/WindowMaker/Pixmaps/swtile.png and b/WindowMaker/Pixmaps/swtile.png differ
roblillack/wmaker
3665410377a2fbac7bfb3728eadbef0fc87b2830
make switchpanel configurable
diff --git a/NEWS b/NEWS index 8ed766f..8eaecfb 100644 --- a/NEWS +++ b/NEWS @@ -1,517 +1,526 @@ NEWS for veteran Window Maker users ----------------------------------- -- 0.95.9 +Configurable SwitchPanel +------------------------ + +SwitchPanel is now more configurable: you can configure the switch panel icon +size by setting the "SwitchPanelIconSize" option to your preferred value in +~/GNUstep/Defaults/WindowMaker. The font size used in this panel now is also +sensible to changes in the system font. + + New user configuration directory environment variable ----------------------------------------------------- In previous versions, the GNUstep directory used to store a user's Window Maker configuration files was specified by the GNUSTEP_USER_ROOT environment variable, which defaulted to ~/GNUstep. However, this environment variable was deprecated in gnustep-make v2. Therefore, it has been replaced by the WMAKER_USER_ROOT environment variable. libXmu is now an optional dependency ------------------------------------ If the library is not found, compilation work, the only limitation will arise when trying to install the standard colormap on displays which are not TrueColor. Please note that if you have the library but not the headers, configure will still stop; there is no user option to explicitly disable the library use. -- 0.95.8 Move pointer with maximized windows ----------------------------------- Implementation for moving mouse pointer within the maximized window. Mouse pointer can be now moved together with window if keyboard was used for arrange maximized windows on screen. This feature can be turned on in WPrefs.app in Expert tab by selecting "Move mouse pointer with half maximized windows.", or setting "PointerWithHalfMaxWindows" to "Yes" on ~/GNUstep/Defaults/WindowMaker file. Alternative way for traverse half-maximized windows --------------------------------------------------- For now, there could be three possible state of the window while using half-maximized feature. Unmaximized window have its state saved during that process, which was use to unmaximize it. For example, if there is a window, which is maximized on the half left side of the screen, and while requesting left-half-maximized, it become unmaximized with size and dimension restored to original state. By setting "AlternativeHalfMaximized" option to "Yes" ~/GNUstep/Defaults/WindowMaker config file (or by using WPrefs.app and option "Alternative transitions between states for half maximized windows."), there would be slightly different change in window "traverse". Given layout depicted below: ┌┬────────────────────┬┐ ├┘ ┌───────┐ ├┤ │ ├───────┤ ├┤ │ │ │ ├┤ │ │ │ ├┤ │ └───────┘ └┤ ├┬┐ │ └┴┴────────────────────┘ Window can be moved using keyboard shortcut right-half-maximize: ┌┬─────────┬──────────┬┐ ├┘ ├──────────┼┤ │ │ ├┤ │ │ ├┤ │ │ ├┤ │ │ ├┤ ├┬┐ └──────────┘│ └┴┴────────────────────┘ Further invoking right-half-maximize will do nothing. Note, that window always can be unmaximzied using appropriate keyboard shortcut or by selecting "Unmaximize" from window menu. Going to opposite direction by invoking left-half-maximize, will make the window maximized in both, vertical and horizontal directions: ┌─────────────────────┬┐ ├─────────────────────┼┤ │ ├┤ │ ├┤ │ ├┤ │ ├┤ ├┬┬───────────────────┘│ └┴┴────────────────────┘ Further invoking left-half-maximize, will make the window maximized in half left side od the screen: ┌──────────┬──────────┬┐ ├──────────┤ ├┤ │ │ ├┤ │ │ ├┤ │ │ ├┤ │ │ └┤ ├┬┬────────┘ │ └┴┴────────────────────┘ And again, further invoking left-half-maximize, will do nothing in this mode. This change affects all possible half-maximized window state also quarters. Issuing bottom-left-corner will take lower left quarter of the screen (nothing is new so far): ┌┬────────────────────┬┐ ├┘ ├┤ │ ├┤ ├──────────┐ ├┤ ├──────────┤ ├┤ │ │ └┤ ├┬┬────────┘ │ └┴┴────────────────────┘ Issuing bottom-right-corner again will change window state to bottom half maximized: ┌┬────────────────────┬┐ ├┘ ├┤ │ ├┤ ├─────────────────────┼┤ ├─────────────────────┼┤ │ ├┤ ├┬┬───────────────────┘│ └┴┴────────────────────┘ Invoking bottom-right-corner again: ┌┬────────────────────┬┐ ├┘ ├┤ │ ├┤ │ ┌──────────┼┤ │ ├──────────┼┤ │ │ ├┤ ├┬┐ └──────────┘│ └┴┴────────────────────┘ Issuing bottom-right-corner again will have no effect. Move half-maximized windows between the screens ----------------------------------------------- New option was introduced to allow change of behaviour of half-maximize windows in multiple displays environment. In such environment it is more natural that half maximized windows would travel from one screen to another. Now it is possible to make that happen by setting an option "MoveHalfMaximizedWindowsBetweenScreens" to "Yes" in ~/GNUstep/Defaults/WindowMaker config file, or by checking "Allow move half-maximized windows between multiple screens." in 'Expert User Preferences" tab in WPrefs.app. For example, given there are two screens in layout where one display is on the left and second display is on the right with window on first screen: ┌┬────────────────┬─────────────────┬┐ ├┘ ┌───────┐ │ ├┤ │ ├───────┤ │ ├┤ │ │ │ │ ├┤ │ │ │ │ ├┤ │ └───────┘ │ └┤ ├┬┐ ├┬┬┐ │ └┴┴───────────────┴┴┴┴───────────────┘ It can be right-half-maximized (using previously defined key combination), so it become: ┌┬───────┬────────┬─────────────────┬┐ ├┘ ├────────┤ ├┤ │ │ │ ├┤ │ │ │ ├┤ │ │ │ ├┤ │ │ │ └┤ ├┬┐ └────────┼┬┬┐ │ └┴┴───────────────┴┴┴┴───────────────┘ In this example there is an assumption that WindowMaker is configured, that maximized windows wont cover mini icons nor dock. Without setting new option to true, issuing another right-half-maximize will restore window dimensions and position to the original state (like on the first figure). With new option set to true it will move window to second screen like: ┌┬────────────────┬────────┬────────┬┐ ├┘ ├────────┤ ├┤ │ │ │ ├┤ │ │ │ ├┤ │ │ │ ├┤ │ │ │ └┤ ├┬┐ ├┬┬┬─────┘ │ └┴┴───────────────┴┴┴┴───────────────┘ Another activation of right-half-maxmimize: ┌┬────────────────┬────────┬────────┬┐ ├┘ │ ├────────┼┤ │ │ │ ├┤ │ │ │ ├┤ │ │ │ ├┤ │ │ │ ├┤ ├┬┐ ├┬┬┐ └────────┘│ └┴┴───────────────┴┴┴┴───────────────┘ And final activation of right-half-maxmimize: ┌┬────────────────┬───────┬─────────┬┐ ├┘ ├───────┤ ├┤ │ │ │ ├┤ │ │ │ ├┤ │ ├───────┘ ├┤ │ │ └┤ ├┬┐ ├┬┬┐ │ └┴┴───────────────┴┴┴┴───────────────┘ Where window is restored its size (but not position, since it it on different head now). Moving window in directions like left-half-maximize, top-half-maximize and bottom-half-maximize will behave in similar way depending on the layout of displays. Note, that only windows that are half-maximized vertically or horizontally can be moved to another screen due to the fact, that direction of movement of quarter-maximized windows is ambiguous. As for vertical/horizontal-maximize, since doesn't move the window but only stretch it vertically/horizontally this feature also doesn't apply. Snapping a window to the top ---------------------------- You can now choose whether snapping a window to the top edge of the screen maximizes it to the top half (the previous and default behavior) or to the full screen by setting "SnapToTopMaximizesFullscreen" to "NO" or "YES", respectively. This setting can also be changed by unchecking or checking "Snapping a window to the top maximizes it to the full screen" in the "Expert User Preferences" tab in WPrefs.app. Global defaults directory configuration --------------------------------------- You can now configure the global defaults directory, where the system WindowMaker, WMRootMenu, etc. files are stored, by running ./configure --with-defsdatadir=/path/to/defaults at build time. The previous method, which only partially worked, involved defining the GLOBAL_DEFAULTS_SUBDIR macro. This is no longer available. Note that the default location is ${sysconfdir}/WindowMaker. -- 0.95.7 Window snapping --------------- You can now "snap" a window, i.e., maximize it to a side or corner of the screen, by dragging it to that side or corner. It is enabled by setting "WindowSnapping = YES" in ~/GNUstep/Defaults/WindowMaker or selecting "Maximize (snap) a window to edge or corner by dragging." under "Expert User Preferences" in WPrefs.app. Note that if "Switch workspaces while dragging windows" is selected under "Workspace Preferences" in WPrefs.app, or if "DontLinkWorkspaces = NO" in ~/GNUstep/Defaults/WindowMaker, then you may only snap a window to the top or bottom of the screen. You may set the distance (in pixels) from the edge or corner of the screen at which a window will begin snapping using "SnapEdgeDetect" and "SnapCornerDetect" in ~/GNUstep/Defaults/WindowMaker or setting "Distance from edge/corner to begin window snap." under "Expert User Preferences" in WPrefs.app. (The defaults are 1 pixel and 10 pixels, respectively). Dragging maximized windows -------------------------- You can now control the behavior when a maximized window is dragged by setting the "DragMaximizedWindow" option in ~/GNUstep/Defaults/WindowMaker or by selecting an option from the "When dragging a maximized window..." pop-up button under "Window Handling Preferences" in WPrefs.app. There are four choices: * "Move" ("...change position (normal behavior)" in WPrefs.app) is the default and traditional behavior. A maximized window is moved when dragged and remains maximized, i.e., it keeps its maximized geometry and can later be unmaximized. * "RestoreGeometry" ("...restore unmaximized geometry") is the behavior standard in desktop environments like GNOME, Cinnamon, and Unity. A maximized window is moved when dragged and is completely unmaximized, i.e., its unmaximized geometry is restored. * "Unmaximize" ("...consider the window unmaximized") causes a maximized window to be moved when dragged and remains partially maximized, i.e., it keeps its maximized geometry, but is consider to be unmaximized. In particular, it can be immediately re-maximized. * "NoMove" ("...do not move the window") prevents a maximized window from being moved when dragged. Note that, to accomodate this option in the "Window Handling Preferences" tab in WPrefs.app, the option to "Open dialogs in the same workspace as their owners" (which sets the "OpenTransientOnOwnerWorkspace" option from ~/GNUstep/Defaults/WindowMaker) has been moved to "Expert User Preferences". Mini-Previews instead of Apercus -------------------------------- Since the original name was not really clear because it is a French word that is rarely used by British people, it was decided to change it to the more usual Mini-Preview name. The setting is configurable with WPrefs in the Icon Preferences tab, the size is now expressed in pixels directly. Ignore Decoration Hints from GNOME applications ----------------------------------------------- The GNOME applications ask Window Maker to get no title bar and no resize bar to their windows by using "Hints". You can re-add them using the Attribute dialog in the Window menu, but if you are using many GNOME applications you may want to tell Window Maker to just ignore them. This is done with the new setting called "IgnoreGtkHints", which is available in the "Expert" panel in WPrefs. Cooperative Window Manager Replacement -------------------------------------- The ICCCM defines a protocol for window managers to ask to replace the currently running one; Window Maker now supports it. You can ask Window Maker to take the place of current one by running "wmaker --replace", or any other window manager can ask Window Maker to leave the place for them when started the same way. Please note that this feature must be explicitely enabled at compile time because by default it is not compiled in ("configure --enable-wmreplace"). --- 0.95.6 More image format supported --------------------------- In addition to a more complete Netpbm image formats support, WindowMaker can now load WebP images. It can also make use of the ImageMagick library to support a lot more formats, like SVG, BMP, TGA... Mini-window apercu ------------------ A small preview of window contents can be enabled from WPrefs, in Miscellaneous Ergonomic Preferences, check miniwindow apercus. Apercu size can be configured using the ApercuSize variable with $ wdwrite WindowMaker ApercuSize 4 in multiples of the icon size (in this case the apercu size will be four times the icon size). The default size is 2 (twice the icon size). Support for up to 9-buttons mouse --------------------------------- The action for the newly supported buttons can be configured from WPrefs. wmiv, an image viewer application --------------------------------- wmiv is a quick image viewer using wrlib to be run from the command line. --- 0.95.5 Support for generated menus in proplist format ---------------------------------------------- The root menu now supports a OPEN_PLMENU option to construct a submenu from the output of a command which is proplist format. This can be used e.g. in conjunction with wmmenugen like: ( "Generated PL Submenu", OPEN_PLMENU, "|| find /usr/share/applications -type f -name '*desktop' | xargs wmmenugen -parser:xdg" ) New window placements --------------------- Now it is possible to maximize windows to the top/bottom halves of the screen and also to the corners (top/bottom + left/right). The keyboard shortcuts can be configured with WPrefs. Options to configure window/menu borders ---------------------------------------- You can now configure the width and color of window and menu borders. For example, the default settings could be configured as follows: $ wdwrite WindowMaker FrameBorderWidth 1 $ wdwrite WindowMaker FrameBorderColor black $ wdwrite WindowMaker FrameSelectedBorderColor white Keyboard shortcuts to move windows between workspaces ----------------------------------------------------- You can now bind keyboard shortcuts - or use the window dropdown menus - to move windows to other workspaces. You can either move a window directly to a particular workspace or to the "next" or "previous" workspace. The new shortcuts can be configured in WPrefs. Native support for Drawers -------------------------- WindowMaker now supports drawers in the dock natively. You can add a dock by right-clicking on a docked appicon and select "Add a drawer". You can now drag appicons to this drawer. You can customize how you want your drawers to auto-expand/collapse and auto-raise/lower, or you can also completely disable them. Improved switch panel functionality ----------------------------------- The switch panel can be used to switch between windows of the same WM_CLASS, for example between all open xterms. If the switch panel is opened as normal with either the "FocusNextKey" or "FocusPrevKey" shortcut, you can switch to the next (or previous) window of the same type as the focused window with the "GroupNextKey" or "GroupPrevKey" shortcut. If the switch panel is opened with the "GroupNextKey" or "GroupPrevKey" shortcut, it will show only windows of the same type as the window which was focused at the time the panel was opened, and no difference will be seen between the two types of window selection shortcut. The new shortcuts can be configured in WPrefs, where they are described as allowing switching between windows of the same group. To maintain consistency with other popular operating systems, the switch panel is now configured so that it no longer automatically closes when the shift key is pressed and released. To configure the switch panel so that it does close on release of the shift key, which was the traditional Window Maker behavior, run the following command: $ wdwrite WindowMaker StrictWindozeCycling NO If you find yourself regularly opening the switch panel just to visualize open windows, you can run the following command to force the first "FocusNextKey" or similar shortcut to open the panel without switching to a new window. $ wdwrite WindowMaker SwitchPanelOnlyOpen YES --- 0.95.4 New window placement strategy ----------------------------- Among the window placement algorithms has arrived the "center" placement to get new windows appear at the center of the screen (unless application explicitly specify a position, of course). Removed dependency to CPP ------------------------- The menu files used to be pre-processed with CPP, which can be a problem because modern system do not install dev tools by default, and some compilers do not provide a pre-processor anyway. WindowMaker is now autonomous. --- 0.95.3 The references to the legacy path /usr/X11R6 have been removed because xorg does not use it in favor of a standard /usr layout. Similarly, the directory /etc/X11/WindowMaker is now /usr/share/WindowMaker. New application Relaunching functionality ----------------------------------------- There are now several ways to launch a new instance of an application with the same command line that was originally used to start it. 1. By selecting Launch from the application's window menu. 2. By using the "Launch new instance of application" keyboard shortcut. 3. By clicking the application's appicon with the middle button. 4. By double-clicking the application's appicon while holding Control. For example, if you have two xterms open, one started with "xterm" and one started with "xterm -rv", using the Relaunch functionality on the first xterm would run "xterm" and using it on the second would run "xterm -rv". Thus Relaunching can also be thought of as "cloning" an application. Application Relaunching works by examining the window's WM_COMMAND property and so will not work if it is not set. Options to limit the window/menu title height --------------------------------------------- You can now set the minimum and maximum titlebar heights. For example, to force all titlebars to 24 pixels execute the following commands: $ wdwrite WindowMaker WindowTitleMinHeight 24 $ wdwrite WindowMaker WindowTitleMaxHeight 24 $ wdwrite WindowMaker MenuTitleMinHeight 24 $ wdwrite WindowMaker MenuTitleMaxHeight 24 --- 0.95.2 New Resizing functionality diff --git a/src/WindowMaker.h b/src/WindowMaker.h index fb046a2..4b718ec 100644 --- a/src/WindowMaker.h +++ b/src/WindowMaker.h @@ -1,658 +1,660 @@ /* * Window Maker window manager * * Copyright (c) 1997-2003 Alfredo K. Kojima * Copyright (c) 2014 Window Maker Team * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef WINDOWMAKER_H_ #define WINDOWMAKER_H_ #include "wconfig.h" #include <assert.h> #include <limits.h> #include <WINGs/WINGs.h> /* class codes */ typedef enum { WCLASS_UNKNOWN = 0, WCLASS_WINDOW = 1, /* managed client windows */ WCLASS_MENU = 2, /* root menus */ WCLASS_APPICON = 3, WCLASS_DUMMYWINDOW = 4, /* window that holds window group leader */ WCLASS_MINIWINDOW = 5, WCLASS_DOCK_ICON = 6, WCLASS_PAGER = 7, WCLASS_TEXT_INPUT = 8, WCLASS_FRAME = 9 } WClassType; /* * generic window levels (a superset of the N*XTSTEP ones) * Applications should use levels between WMDesktopLevel and * WMScreensaverLevel anything boyond that range is allowed, * but discouraged. */ enum { WMBackLevel = INT_MIN+1, /* Very lowest level */ WMDesktopLevel = -1000, /* Lowest level of normal use */ WMSunkenLevel = -1, WMNormalLevel = 0, WMFloatingLevel = 3, WMDockLevel = 5, WMSubmenuLevel = 15, WMMainMenuLevel = 20, WMStatusLevel = 21, WMFullscreenLevel = 50, WMModalLevel = 100, WMPopUpLevel = 101, WMScreensaverLevel = 1000, WMOuterSpaceLevel = INT_MAX }; /* * WObjDescriptor will be used by the event dispatcher to * send events to a particular object through the methods in the * method table. If all objects of the same class share the * same methods, the class method table should be used, otherwise * a new method table must be created for each object. * It is also assigned to find the parent structure of a given * window (like the WWindow or WMenu for a button) */ typedef struct WObjDescriptor { void *self; /* the object that will be called */ /* event handlers */ void (*handle_expose)(struct WObjDescriptor *sender, XEvent *event); void (*handle_mousedown)(struct WObjDescriptor *sender, XEvent *event); void (*handle_enternotify)(struct WObjDescriptor *sender, XEvent *event); void (*handle_leavenotify)(struct WObjDescriptor *sender, XEvent *event); WClassType parent_type; /* type code of the parent */ void *parent; /* parent object (WWindow or WMenu) */ } WObjDescriptor; /* internal buttons */ #define WBUT_CLOSE 0 #define WBUT_BROKENCLOSE 1 #define WBUT_ICONIFY 2 #define WBUT_KILL 3 #ifdef XKB_BUTTON_HINT #define WBUT_XKBGROUP1 4 #define WBUT_XKBGROUP2 5 #define WBUT_XKBGROUP3 6 #define WBUT_XKBGROUP4 7 #define PRED_BPIXMAPS 8 /* reserved for 4 groups */ #else #define PRED_BPIXMAPS 4 /* count of WBUT icons */ #endif /* XKB_BUTTON_HINT */ /* Mouse cursors */ typedef enum { WCUR_NORMAL, WCUR_MOVE, WCUR_RESIZE, WCUR_TOPLEFTRESIZE, WCUR_TOPRIGHTRESIZE, WCUR_BOTTOMLEFTRESIZE, WCUR_BOTTOMRIGHTRESIZE, WCUR_VERTICALRESIZE, WCUR_HORIZONRESIZE, WCUR_WAIT, WCUR_ARROW, WCUR_QUESTION, WCUR_TEXT, WCUR_SELECT, WCUR_ROOT, WCUR_EMPTY, /* Count of the number of cursors defined */ WCUR_LAST } w_cursor; /* geometry displays */ #define WDIS_NEW 0 /* new style */ #define WDIS_CENTER 1 /* center of screen */ #define WDIS_TOPLEFT 2 /* top left corner of screen */ #define WDIS_FRAME_CENTER 3 /* center of the frame */ #define WDIS_NONE 4 /* keyboard input focus mode */ #define WKF_CLICK 0 #define WKF_SLOPPY 2 /* colormap change mode */ #define WCM_CLICK 0 #define WCM_POINTER 1 /* window placement mode */ #define WPM_MANUAL 0 #define WPM_CASCADE 1 #define WPM_SMART 2 #define WPM_RANDOM 3 #define WPM_AUTO 4 #define WPM_CENTER 5 /* text justification */ #define WTJ_CENTER 0 #define WTJ_LEFT 1 #define WTJ_RIGHT 2 /* iconification styles */ #define WIS_ZOOM 0 #define WIS_TWIST 1 #define WIS_FLIP 2 #define WIS_NONE 3 #define WIS_RANDOM 4 /* secret */ /* switchmenu actions */ #define ACTION_ADD 0 #define ACTION_REMOVE 1 #define ACTION_CHANGE 2 #define ACTION_CHANGE_WORKSPACE 3 #define ACTION_CHANGE_STATE 4 /* speeds */ #define SPEED_ULTRAFAST 0 #define SPEED_FAST 1 #define SPEED_MEDIUM 2 #define SPEED_SLOW 3 #define SPEED_ULTRASLOW 4 /* window states */ #define WS_FOCUSED 0 #define WS_UNFOCUSED 1 #define WS_PFOCUSED 2 /* clip title colors */ #define CLIP_NORMAL 0 #define CLIP_COLLAPSED 1 /* icon yard position */ #define IY_VERT 1 #define IY_HORIZ 0 #define IY_TOP 2 #define IY_BOTTOM 0 #define IY_RIGHT 4 #define IY_LEFT 0 /* menu styles */ #define MS_NORMAL 0 #define MS_SINGLE_TEXTURE 1 #define MS_FLAT 2 /* workspace actions */ #define WA_NONE 0 #define WA_SELECT_WINDOWS 1 #define WA_OPEN_APPMENU 2 #define WA_OPEN_WINLISTMENU 3 #define WA_SWITCH_WORKSPACES 4 #define WA_MOVE_PREVWORKSPACE 5 #define WA_MOVE_NEXTWORKSPACE 6 #define WA_SWITCH_WINDOWS 7 #define WA_MOVE_PREVWINDOW 8 #define WA_MOVE_NEXTWINDOW 9 /* workspace display position */ #define WD_NONE 0 #define WD_CENTER 1 #define WD_TOP 2 #define WD_BOTTOM 3 #define WD_TOPLEFT 4 #define WD_TOPRIGHT 5 #define WD_BOTTOMLEFT 6 #define WD_BOTTOMRIGHT 7 /* titlebar style */ #define TS_NEW 0 #define TS_OLD 1 #define TS_NEXT 2 /* workspace border position */ #define WB_NONE 0 #define WB_LEFTRIGHT 1 #define WB_TOPBOTTOM 2 #define WB_ALLDIRS (WB_LEFTRIGHT|WB_TOPBOTTOM) /* drag maximized window behaviors */ enum { DRAGMAX_MOVE, DRAGMAX_RESTORE, DRAGMAX_UNMAXIMIZE, DRAGMAX_NOMOVE }; /* program states */ typedef enum { WSTATE_NORMAL = 0, WSTATE_NEED_EXIT = 1, WSTATE_NEED_RESTART = 2, WSTATE_EXITING = 3, WSTATE_RESTARTING = 4, WSTATE_MODAL = 5, WSTATE_NEED_REREAD = 6 } wprog_state; #define WCHECK_STATE(chk_state) (w_global.program.state == (chk_state)) #define WCHANGE_STATE(nstate) {\ if (w_global.program.state == WSTATE_NORMAL \ || (nstate) != WSTATE_MODAL) \ w_global.program.state = (nstate); \ if (w_global.program.signal_state != 0) \ w_global.program.state = w_global.program.signal_state; \ } /* only call inside signal handlers, with signals blocked */ #define SIG_WCHANGE_STATE(nstate) {\ w_global.program.signal_state = (nstate); \ w_global.program.state = (nstate); \ } /* Flags for the Window Maker state when restarting/crash situations */ #define WFLAGS_NONE (0) #define WFLAGS_CRASHED (1<<0) /* notifications */ #ifdef MAINFILE #define NOTIFICATION(n) const char WN##n [] = #n #else #define NOTIFICATION(n) extern const char WN##n [] #endif NOTIFICATION(WindowAppearanceSettingsChanged); NOTIFICATION(IconAppearanceSettingsChanged); NOTIFICATION(IconTileSettingsChanged); NOTIFICATION(MenuAppearanceSettingsChanged); NOTIFICATION(MenuTitleAppearanceSettingsChanged); /* appearance settings clientdata flags */ enum { WFontSettings = 1 << 0, WTextureSettings = 1 << 1, WColorSettings = 1 << 2 }; typedef struct { int x1, y1; int x2, y2; } WArea; typedef struct WCoord { int x, y; } WCoord; extern struct WPreferences { char *pixmap_path; /* : separated list of paths to find pixmaps */ char *icon_path; /* : separated list of paths to find icons */ WMArray *fallbackWMs; /* fallback window manager list */ char *logger_shell; /* shell to log child stdi/o */ RImage *button_images; /* titlebar button images */ char smooth_workspace_back; signed char size_display; /* display type for resize geometry */ signed char move_display; /* display type for move geometry */ signed char window_placement; /* window placement mode */ signed char colormap_mode; /* colormap focus mode */ signed char focus_mode; /* window focusing mode */ char opaque_move; /* update window position during move */ char opaque_resize; /* update window position during resize */ char opaque_move_resize_keyboard; /* update window position during move,resize with keyboard */ char wrap_menus; /* wrap menus at edge of screen */ char scrollable_menus; /* let them be scrolled */ char vi_key_menus; /* use h/j/k/l to select */ char align_menus; /* align menu with their parents */ char use_saveunders; /* turn on SaveUnders for menus, icons etc. */ char no_window_over_dock; char no_window_over_icons; WCoord window_place_origin; /* Offset for windows placed on screen */ char constrain_window_size; /* don't let windows get bigger than screen */ char windows_cycling; /* windoze cycling */ char circ_raise; /* raise window after Alt-tabbing */ char ignore_focus_click; char open_transients_with_parent; /* open transient window in same workspace as parent */ signed char title_justification; /* titlebar text alignment */ int window_title_clearance; int window_title_min_height; int window_title_max_height; int menu_title_clearance; int menu_title_min_height; int menu_title_max_height; int menu_text_clearance; char multi_byte_text; #ifdef KEEP_XKB_LOCK_STATUS char modelock; #endif char no_dithering; /* use dithering or not */ char no_animations; /* enable/disable animations */ char no_autowrap; /* wrap workspace when window is moved to the edge */ char window_snapping; /* enable window snapping */ int snap_edge_detect; /* how far from edge to begin snap */ int snap_corner_detect; /* how far from corner to begin snap */ char snap_to_top_maximizes_fullscreen; char drag_maximized_window; /* behavior when a maximized window is dragged */ char move_half_max_between_heads; /* move half maximized window between available heads */ char alt_half_maximize; /* alternative half-maximize feature behavior */ char pointer_with_half_max_windows; char highlight_active_app; /* show the focused app by highlighting its icon */ char auto_arrange_icons; /* automagically arrange icons */ char icon_box_position; /* position to place icons */ signed char iconification_style; /* position to place icons */ char disable_root_mouse; /* disable button events in root window */ char auto_focus; /* focus window when it's mapped */ char *icon_back_file; /* background image for icons */ char enforce_icon_margin; /* auto-shrink icon images */ WCoord *root_menu_pos; /* initial position of the root menu*/ WCoord *app_menu_pos; WCoord *win_menu_pos; signed char icon_yard; /* aka iconbox */ int raise_delay; /* delay for autoraise. 0 is disabled */ int cmap_size; /* size of dithering colormap in colors per channel */ int icon_size; /* size of the icon */ signed char menu_style; /* menu decoration style */ signed char workspace_name_display_position; unsigned int modifier_mask; /* mask to use as kbd modifier */ char *modifier_labels[7]; /* Names of the modifiers */ unsigned int supports_tiff; /* Use tiff files */ char ws_advance; /* Create new workspace and advance */ char ws_cycle; /* Cycle existing workspaces */ char save_session_on_exit; /* automatically save session on exit */ char sticky_icons; /* If miniwindows will be onmipresent */ char dont_confirm_kill; /* do not confirm Kill application */ char disable_miniwindows; char enable_workspace_pager; char ignore_gtk_decoration_hints; char dont_blink; /* do not blink icon selection */ /* Appearance options */ char new_style; /* Use newstyle buttons */ char superfluous; /* Use superfluous things */ /* root window mouse bindings */ signed char mouse_button1; /* action for left mouse button */ signed char mouse_button2; /* action for middle mouse button */ signed char mouse_button3; /* action for right mouse button */ signed char mouse_button8; /* action for 4th button aka backward mouse button */ signed char mouse_button9; /* action for 5th button aka forward mouse button */ signed char mouse_wheel_scroll; /* action for mouse wheel scroll */ signed char mouse_wheel_tilt; /* action for mouse wheel tilt */ /* balloon text */ char window_balloon; char miniwin_title_balloon; char miniwin_preview_balloon; char appicon_balloon; char help_balloon; /* some constants */ int dblclick_time; /* double click delay time in ms */ /* animate menus */ signed char menu_scroll_speed; /* how fast menus are scrolled */ /* animate icon sliding */ signed char icon_slide_speed; /* icon slide animation speed */ /* shading animation */ signed char shade_speed; /* bouncing animation */ char bounce_appicons_when_urgent; char raise_appicons_when_bouncing; char do_not_make_appicons_bounce; int edge_resistance; int resize_increment; char attract; unsigned int workspace_border_size; /* Size in pixels of the workspace border */ char workspace_border_position; /* Where to leave a workspace border */ char single_click; /* single click to lauch applications */ int history_lines; /* history of "Run..." dialog */ char cycle_active_head_only; /* Cycle only windows on the active head */ char cycle_ignore_minimized; /* Ignore minimized windows when cycling */ char strict_windoze_cycle; /* don't close switch panel when shift is released */ char panel_only_open; /* Only open the switch panel; don't switch */ int minipreview_size; /* Size of Mini-Previews in pixels */ /* All delays here are in ms. 0 means instant auto-action. */ int clip_auto_raise_delay; /* Delay after which the clip will be raised when entered */ int clip_auto_lower_delay; /* Delay after which the clip will be lowered when leaved */ int clip_auto_expand_delay; /* Delay after which the clip will expand when entered */ int clip_auto_collapse_delay; /* Delay after which the clip will collapse when leaved */ RImage *swtileImage; RImage *swbackImage[9]; union WTexture *wsmbackTexture; char show_clip_title; struct { #ifdef USE_ICCCM_WMREPLACE unsigned int replace:1; /* replace existing window manager */ #endif unsigned int nodock:1; /* don't display the dock */ unsigned int noclip:1; /* don't display the clip */ unsigned int clip_merged_in_dock:1; /* disable clip, switch workspaces with dock */ unsigned int nodrawer:1; /* don't use drawers */ unsigned int wrap_appicons_in_dock:1; /* Whether to wrap appicons when Dock is moved up and down */ unsigned int noupdates:1; /* don't require ~/GNUstep (-static) */ unsigned int noautolaunch:1; /* don't autolaunch apps */ unsigned int norestore:1; /* don't restore session */ unsigned int restarting:2; } flags; /* internal flags */ /* Map table between w_cursor and actual X id */ Cursor cursor[WCUR_LAST]; + int switch_panel_icon_size; /* icon size in switch panel */ + } wPreferences; /****** Global Variables ******/ extern Display *dpy; extern struct wmaker_global_variables { /* Tracking of the state of the program */ struct { wprog_state state; wprog_state signal_state; } program; /* locale to use. NULL==POSIX or C */ const char *locale; /* Tracking of X events timestamps */ struct { /* ts of the last event we received */ Time last_event; /* ts on the last time we did XSetInputFocus() */ Time focus_change; } timestamp; /* Global Domains, for storing dictionaries */ struct { /* Note: you must #include <defaults.h> if you want to use them */ struct WDDomain *wmaker; struct WDDomain *window_attr; struct WDDomain *root_menu; } domain; /* Screens related */ int screen_count; /* * Ignore Workspace Change: * this variable is used to prevent workspace switch while certain * operations are ongoing. */ Bool ignore_workspace_change; /* * Process WorkspaceMap Event: * this variable is set when the Workspace Map window is being displayed, * it is mainly used to avoid re-opening another one at the same time */ Bool process_workspacemap_event; #ifdef HAVE_INOTIFY struct { int fd_event_queue; /* Inotify's queue file descriptor */ int wd_defaults; /* Watch Descriptor for the 'Defaults' configuration file */ } inotify; #endif /* definition for X Atoms */ struct { /* Window-Manager related */ struct { Atom state; Atom change_state; Atom protocols; Atom take_focus; Atom delete_window; Atom save_yourself; Atom client_leader; Atom colormap_windows; Atom colormap_notify; Atom ignore_focus_events; } wm; /* GNUStep related */ struct { Atom wm_attr; Atom wm_miniaturize_window; Atom wm_resizebar; Atom titlebar_state; } gnustep; /* Destkop-environment related */ struct { Atom gtk_object_path; } desktop; /* WindowMaker specific */ struct { Atom menu; Atom wm_protocols; Atom state; Atom wm_function; Atom noticeboard; Atom command; Atom icon_size; Atom icon_tile; } wmaker; } atom; /* X Contexts */ struct { XContext client_win; XContext app_win; XContext stack; } context; /* X Extensions */ struct { #ifdef USE_XSHAPE struct { Bool supported; int event_base; } shape; #endif #ifdef KEEP_XKB_LOCK_STATUS struct { Bool supported; int event_base; } xkb; #endif #ifdef USE_RANDR struct { Bool supported; int event_base; } randr; #endif /* * If no extension were activated, we would end up with an empty * structure, which old compilers may not appreciate, so let's * work around this with a simple: */ int dummy; } xext; /* Keyboard and shortcuts */ struct { /* * Bit-mask to hide special key modifiers which we don't want to * impact the shortcuts (typically: CapsLock, NumLock, ScrollLock) */ unsigned int modifiers_mask; } shortcut; } w_global; /****** Notifications ******/ extern const char WMNManaged[]; extern const char WMNUnmanaged[]; extern const char WMNChangedWorkspace[]; extern const char WMNChangedState[]; extern const char WMNChangedFocus[]; extern const char WMNChangedStacking[]; extern const char WMNChangedName[]; extern const char WMNWorkspaceCreated[]; extern const char WMNWorkspaceDestroyed[]; extern const char WMNWorkspaceChanged[]; extern const char WMNWorkspaceNameChanged[]; extern const char WMNResetStacking[]; #endif diff --git a/src/defaults.c b/src/defaults.c index 682f659..440376b 100644 --- a/src/defaults.c +++ b/src/defaults.c @@ -1,864 +1,866 @@ /* defaults.c - manage configuration through defaults db * * Window Maker window manager * * Copyright (c) 1997-2003 Alfredo K. Kojima * Copyright (c) 1998-2003 Dan Pascu * Copyright (c) 2014 Window Maker Team * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "wconfig.h" #include <stdio.h> #include <stdint.h> #include <stdlib.h> #include <unistd.h> #include <string.h> #include <strings.h> #include <ctype.h> #include <time.h> #include <sys/types.h> #include <sys/stat.h> #include <limits.h> #include <signal.h> #ifndef PATH_MAX #define PATH_MAX DEFAULT_PATH_MAX #endif #include <X11/Xlib.h> #include <X11/Xutil.h> #include <X11/keysym.h> #include <wraster.h> #include "WindowMaker.h" #include "framewin.h" #include "window.h" #include "texture.h" #include "screen.h" #include "resources.h" #include "defaults.h" #include "keybind.h" #include "xmodifier.h" #include "icon.h" #include "main.h" #include "actions.h" #include "dock.h" #include "workspace.h" #include "properties.h" #include "misc.h" #include "winmenu.h" #define MAX_SHORTCUT_LENGTH 32 typedef struct _WDefaultEntry WDefaultEntry; typedef int (WDECallbackConvert) (WScreen *scr, WDefaultEntry *entry, WMPropList *plvalue, void *addr, void **tdata); typedef int (WDECallbackUpdate) (WScreen *scr, WDefaultEntry *entry, void *tdata, void *extra_data); struct _WDefaultEntry { const char *key; const char *default_value; void *extra_data; void *addr; WDECallbackConvert *convert; WDECallbackUpdate *update; WMPropList *plkey; WMPropList *plvalue; /* default value */ }; /* used to map strings to integers */ typedef struct { const char *string; short value; char is_alias; } WOptionEnumeration; /* type converters */ static WDECallbackConvert getBool; static WDECallbackConvert getInt; static WDECallbackConvert getCoord; static WDECallbackConvert getPathList; static WDECallbackConvert getEnum; static WDECallbackConvert getTexture; static WDECallbackConvert getWSBackground; static WDECallbackConvert getWSSpecificBackground; static WDECallbackConvert getFont; static WDECallbackConvert getColor; static WDECallbackConvert getKeybind; static WDECallbackConvert getModMask; static WDECallbackConvert getPropList; /* value setting functions */ static WDECallbackUpdate setJustify; static WDECallbackUpdate setClearance; static WDECallbackUpdate setIfDockPresent; static WDECallbackUpdate setClipMergedInDock; static WDECallbackUpdate setWrapAppiconsInDock; static WDECallbackUpdate setStickyIcons; static WDECallbackUpdate setWidgetColor; static WDECallbackUpdate setIconTile; static WDECallbackUpdate setWinTitleFont; static WDECallbackUpdate setMenuTitleFont; static WDECallbackUpdate setMenuTextFont; static WDECallbackUpdate setIconTitleFont; static WDECallbackUpdate setIconTitleColor; static WDECallbackUpdate setIconTitleBack; static WDECallbackUpdate setFrameBorderWidth; static WDECallbackUpdate setFrameBorderColor; static WDECallbackUpdate setFrameFocusedBorderColor; static WDECallbackUpdate setFrameSelectedBorderColor; static WDECallbackUpdate setLargeDisplayFont; static WDECallbackUpdate setWTitleColor; static WDECallbackUpdate setFTitleBack; static WDECallbackUpdate setPTitleBack; static WDECallbackUpdate setUTitleBack; static WDECallbackUpdate setResizebarBack; static WDECallbackUpdate setWorkspaceBack; static WDECallbackUpdate setWorkspaceSpecificBack; static WDECallbackUpdate setMenuTitleColor; static WDECallbackUpdate setMenuTextColor; static WDECallbackUpdate setMenuDisabledColor; static WDECallbackUpdate setMenuTitleBack; static WDECallbackUpdate setMenuTextBack; static WDECallbackUpdate setHightlight; static WDECallbackUpdate setHightlightText; static WDECallbackUpdate setKeyGrab; static WDECallbackUpdate setDoubleClick; static WDECallbackUpdate setIconPosition; static WDECallbackUpdate setWorkspaceMapBackground; static WDECallbackUpdate setClipTitleFont; static WDECallbackUpdate setClipTitleColor; static WDECallbackUpdate setMenuStyle; static WDECallbackUpdate setSwPOptions; static WDECallbackUpdate updateUsableArea; static WDECallbackUpdate setModifierKeyLabels; static WDECallbackConvert getCursor; static WDECallbackUpdate setCursor; /* * Tables to convert strings to enumeration values. * Values stored are char */ /* WARNING: sum of length of all value strings must not exceed * this value */ #define TOTAL_VALUES_LENGTH 80 #define REFRESH_WINDOW_TEXTURES (1<<0) #define REFRESH_MENU_TEXTURE (1<<1) #define REFRESH_MENU_FONT (1<<2) #define REFRESH_MENU_COLOR (1<<3) #define REFRESH_MENU_TITLE_TEXTURE (1<<4) #define REFRESH_MENU_TITLE_FONT (1<<5) #define REFRESH_MENU_TITLE_COLOR (1<<6) #define REFRESH_WINDOW_TITLE_COLOR (1<<7) #define REFRESH_WINDOW_FONT (1<<8) #define REFRESH_ICON_TILE (1<<9) #define REFRESH_ICON_FONT (1<<10) #define REFRESH_BUTTON_IMAGES (1<<11) #define REFRESH_ICON_TITLE_COLOR (1<<12) #define REFRESH_ICON_TITLE_BACK (1<<13) #define REFRESH_WORKSPACE_MENU (1<<14) #define REFRESH_FRAME_BORDER REFRESH_MENU_FONT|REFRESH_WINDOW_FONT static WOptionEnumeration seFocusModes[] = { {"Manual", WKF_CLICK, 0}, {"ClickToFocus", WKF_CLICK, 1}, {"Sloppy", WKF_SLOPPY, 0}, {"SemiAuto", WKF_SLOPPY, 1}, {"Auto", WKF_SLOPPY, 1}, {NULL, 0, 0} }; static WOptionEnumeration seTitlebarModes[] = { {"new", TS_NEW, 0}, {"old", TS_OLD, 0}, {"next", TS_NEXT, 0}, {NULL, 0, 0} }; static WOptionEnumeration seColormapModes[] = { {"Manual", WCM_CLICK, 0}, {"ClickToFocus", WCM_CLICK, 1}, {"Auto", WCM_POINTER, 0}, {"FocusFollowMouse", WCM_POINTER, 1}, {NULL, 0, 0} }; static WOptionEnumeration sePlacements[] = { {"Auto", WPM_AUTO, 0}, {"Smart", WPM_SMART, 0}, {"Cascade", WPM_CASCADE, 0}, {"Random", WPM_RANDOM, 0}, {"Manual", WPM_MANUAL, 0}, {"Center", WPM_CENTER, 0}, {NULL, 0, 0} }; static WOptionEnumeration seGeomDisplays[] = { {"None", WDIS_NONE, 0}, {"Center", WDIS_CENTER, 0}, {"Corner", WDIS_TOPLEFT, 0}, {"Floating", WDIS_FRAME_CENTER, 0}, {"Line", WDIS_NEW, 0}, {NULL, 0, 0} }; static WOptionEnumeration seSpeeds[] = { {"UltraFast", SPEED_ULTRAFAST, 0}, {"Fast", SPEED_FAST, 0}, {"Medium", SPEED_MEDIUM, 0}, {"Slow", SPEED_SLOW, 0}, {"UltraSlow", SPEED_ULTRASLOW, 0}, {NULL, 0, 0} }; static WOptionEnumeration seMouseButtonActions[] = { {"None", WA_NONE, 0}, {"SelectWindows", WA_SELECT_WINDOWS, 0}, {"OpenApplicationsMenu", WA_OPEN_APPMENU, 0}, {"OpenWindowListMenu", WA_OPEN_WINLISTMENU, 0}, {"MoveToPrevWorkspace", WA_MOVE_PREVWORKSPACE, 0}, {"MoveToNextWorkspace", WA_MOVE_NEXTWORKSPACE, 0}, {"MoveToPrevWindow", WA_MOVE_PREVWINDOW, 0}, {"MoveToNextWindow", WA_MOVE_NEXTWINDOW, 0}, {NULL, 0, 0} }; static WOptionEnumeration seMouseWheelActions[] = { {"None", WA_NONE, 0}, {"SwitchWorkspaces", WA_SWITCH_WORKSPACES, 0}, {"SwitchWindows", WA_SWITCH_WINDOWS, 0}, {NULL, 0, 0} }; static WOptionEnumeration seIconificationStyles[] = { {"Zoom", WIS_ZOOM, 0}, {"Twist", WIS_TWIST, 0}, {"Flip", WIS_FLIP, 0}, {"None", WIS_NONE, 0}, {"random", WIS_RANDOM, 0}, {NULL, 0, 0} }; static WOptionEnumeration seJustifications[] = { {"Left", WTJ_LEFT, 0}, {"Center", WTJ_CENTER, 0}, {"Right", WTJ_RIGHT, 0}, {NULL, 0, 0} }; static WOptionEnumeration seIconPositions[] = { {"blv", IY_BOTTOM | IY_LEFT | IY_VERT, 0}, {"blh", IY_BOTTOM | IY_LEFT | IY_HORIZ, 0}, {"brv", IY_BOTTOM | IY_RIGHT | IY_VERT, 0}, {"brh", IY_BOTTOM | IY_RIGHT | IY_HORIZ, 0}, {"tlv", IY_TOP | IY_LEFT | IY_VERT, 0}, {"tlh", IY_TOP | IY_LEFT | IY_HORIZ, 0}, {"trv", IY_TOP | IY_RIGHT | IY_VERT, 0}, {"trh", IY_TOP | IY_RIGHT | IY_HORIZ, 0}, {NULL, 0, 0} }; static WOptionEnumeration seMenuStyles[] = { {"normal", MS_NORMAL, 0}, {"singletexture", MS_SINGLE_TEXTURE, 0}, {"flat", MS_FLAT, 0}, {NULL, 0, 0} }; static WOptionEnumeration seDisplayPositions[] = { {"none", WD_NONE, 0}, {"center", WD_CENTER, 0}, {"top", WD_TOP, 0}, {"bottom", WD_BOTTOM, 0}, {"topleft", WD_TOPLEFT, 0}, {"topright", WD_TOPRIGHT, 0}, {"bottomleft", WD_BOTTOMLEFT, 0}, {"bottomright", WD_BOTTOMRIGHT, 0}, {NULL, 0, 0} }; static WOptionEnumeration seWorkspaceBorder[] = { {"None", WB_NONE, 0}, {"LeftRight", WB_LEFTRIGHT, 0}, {"TopBottom", WB_TOPBOTTOM, 0}, {"AllDirections", WB_ALLDIRS, 0}, {NULL, 0, 0} }; static WOptionEnumeration seDragMaximizedWindow[] = { {"Move", DRAGMAX_MOVE, 0}, {"RestoreGeometry", DRAGMAX_RESTORE, 0}, {"Unmaximize", DRAGMAX_UNMAXIMIZE, 0}, {"NoMove", DRAGMAX_NOMOVE, 0}, {NULL, 0, 0} }; /* * ALL entries in the tables below NEED to have a default value * defined, and this value needs to be correct. * * Also add the default key/value pair to WindowMaker/Defaults/WindowMaker.in */ /* these options will only affect the window manager on startup * * static defaults can't access the screen data, because it is * created after these defaults are read */ WDefaultEntry staticOptionList[] = { {"ColormapSize", "4", NULL, &wPreferences.cmap_size, getInt, NULL, NULL, NULL}, {"DisableDithering", "NO", NULL, &wPreferences.no_dithering, getBool, NULL, NULL, NULL}, {"IconSize", "64", NULL, &wPreferences.icon_size, getInt, NULL, NULL, NULL}, {"ModifierKey", "Mod1", NULL, &wPreferences.modifier_mask, getModMask, NULL, NULL, NULL}, {"FocusMode", "manual", seFocusModes, /* have a problem when switching from */ &wPreferences.focus_mode, getEnum, NULL, NULL, NULL}, /* manual to sloppy without restart */ {"NewStyle", "new", seTitlebarModes, &wPreferences.new_style, getEnum, NULL, NULL, NULL}, {"DisableDock", "NO", (void *)WM_DOCK, NULL, getBool, setIfDockPresent, NULL, NULL}, {"DisableClip", "NO", (void *)WM_CLIP, NULL, getBool, setIfDockPresent, NULL, NULL}, {"DisableDrawers", "NO", (void *)WM_DRAWER, NULL, getBool, setIfDockPresent, NULL, NULL}, {"ClipMergedInDock", "NO", NULL, NULL, getBool, setClipMergedInDock, NULL, NULL}, {"DisableMiniwindows", "NO", NULL, &wPreferences.disable_miniwindows, getBool, NULL, NULL, NULL}, {"EnableWorkspacePager", "NO", NULL, - &wPreferences.enable_workspace_pager, getBool, NULL, NULL, NULL} + &wPreferences.enable_workspace_pager, getBool, NULL, NULL, NULL}, + {"SwitchPanelIconSize", "48", NULL, + &wPreferences.switch_panel_icon_size, getInt, NULL, NULL, NULL}, }; #define NUM2STRING_(x) #x #define NUM2STRING(x) NUM2STRING_(x) WDefaultEntry optionList[] = { /* dynamic options */ {"IconPosition", "blh", seIconPositions, &wPreferences.icon_yard, getEnum, setIconPosition, NULL, NULL}, {"IconificationStyle", "Zoom", seIconificationStyles, &wPreferences.iconification_style, getEnum, NULL, NULL, NULL}, {"EnforceIconMargin", "NO", NULL, &wPreferences.enforce_icon_margin, getBool, NULL, NULL, NULL}, {"DisableWSMouseActions", "NO", NULL, &wPreferences.disable_root_mouse, getBool, NULL, NULL, NULL}, {"MouseLeftButtonAction", "SelectWindows", seMouseButtonActions, &wPreferences.mouse_button1, getEnum, NULL, NULL, NULL}, {"MouseMiddleButtonAction", "OpenWindowListMenu", seMouseButtonActions, &wPreferences.mouse_button2, getEnum, NULL, NULL, NULL}, {"MouseRightButtonAction", "OpenApplicationsMenu", seMouseButtonActions, &wPreferences.mouse_button3, getEnum, NULL, NULL, NULL}, {"MouseBackwardButtonAction", "None", seMouseButtonActions, &wPreferences.mouse_button8, getEnum, NULL, NULL, NULL}, {"MouseForwardButtonAction", "None", seMouseButtonActions, &wPreferences.mouse_button9, getEnum, NULL, NULL, NULL}, {"MouseWheelAction", "None", seMouseWheelActions, &wPreferences.mouse_wheel_scroll, getEnum, NULL, NULL, NULL}, {"MouseWheelTiltAction", "None", seMouseWheelActions, &wPreferences.mouse_wheel_tilt, getEnum, NULL, NULL, NULL}, {"PixmapPath", DEF_PIXMAP_PATHS, NULL, &wPreferences.pixmap_path, getPathList, NULL, NULL, NULL}, {"IconPath", DEF_ICON_PATHS, NULL, &wPreferences.icon_path, getPathList, NULL, NULL, NULL}, {"ColormapMode", "auto", seColormapModes, &wPreferences.colormap_mode, getEnum, NULL, NULL, NULL}, {"AutoFocus", "YES", NULL, &wPreferences.auto_focus, getBool, NULL, NULL, NULL}, {"RaiseDelay", "0", NULL, &wPreferences.raise_delay, getInt, NULL, NULL, NULL}, {"CirculateRaise", "NO", NULL, &wPreferences.circ_raise, getBool, NULL, NULL, NULL}, {"Superfluous", "YES", NULL, &wPreferences.superfluous, getBool, NULL, NULL, NULL}, {"AdvanceToNewWorkspace", "NO", NULL, &wPreferences.ws_advance, getBool, NULL, NULL, NULL}, {"CycleWorkspaces", "NO", NULL, &wPreferences.ws_cycle, getBool, NULL, NULL, NULL}, {"WorkspaceNameDisplayPosition", "center", seDisplayPositions, &wPreferences.workspace_name_display_position, getEnum, NULL, NULL, NULL}, {"WorkspaceBorder", "None", seWorkspaceBorder, &wPreferences.workspace_border_position, getEnum, updateUsableArea, NULL, NULL}, {"WorkspaceBorderSize", "0", NULL, &wPreferences.workspace_border_size, getInt, updateUsableArea, NULL, NULL}, {"StickyIcons", "NO", NULL, &wPreferences.sticky_icons, getBool, setStickyIcons, NULL, NULL}, {"SaveSessionOnExit", "NO", NULL, &wPreferences.save_session_on_exit, getBool, NULL, NULL, NULL}, {"WrapMenus", "NO", NULL, &wPreferences.wrap_menus, getBool, NULL, NULL, NULL}, {"ScrollableMenus", "YES", NULL, &wPreferences.scrollable_menus, getBool, NULL, NULL, NULL}, {"MenuScrollSpeed", "fast", seSpeeds, &wPreferences.menu_scroll_speed, getEnum, NULL, NULL, NULL}, {"IconSlideSpeed", "fast", seSpeeds, &wPreferences.icon_slide_speed, getEnum, NULL, NULL, NULL}, {"ShadeSpeed", "fast", seSpeeds, &wPreferences.shade_speed, getEnum, NULL, NULL, NULL}, {"BounceAppIconsWhenUrgent", "YES", NULL, &wPreferences.bounce_appicons_when_urgent, getBool, NULL, NULL, NULL}, {"RaiseAppIconsWhenBouncing", "NO", NULL, &wPreferences.raise_appicons_when_bouncing, getBool, NULL, NULL, NULL}, {"DoNotMakeAppIconsBounce", "NO", NULL, &wPreferences.do_not_make_appicons_bounce, getBool, NULL, NULL, NULL}, {"DoubleClickTime", "250", (void *)&wPreferences.dblclick_time, &wPreferences.dblclick_time, getInt, setDoubleClick, NULL, NULL}, {"ClipAutoraiseDelay", "600", NULL, &wPreferences.clip_auto_raise_delay, getInt, NULL, NULL, NULL}, {"ClipAutolowerDelay", "1000", NULL, &wPreferences.clip_auto_lower_delay, getInt, NULL, NULL, NULL}, {"ClipAutoexpandDelay", "600", NULL, &wPreferences.clip_auto_expand_delay, getInt, NULL, NULL, NULL}, {"ClipAutocollapseDelay", "1000", NULL, &wPreferences.clip_auto_collapse_delay, getInt, NULL, NULL, NULL}, {"WrapAppiconsInDock", "YES", NULL, NULL, getBool, setWrapAppiconsInDock, NULL, NULL}, {"AlignSubmenus", "NO", NULL, &wPreferences.align_menus, getBool, NULL, NULL, NULL}, {"ViKeyMenus", "NO", NULL, &wPreferences.vi_key_menus, getBool, NULL, NULL, NULL}, {"OpenTransientOnOwnerWorkspace", "NO", NULL, &wPreferences.open_transients_with_parent, getBool, NULL, NULL, NULL}, {"WindowPlacement", "auto", sePlacements, &wPreferences.window_placement, getEnum, NULL, NULL, NULL}, {"IgnoreFocusClick", "NO", NULL, &wPreferences.ignore_focus_click, getBool, NULL, NULL, NULL}, {"UseSaveUnders", "NO", NULL, &wPreferences.use_saveunders, getBool, NULL, NULL, NULL}, {"OpaqueMove", "YES", NULL, &wPreferences.opaque_move, getBool, NULL, NULL, NULL}, {"OpaqueResize", "NO", NULL, &wPreferences.opaque_resize, getBool, NULL, NULL, NULL}, {"OpaqueMoveResizeKeyboard", "NO", NULL, &wPreferences.opaque_move_resize_keyboard, getBool, NULL, NULL, NULL}, {"DisableAnimations", "NO", NULL, &wPreferences.no_animations, getBool, NULL, NULL, NULL}, {"DontLinkWorkspaces", "YES", NULL, &wPreferences.no_autowrap, getBool, NULL, NULL, NULL}, {"WindowSnapping", "NO", NULL, &wPreferences.window_snapping, getBool, NULL, NULL, NULL}, {"SnapEdgeDetect", "1", NULL, &wPreferences.snap_edge_detect, getInt, NULL, NULL, NULL}, {"SnapCornerDetect", "10", NULL, &wPreferences.snap_corner_detect, getInt, NULL, NULL, NULL}, {"SnapToTopMaximizesFullscreen", "NO", NULL, &wPreferences.snap_to_top_maximizes_fullscreen, getBool, NULL, NULL, NULL}, {"DragMaximizedWindow", "Move", seDragMaximizedWindow, &wPreferences.drag_maximized_window, getEnum, NULL, NULL, NULL}, {"MoveHalfMaximizedWindowsBetweenScreens", "NO", NULL, &wPreferences.move_half_max_between_heads, getBool, NULL, NULL, NULL}, {"AlternativeHalfMaximized", "NO", NULL, &wPreferences.alt_half_maximize, getBool, NULL, NULL, NULL}, {"PointerWithHalfMaxWindows", "NO", NULL, &wPreferences.pointer_with_half_max_windows, getBool, NULL, NULL, NULL}, {"HighlightActiveApp", "YES", NULL, &wPreferences.highlight_active_app, getBool, NULL, NULL, NULL}, {"AutoArrangeIcons", "NO", NULL, &wPreferences.auto_arrange_icons, getBool, NULL, NULL, NULL}, {"NoWindowOverDock", "NO", NULL, &wPreferences.no_window_over_dock, getBool, updateUsableArea, NULL, NULL}, {"NoWindowOverIcons", "NO", NULL, &wPreferences.no_window_over_icons, getBool, updateUsableArea, NULL, NULL}, {"WindowPlaceOrigin", "(64, 0)", NULL, &wPreferences.window_place_origin, getCoord, NULL, NULL, NULL}, {"ResizeDisplay", "center", seGeomDisplays, &wPreferences.size_display, getEnum, NULL, NULL, NULL}, {"MoveDisplay", "floating", seGeomDisplays, &wPreferences.move_display, getEnum, NULL, NULL, NULL}, {"DontConfirmKill", "NO", NULL, &wPreferences.dont_confirm_kill, getBool, NULL, NULL, NULL}, {"WindowTitleBalloons", "YES", NULL, &wPreferences.window_balloon, getBool, NULL, NULL, NULL}, {"MiniwindowTitleBalloons", "NO", NULL, &wPreferences.miniwin_title_balloon, getBool, NULL, NULL, NULL}, {"MiniwindowPreviewBalloons", "NO", NULL, &wPreferences.miniwin_preview_balloon, getBool, NULL, NULL, NULL}, {"AppIconBalloons", "NO", NULL, &wPreferences.appicon_balloon, getBool, NULL, NULL, NULL}, {"HelpBalloons", "NO", NULL, &wPreferences.help_balloon, getBool, NULL, NULL, NULL}, {"EdgeResistance", "30", NULL, &wPreferences.edge_resistance, getInt, NULL, NULL, NULL}, {"ResizeIncrement", "0", NULL, &wPreferences.resize_increment, getInt, NULL, NULL, NULL}, {"Attraction", "NO", NULL, &wPreferences.attract, getBool, NULL, NULL, NULL}, {"DisableBlinking", "NO", NULL, &wPreferences.dont_blink, getBool, NULL, NULL, NULL}, {"SingleClickLaunch", "NO", NULL, &wPreferences.single_click, getBool, NULL, NULL, NULL}, {"StrictWindozeCycle", "YES", NULL, &wPreferences.strict_windoze_cycle, getBool, NULL, NULL, NULL}, {"SwitchPanelOnlyOpen", "NO", NULL, &wPreferences.panel_only_open, getBool, NULL, NULL, NULL}, {"MiniPreviewSize", "128", NULL, &wPreferences.minipreview_size, getInt, NULL, NULL, NULL}, {"IgnoreGtkHints", "NO", NULL, &wPreferences.ignore_gtk_decoration_hints, getBool, NULL, NULL, NULL}, /* style options */ {"MenuStyle", "normal", seMenuStyles, &wPreferences.menu_style, getEnum, setMenuStyle, NULL, NULL}, {"WidgetColor", "(solid, gray)", NULL, NULL, getTexture, setWidgetColor, NULL, NULL}, {"WorkspaceSpecificBack", "()", NULL, NULL, getWSSpecificBackground, setWorkspaceSpecificBack, NULL, NULL}, /* WorkspaceBack must come after WorkspaceSpecificBack or * WorkspaceBack won't know WorkspaceSpecificBack was also * specified and 2 copies of wmsetbg will be launched */ {"WorkspaceBack", "(solid, \"rgb:50/50/75\")", NULL, NULL, getWSBackground, setWorkspaceBack, NULL, NULL}, {"SmoothWorkspaceBack", "NO", NULL, NULL, getBool, NULL, NULL, NULL}, {"IconBack", "(dgradient, \"rgb:a6/a6/b6\", \"rgb:51/55/61\")", NULL, NULL, getTexture, setIconTile, NULL, NULL}, {"TitleJustify", "center", seJustifications, &wPreferences.title_justification, getEnum, setJustify, NULL, NULL}, {"WindowTitleFont", DEF_TITLE_FONT, NULL, NULL, getFont, setWinTitleFont, NULL, NULL}, {"WindowTitleExtendSpace", DEF_WINDOW_TITLE_EXTEND_SPACE, NULL, &wPreferences.window_title_clearance, getInt, setClearance, NULL, NULL}, {"WindowTitleMinHeight", "0", NULL, &wPreferences.window_title_min_height, getInt, setClearance, NULL, NULL}, {"WindowTitleMaxHeight", NUM2STRING(INT_MAX), NULL, &wPreferences.window_title_max_height, getInt, setClearance, NULL, NULL}, {"MenuTitleExtendSpace", DEF_MENU_TITLE_EXTEND_SPACE, NULL, &wPreferences.menu_title_clearance, getInt, setClearance, NULL, NULL}, {"MenuTitleMinHeight", "0", NULL, &wPreferences.menu_title_min_height, getInt, setClearance, NULL, NULL}, {"MenuTitleMaxHeight", NUM2STRING(INT_MAX), NULL, &wPreferences.menu_title_max_height, getInt, setClearance, NULL, NULL}, {"MenuTextExtendSpace", DEF_MENU_TEXT_EXTEND_SPACE, NULL, &wPreferences.menu_text_clearance, getInt, setClearance, NULL, NULL}, {"MenuTitleFont", DEF_MENU_TITLE_FONT, NULL, NULL, getFont, setMenuTitleFont, NULL, NULL}, {"MenuTextFont", DEF_MENU_ENTRY_FONT, NULL, NULL, getFont, setMenuTextFont, NULL, NULL}, {"IconTitleFont", DEF_ICON_TITLE_FONT, NULL, NULL, getFont, setIconTitleFont, NULL, NULL}, {"ClipTitleFont", DEF_CLIP_TITLE_FONT, NULL, NULL, getFont, setClipTitleFont, NULL, NULL}, {"ShowClipTitle", "YES", NULL, &wPreferences.show_clip_title, getBool, NULL, NULL, NULL}, {"LargeDisplayFont", DEF_WORKSPACE_NAME_FONT, NULL, NULL, getFont, setLargeDisplayFont, NULL, NULL}, {"HighlightColor", "white", NULL, NULL, getColor, setHightlight, NULL, NULL}, {"HighlightTextColor", "black", NULL, NULL, getColor, setHightlightText, NULL, NULL}, {"ClipTitleColor", "black", (void *)CLIP_NORMAL, NULL, getColor, setClipTitleColor, NULL, NULL}, {"CClipTitleColor", "\"rgb:61/61/61\"", (void *)CLIP_COLLAPSED, NULL, getColor, setClipTitleColor, NULL, NULL}, {"FTitleColor", "white", (void *)WS_FOCUSED, NULL, getColor, setWTitleColor, NULL, NULL}, {"PTitleColor", "white", (void *)WS_PFOCUSED, NULL, getColor, setWTitleColor, NULL, NULL}, {"UTitleColor", "black", (void *)WS_UNFOCUSED, NULL, getColor, setWTitleColor, NULL, NULL}, {"FTitleBack", "(solid, black)", NULL, NULL, getTexture, setFTitleBack, NULL, NULL}, {"PTitleBack", "(solid, gray40)", NULL, NULL, getTexture, setPTitleBack, NULL, NULL}, {"UTitleBack", "(solid, \"rgb:aa/aa/aa\")", NULL, NULL, getTexture, setUTitleBack, NULL, NULL}, {"ResizebarBack", "(solid, \"rgb:aa/aa/aa\")", NULL, NULL, getTexture, setResizebarBack, NULL, NULL}, {"MenuTitleColor", "white", NULL, NULL, getColor, setMenuTitleColor, NULL, NULL}, {"MenuTextColor", "black", NULL, NULL, getColor, setMenuTextColor, NULL, NULL}, {"MenuDisabledColor", "gray50", NULL, NULL, getColor, setMenuDisabledColor, NULL, NULL}, {"MenuTitleBack", "(solid, black)", NULL, NULL, getTexture, setMenuTitleBack, NULL, NULL}, {"MenuTextBack", "(solid, \"rgb:aa/aa/aa\")", NULL, NULL, getTexture, setMenuTextBack, NULL, NULL}, {"IconTitleColor", "white", NULL, NULL, getColor, setIconTitleColor, NULL, NULL}, {"IconTitleBack", "black", NULL, NULL, getColor, setIconTitleBack, NULL, NULL}, {"SwitchPanelImages", "(swtile.png, swback.png, 30, 40)", &wPreferences, NULL, getPropList, setSwPOptions, NULL, NULL}, {"ModifierKeyLabels", "(\"Shift+\", \"Control+\", \"Mod1+\", \"Mod2+\", \"Mod3+\", \"Mod4+\", \"Mod5+\")", &wPreferences, NULL, getPropList, setModifierKeyLabels, NULL, NULL}, {"FrameBorderWidth", "1", NULL, NULL, getInt, setFrameBorderWidth, NULL, NULL}, {"FrameBorderColor", "black", NULL, NULL, getColor, setFrameBorderColor, NULL, NULL}, {"FrameFocusedBorderColor", "black", NULL, NULL, getColor, setFrameFocusedBorderColor, NULL, NULL}, {"FrameSelectedBorderColor", "white", NULL, NULL, getColor, setFrameSelectedBorderColor, NULL, NULL}, {"WorkspaceMapBack", "(solid, black)", NULL, NULL, getTexture, setWorkspaceMapBackground, NULL, NULL}, /* keybindings */ {"RootMenuKey", "F12", (void *)WKBD_ROOTMENU, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowListKey", "F11", (void *)WKBD_WINDOWLIST, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowMenuKey", "Control+Escape", (void *)WKBD_WINDOWMENU, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"DockRaiseLowerKey", "None", (void*)WKBD_DOCKRAISELOWER, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"ClipRaiseLowerKey", "None", (void *)WKBD_CLIPRAISELOWER, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MiniaturizeKey", "Mod1+M", (void *)WKBD_MINIATURIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MinimizeAllKey", "None", (void *)WKBD_MINIMIZEALL, NULL, getKeybind, setKeyGrab, NULL, NULL }, {"HideKey", "Mod1+H", (void *)WKBD_HIDE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"HideOthersKey", "None", (void *)WKBD_HIDE_OTHERS, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveResizeKey", "None", (void *)WKBD_MOVERESIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"CloseKey", "None", (void *)WKBD_CLOSE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MaximizeKey", "None", (void *)WKBD_MAXIMIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"VMaximizeKey", "None", (void *)WKBD_VMAXIMIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"HMaximizeKey", "None", (void *)WKBD_HMAXIMIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"LHMaximizeKey", "None", (void*)WKBD_LHMAXIMIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"RHMaximizeKey", "None", (void*)WKBD_RHMAXIMIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"THMaximizeKey", "None", (void*)WKBD_THMAXIMIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"BHMaximizeKey", "None", (void*)WKBD_BHMAXIMIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"LTCMaximizeKey", "None", (void*)WKBD_LTCMAXIMIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"RTCMaximizeKey", "None", (void*)WKBD_RTCMAXIMIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"LBCMaximizeKey", "None", (void*)WKBD_LBCMAXIMIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"RBCMaximizeKey", "None", (void*)WKBD_RBCMAXIMIZE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MaximusKey", "None", (void*)WKBD_MAXIMUS, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"KeepOnTopKey", "None", (void *)WKBD_KEEP_ON_TOP, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"KeepAtBottomKey", "None", (void *)WKBD_KEEP_AT_BOTTOM, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"OmnipresentKey", "None", (void *)WKBD_OMNIPRESENT, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"RaiseKey", "Mod1+Up", (void *)WKBD_RAISE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"LowerKey", "Mod1+Down", (void *)WKBD_LOWER, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"RaiseLowerKey", "None", (void *)WKBD_RAISELOWER, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"ShadeKey", "None", (void *)WKBD_SHADE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"SelectKey", "None", (void *)WKBD_SELECT, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WorkspaceMapKey", "None", (void *)WKBD_WORKSPACEMAP, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"FocusNextKey", "Mod1+Tab", (void *)WKBD_FOCUSNEXT, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"FocusPrevKey", "Mod1+Shift+Tab", (void *)WKBD_FOCUSPREV, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"GroupNextKey", "None", (void *)WKBD_GROUPNEXT, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"GroupPrevKey", "None", (void *)WKBD_GROUPPREV, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"NextWorkspaceKey", "Mod1+Control+Right", (void *)WKBD_NEXTWORKSPACE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"PrevWorkspaceKey", "Mod1+Control+Left", (void *)WKBD_PREVWORKSPACE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"LastWorkspaceKey", "None", (void *)WKBD_LASTWORKSPACE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"NextWorkspaceLayerKey", "None", (void *)WKBD_NEXTWSLAYER, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"PrevWorkspaceLayerKey", "None", (void *)WKBD_PREVWSLAYER, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"Workspace1Key", "Mod1+1", (void *)WKBD_WORKSPACE1, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"Workspace2Key", "Mod1+2", (void *)WKBD_WORKSPACE2, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"Workspace3Key", "Mod1+3", (void *)WKBD_WORKSPACE3, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"Workspace4Key", "Mod1+4", (void *)WKBD_WORKSPACE4, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"Workspace5Key", "Mod1+5", (void *)WKBD_WORKSPACE5, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"Workspace6Key", "Mod1+6", (void *)WKBD_WORKSPACE6, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"Workspace7Key", "Mod1+7", (void *)WKBD_WORKSPACE7, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"Workspace8Key", "Mod1+8", (void *)WKBD_WORKSPACE8, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"Workspace9Key", "Mod1+9", (void *)WKBD_WORKSPACE9, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"Workspace10Key", "Mod1+0", (void *)WKBD_WORKSPACE10, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToWorkspace1Key", "None", (void *)WKBD_MOVE_WORKSPACE1, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToWorkspace2Key", "None", (void *)WKBD_MOVE_WORKSPACE2, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToWorkspace3Key", "None", (void *)WKBD_MOVE_WORKSPACE3, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToWorkspace4Key", "None", (void *)WKBD_MOVE_WORKSPACE4, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToWorkspace5Key", "None", (void *)WKBD_MOVE_WORKSPACE5, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToWorkspace6Key", "None", (void *)WKBD_MOVE_WORKSPACE6, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToWorkspace7Key", "None", (void *)WKBD_MOVE_WORKSPACE7, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToWorkspace8Key", "None", (void *)WKBD_MOVE_WORKSPACE8, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToWorkspace9Key", "None", (void *)WKBD_MOVE_WORKSPACE9, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToWorkspace10Key", "None", (void *)WKBD_MOVE_WORKSPACE10, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToNextWorkspaceKey", "None", (void *)WKBD_MOVE_NEXTWORKSPACE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToPrevWorkspaceKey", "None", (void *)WKBD_MOVE_PREVWORKSPACE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToLastWorkspaceKey", "None", (void *)WKBD_MOVE_LASTWORKSPACE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToNextWorkspaceLayerKey", "None", (void *)WKBD_MOVE_NEXTWSLAYER, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveToPrevWorkspaceLayerKey", "None", (void *)WKBD_MOVE_PREVWSLAYER, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowShortcut1Key", "None", (void *)WKBD_WINDOW1, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowShortcut2Key", "None", (void *)WKBD_WINDOW2, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowShortcut3Key", "None", (void *)WKBD_WINDOW3, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowShortcut4Key", "None", (void *)WKBD_WINDOW4, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowShortcut5Key", "None", (void *)WKBD_WINDOW5, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowShortcut6Key", "None", (void *)WKBD_WINDOW6, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowShortcut7Key", "None", (void *)WKBD_WINDOW7, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowShortcut8Key", "None", (void *)WKBD_WINDOW8, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowShortcut9Key", "None", (void *)WKBD_WINDOW9, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowShortcut10Key", "None", (void *)WKBD_WINDOW10, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveTo12to6Head", "None", (void *)WKBD_MOVE_12_TO_6_HEAD, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"MoveTo6to12Head", "None", (void *)WKBD_MOVE_6_TO_12_HEAD, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"WindowRelaunchKey", "None", (void *)WKBD_RELAUNCH, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"ScreenSwitchKey", "None", (void *)WKBD_SWITCH_SCREEN, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"RunKey", "None", (void *)WKBD_RUN, NULL, getKeybind, setKeyGrab, NULL, NULL}, #ifdef KEEP_XKB_LOCK_STATUS {"ToggleKbdModeKey", "None", (void *)WKBD_TOGGLE, NULL, getKeybind, setKeyGrab, NULL, NULL}, {"KbdModeLock", "NO", NULL, &wPreferences.modelock, getBool, NULL, NULL, NULL}, #endif /* KEEP_XKB_LOCK_STATUS */ {"NormalCursor", "(builtin, left_ptr)", (void *)WCUR_ROOT, NULL, getCursor, setCursor, NULL, NULL}, {"ArrowCursor", "(builtin, top_left_arrow)", (void *)WCUR_ARROW, NULL, getCursor, setCursor, NULL, NULL}, {"MoveCursor", "(builtin, fleur)", (void *)WCUR_MOVE, NULL, getCursor, setCursor, NULL, NULL}, {"ResizeCursor", "(builtin, sizing)", (void *)WCUR_RESIZE, NULL, getCursor, setCursor, NULL, NULL}, {"TopLeftResizeCursor", "(builtin, top_left_corner)", (void *)WCUR_TOPLEFTRESIZE, NULL, getCursor, setCursor, NULL, NULL}, {"TopRightResizeCursor", "(builtin, top_right_corner)", (void *)WCUR_TOPRIGHTRESIZE, NULL, getCursor, setCursor, NULL, NULL}, {"BottomLeftResizeCursor", "(builtin, bottom_left_corner)", (void *)WCUR_BOTTOMLEFTRESIZE, NULL, getCursor, setCursor, NULL, NULL}, {"BottomRightResizeCursor", "(builtin, bottom_right_corner)", (void *)WCUR_BOTTOMRIGHTRESIZE, NULL, getCursor, setCursor, NULL, NULL}, {"VerticalResizeCursor", "(builtin, sb_v_double_arrow)", (void *)WCUR_VERTICALRESIZE, NULL, getCursor, setCursor, NULL, NULL}, {"HorizontalResizeCursor", "(builtin, sb_h_double_arrow)", (void *)WCUR_HORIZONRESIZE, NULL, getCursor, setCursor, NULL, NULL}, {"WaitCursor", "(builtin, watch)", (void *)WCUR_WAIT, NULL, getCursor, setCursor, NULL, NULL}, {"QuestionCursor", "(builtin, question_arrow)", (void *)WCUR_QUESTION, NULL, getCursor, setCursor, NULL, NULL}, {"TextCursor", "(builtin, xterm)", (void *)WCUR_TEXT, NULL, getCursor, setCursor, NULL, NULL}, {"SelectCursor", "(builtin, cross)", (void *)WCUR_SELECT, NULL, getCursor, setCursor, NULL, NULL}, {"DialogHistoryLines", "500", NULL, &wPreferences.history_lines, getInt, NULL, NULL, NULL}, {"CycleActiveHeadOnly", "NO", NULL, &wPreferences.cycle_active_head_only, getBool, NULL, NULL, NULL}, {"CycleIgnoreMinimized", "NO", NULL, &wPreferences.cycle_ignore_minimized, getBool, NULL, NULL, NULL} }; static void initDefaults(void) { unsigned int i; WDefaultEntry *entry; WMPLSetCaseSensitive(False); for (i = 0; i < wlengthof(optionList); i++) { entry = &optionList[i]; entry->plkey = WMCreatePLString(entry->key); if (entry->default_value) entry->plvalue = WMCreatePropListFromDescription(entry->default_value); else entry->plvalue = NULL; } for (i = 0; i < wlengthof(staticOptionList); i++) { entry = &staticOptionList[i]; entry->plkey = WMCreatePLString(entry->key); if (entry->default_value) entry->plvalue = WMCreatePropListFromDescription(entry->default_value); else entry->plvalue = NULL; } } static WMPropList *readGlobalDomain(const char *domainName, Bool requireDictionary) { WMPropList *globalDict = NULL; char path[PATH_MAX]; struct stat stbuf; snprintf(path, sizeof(path), "%s/%s", DEFSDATADIR, domainName); if (stat(path, &stbuf) >= 0) { diff --git a/src/switchpanel.c b/src/switchpanel.c index 51e6a6f..5bf84da 100644 --- a/src/switchpanel.c +++ b/src/switchpanel.c @@ -1,719 +1,731 @@ /* * Window Maker window manager * * Copyright (c) 1997-2004 Alfredo K. Kojima * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include "wconfig.h" #include <stdint.h> #include <stdlib.h> #include <string.h> #include <sys/time.h> #include "WindowMaker.h" #include "screen.h" #include "framewin.h" #include "icon.h" #include "window.h" #include "defaults.h" #include "switchpanel.h" #include "misc.h" #include "xinerama.h" #ifdef USE_XSHAPE #include <X11/extensions/shape.h> #endif struct SwitchPanel { WScreen *scr; WMWindow *win; WMFrame *iconBox; WMArray *icons; WMArray *images; WMArray *windows; WMArray *flags; RImage *bg; int current; int firstVisible; int visibleCount; WMLabel *label; RImage *tileTmp; RImage *tile; WMFont *font; WMColor *white; }; -#define BORDER_SPACE 10 -#define ICON_SIZE 48 -#define ICON_TILE_SIZE 64 -#define LABEL_HEIGHT 25 +/* these values will be updated whenever the switch panel + * is created to to match the size defined in switch_panel_icon_size + * and the selected font size */ +static short int icon_size; +static short int border_space; +static short int icon_tile_size; +static short int label_height; + #define SCREEN_BORDER_SPACING 2*20 #define ICON_SELECTED (1<<1) #define ICON_DIM (1<<2) static int canReceiveFocus(WWindow *wwin) { if (wwin->frame->workspace != wwin->screen_ptr->current_workspace) return 0; if (wPreferences.cycle_active_head_only && wGetHeadForWindow(wwin) != wGetHeadForPointerLocation(wwin->screen_ptr)) return 0; if (WFLAGP(wwin, no_focusable)) return 0; if (!wwin->flags.mapped) { if (!wwin->flags.shaded && !wwin->flags.miniaturized && !wwin->flags.hidden) return 0; else return -1; } return 1; } static Bool sameWindowClass(WWindow *wwin, WWindow *curwin) { if (!wwin->wm_class || !curwin->wm_class) return False; if (strcmp(wwin->wm_class, curwin->wm_class)) return False; return True; } static void changeImage(WSwitchPanel *panel, int idecks, int selected, Bool dim, Bool force) { WMFrame *icon = NULL; RImage *image = NULL; int flags; int desired = 0; /* This whole function is a no-op if we aren't drawing the panel */ if (!wPreferences.swtileImage) return; icon = WMGetFromArray(panel->icons, idecks); image = WMGetFromArray(panel->images, idecks); flags = (int) (uintptr_t) WMGetFromArray(panel->flags, idecks); if (selected) desired |= ICON_SELECTED; if (dim) desired |= ICON_DIM; if (flags == desired && !force) return; WMReplaceInArray(panel->flags, idecks, (void *) (uintptr_t) desired); if (!panel->bg && !panel->tile && !selected) WMSetFrameRelief(icon, WRFlat); if (image && icon) { RImage *back; int opaq = (dim) ? 75 : 255; RImage *tile; WMPoint pos; Pixmap p; if (canReceiveFocus(WMGetFromArray(panel->windows, idecks)) < 0) opaq = 50; pos = WMGetViewPosition(WMWidgetView(icon)); back = panel->tileTmp; if (panel->bg) { RCopyArea(back, panel->bg, - BORDER_SPACE + pos.x - panel->firstVisible * ICON_TILE_SIZE, - BORDER_SPACE + pos.y, back->width, back->height, 0, 0); + border_space + pos.x - panel->firstVisible * icon_tile_size, + border_space + pos.y, back->width, back->height, 0, 0); } else { RColor color; WMScreen *wscr = WMWidgetScreen(icon); color.red = 255; color.red = WMRedComponentOfColor(WMGrayColor(wscr)) >> 8; color.green = WMGreenComponentOfColor(WMGrayColor(wscr)) >> 8; color.blue = WMBlueComponentOfColor(WMGrayColor(wscr)) >> 8; RFillImage(back, &color); } if (selected) { tile = panel->tile; RCombineArea(back, tile, 0, 0, tile->width, tile->height, (back->width - tile->width) / 2, (back->height - tile->height) / 2); } RCombineAreaWithOpaqueness(back, image, 0, 0, image->width, image->height, (back->width - image->width) / 2, (back->height - image->height) / 2, opaq); RConvertImage(panel->scr->rcontext, back, &p); XSetWindowBackgroundPixmap(dpy, WMWidgetXID(icon), p); XClearWindow(dpy, WMWidgetXID(icon)); XFreePixmap(dpy, p); } if (!panel->bg && !panel->tile && selected) WMSetFrameRelief(icon, WRSimple); } static void addIconForWindow(WSwitchPanel *panel, WMWidget *parent, WWindow *wwin, int x, int y) { WMFrame *icon = WMCreateFrame(parent); RImage *image = NULL; WMSetFrameRelief(icon, WRFlat); - WMResizeWidget(icon, ICON_TILE_SIZE, ICON_TILE_SIZE); + WMResizeWidget(icon, icon_tile_size, icon_tile_size); WMMoveWidget(icon, x, y); if (!WFLAGP(wwin, always_user_icon) && wwin->net_icon_image) image = RRetainImage(wwin->net_icon_image); /* get_icon_image() includes the default icon image */ if (!image) - image = get_icon_image(panel->scr, wwin->wm_instance, wwin->wm_class, ICON_TILE_SIZE); + image = get_icon_image(panel->scr, wwin->wm_instance, wwin->wm_class, icon_tile_size); /* We must resize the icon size (~64) to the switch panel icon size (~48) */ - image = wIconValidateIconSize(image, ICON_SIZE); + image = wIconValidateIconSize(image, icon_size); WMAddToArray(panel->images, image); WMAddToArray(panel->icons, icon); } static void scrollIcons(WSwitchPanel *panel, int delta) { int nfirst = panel->firstVisible + delta; int i; int count = WMGetArrayItemCount(panel->windows); Bool dim; if (count <= panel->visibleCount) return; if (nfirst < 0) nfirst = 0; else if (nfirst >= count - panel->visibleCount) nfirst = count - panel->visibleCount; if (nfirst == panel->firstVisible) return; - WMMoveWidget(panel->iconBox, -nfirst * ICON_TILE_SIZE, 0); + WMMoveWidget(panel->iconBox, -nfirst * icon_tile_size, 0); panel->firstVisible = nfirst; for (i = panel->firstVisible; i < panel->firstVisible + panel->visibleCount; i++) { if (i == panel->current) continue; dim = ((int) (uintptr_t) WMGetFromArray(panel->flags, i) & ICON_DIM); changeImage(panel, i, 0, dim, True); } } /* * 0 1 2 * 3 4 5 * 6 7 8 */ static RImage *assemblePuzzleImage(RImage **images, int width, int height) { RImage *img; RImage *tmp; int tw, th; RColor color; tw = width - images[0]->width - images[2]->width; th = height - images[0]->height - images[6]->height; if (tw <= 0 || th <= 0) return NULL; img = RCreateImage(width, height, 1); if (!img) return NULL; color.red = 0; color.green = 0; color.blue = 0; color.alpha = 255; RFillImage(img, &color); /* top */ tmp = RSmoothScaleImage(images[1], tw, images[1]->height); RCopyArea(img, tmp, 0, 0, tmp->width, tmp->height, images[0]->width, 0); RReleaseImage(tmp); /* bottom */ tmp = RSmoothScaleImage(images[7], tw, images[7]->height); RCopyArea(img, tmp, 0, 0, tmp->width, tmp->height, images[6]->width, height - images[6]->height); RReleaseImage(tmp); /* left */ tmp = RSmoothScaleImage(images[3], images[3]->width, th); RCopyArea(img, tmp, 0, 0, tmp->width, tmp->height, 0, images[0]->height); RReleaseImage(tmp); /* right */ tmp = RSmoothScaleImage(images[5], images[5]->width, th); RCopyArea(img, tmp, 0, 0, tmp->width, tmp->height, width - images[5]->width, images[2]->height); RReleaseImage(tmp); /* center */ tmp = RSmoothScaleImage(images[4], tw, th); RCopyArea(img, tmp, 0, 0, tmp->width, tmp->height, images[0]->width, images[0]->height); RReleaseImage(tmp); /* corners */ RCopyArea(img, images[0], 0, 0, images[0]->width, images[0]->height, 0, 0); RCopyArea(img, images[2], 0, 0, images[2]->width, images[2]->height, width - images[2]->width, 0); RCopyArea(img, images[6], 0, 0, images[6]->width, images[6]->height, 0, height - images[6]->height); RCopyArea(img, images[8], 0, 0, images[8]->width, images[8]->height, width - images[8]->width, height - images[8]->height); return img; } static RImage *createBackImage(int width, int height) { return assemblePuzzleImage(wPreferences.swbackImage, width, height); } static RImage *getTile(void) { RImage *stile; if (!wPreferences.swtileImage) return NULL; - stile = RScaleImage(wPreferences.swtileImage, ICON_TILE_SIZE, ICON_TILE_SIZE); + stile = RScaleImage(wPreferences.swtileImage, icon_tile_size, icon_tile_size); if (!stile) return wPreferences.swtileImage; return stile; } static void drawTitle(WSwitchPanel *panel, int idecks, const char *title) { char *ntitle; int width = WMWidgetWidth(panel->win); int x; if (title) - ntitle = ShrinkString(panel->font, title, width - 2 * BORDER_SPACE); + ntitle = ShrinkString(panel->font, title, width - 2 * border_space); else ntitle = NULL; if (panel->bg) { if (ntitle) { if (strcmp(ntitle, title) != 0) { - x = BORDER_SPACE; + x = border_space; } else { int w = WMWidthOfString(panel->font, ntitle, strlen(ntitle)); - x = BORDER_SPACE + (idecks - panel->firstVisible) * ICON_TILE_SIZE + - ICON_TILE_SIZE / 2 - w / 2; - if (x < BORDER_SPACE) - x = BORDER_SPACE; - else if (x + w > width - BORDER_SPACE) - x = width - BORDER_SPACE - w; + x = border_space + (idecks - panel->firstVisible) * icon_tile_size+ + icon_tile_size/ 2 - w / 2; + if (x < border_space) + x = border_space; + else if (x + w > width - border_space) + x = width - border_space - w; } } XClearWindow(dpy, WMWidgetXID(panel->win)); if (ntitle) WMDrawString(panel->scr->wmscreen, WMWidgetXID(panel->win), panel->white, panel->font, x, - WMWidgetHeight(panel->win) - BORDER_SPACE - LABEL_HEIGHT + + WMWidgetHeight(panel->win) - border_space - label_height + WMFontHeight(panel->font) / 2, ntitle, strlen(ntitle)); } else { if (ntitle) WMSetLabelText(panel->label, ntitle); } if (ntitle) free(ntitle); } static WMArray *makeWindowListArray(WScreen *scr, int include_unmapped, Bool class_only) { WMArray *windows = WMCreateArray(10); WWindow *wwin = scr->focused_window; while (wwin) { if ((canReceiveFocus(wwin) != 0) && (wwin->flags.mapped || wwin->flags.shaded || include_unmapped)) { if (class_only) if (!sameWindowClass(scr->focused_window, wwin)) { wwin = wwin->prev; continue; } if (!WFLAGP(wwin, skip_switchpanel)) WMAddToArray(windows, wwin); } wwin = wwin->prev; } return windows; } static WMArray *makeWindowFlagsArray(int count) { WMArray *flags = WMCreateArray(count); int i; for (i = 0; i < count; i++) WMAddToArray(flags, (void *) 0); return flags; } WSwitchPanel *wInitSwitchPanel(WScreen *scr, WWindow *curwin, Bool class_only) { + int wmScaleWidth, wmScaleHeight; + WMGetScaleBaseFromSystemFont(scr->wmscreen, &wmScaleWidth, &wmScaleHeight); + + icon_size = wPreferences.switch_panel_icon_size; + icon_tile_size = (short int)(((float)icon_size * (float)1.2) + 0.5); + border_space = WMScaleY(10); + label_height = WMScaleY(25); + WWindow *wwin; WSwitchPanel *panel = wmalloc(sizeof(WSwitchPanel)); WMFrame *viewport; int i, width, height, iconsThatFitCount, count; WMRect rect = wGetRectForHead(scr, wGetHeadForPointerLocation(scr)); panel->scr = scr; panel->windows = makeWindowListArray(scr, wPreferences.swtileImage != NULL, class_only); count = WMGetArrayItemCount(panel->windows); if (count) panel->flags = makeWindowFlagsArray(count); if (count == 0) { WMFreeArray(panel->windows); wfree(panel); return NULL; } - width = ICON_TILE_SIZE * count; + width = icon_tile_size* count; iconsThatFitCount = count; - if (width > rect.size.width) { - iconsThatFitCount = (rect.size.width - SCREEN_BORDER_SPACING) / ICON_TILE_SIZE; - width = iconsThatFitCount * ICON_TILE_SIZE; + if (width > (int)rect.size.width) { + iconsThatFitCount = (rect.size.width - SCREEN_BORDER_SPACING) / icon_tile_size; + width = iconsThatFitCount * icon_tile_size; } panel->visibleCount = iconsThatFitCount; if (!wPreferences.swtileImage) return panel; - height = LABEL_HEIGHT + ICON_TILE_SIZE; + height = label_height + icon_tile_size; - panel->tileTmp = RCreateImage(ICON_TILE_SIZE, ICON_TILE_SIZE, 1); + panel->tileTmp = RCreateImage(icon_tile_size, icon_tile_size, 1); panel->tile = getTile(); if (panel->tile && wPreferences.swbackImage[8]) - panel->bg = createBackImage(width + 2 * BORDER_SPACE, height + 2 * BORDER_SPACE); + panel->bg = createBackImage(width + 2 * border_space, height + 2 * border_space); if (!panel->tileTmp || !panel->tile) { if (panel->bg) RReleaseImage(panel->bg); panel->bg = NULL; if (panel->tile) RReleaseImage(panel->tile); panel->tile = NULL; if (panel->tileTmp) RReleaseImage(panel->tileTmp); panel->tileTmp = NULL; } panel->white = WMWhiteColor(scr->wmscreen); - panel->font = WMBoldSystemFontOfSize(scr->wmscreen, 12); + panel->font = WMBoldSystemFontOfSize(scr->wmscreen, WMScaleY(12)); panel->icons = WMCreateArray(count); panel->images = WMCreateArray(count); panel->win = WMCreateWindow(scr->wmscreen, ""); if (!panel->bg) { WMFrame *frame = WMCreateFrame(panel->win); WMColor *darkGray = WMDarkGrayColor(scr->wmscreen); WMSetFrameRelief(frame, WRSimple); WMSetViewExpandsToParent(WMWidgetView(frame), 0, 0, 0, 0); panel->label = WMCreateLabel(panel->win); - WMResizeWidget(panel->label, width, LABEL_HEIGHT); - WMMoveWidget(panel->label, BORDER_SPACE, BORDER_SPACE + ICON_TILE_SIZE + 5); + WMResizeWidget(panel->label, width, label_height); + WMMoveWidget(panel->label, border_space, border_space + icon_tile_size+ 5); WMSetLabelRelief(panel->label, WRSimple); WMSetWidgetBackgroundColor(panel->label, darkGray); WMSetLabelFont(panel->label, panel->font); WMSetLabelTextColor(panel->label, panel->white); WMReleaseColor(darkGray); height += 5; } - WMResizeWidget(panel->win, width + 2 * BORDER_SPACE, height + 2 * BORDER_SPACE); + WMResizeWidget(panel->win, width + 2 * border_space, height + 2 * border_space); viewport = WMCreateFrame(panel->win); - WMResizeWidget(viewport, width, ICON_TILE_SIZE); - WMMoveWidget(viewport, BORDER_SPACE, BORDER_SPACE); + WMResizeWidget(viewport, width, icon_tile_size); + WMMoveWidget(viewport, border_space, border_space); WMSetFrameRelief(viewport, WRFlat); panel->iconBox = WMCreateFrame(viewport); WMMoveWidget(panel->iconBox, 0, 0); - WMResizeWidget(panel->iconBox, ICON_TILE_SIZE * count, ICON_TILE_SIZE); + WMResizeWidget(panel->iconBox, icon_tile_size* count, icon_tile_size); WMSetFrameRelief(panel->iconBox, WRFlat); WM_ITERATE_ARRAY(panel->windows, wwin, i) { - addIconForWindow(panel, panel->iconBox, wwin, i * ICON_TILE_SIZE, 0); + addIconForWindow(panel, panel->iconBox, wwin, i * icon_tile_size, 0); } WMMapSubwidgets(panel->win); WMRealizeWidget(panel->win); WM_ITERATE_ARRAY(panel->windows, wwin, i) { changeImage(panel, i, 0, False, True); } if (panel->bg) { Pixmap pixmap, mask; RConvertImageMask(scr->rcontext, panel->bg, &pixmap, &mask, 250); XSetWindowBackgroundPixmap(dpy, WMWidgetXID(panel->win), pixmap); #ifdef USE_XSHAPE if (mask && w_global.xext.shape.supported) XShapeCombineMask(dpy, WMWidgetXID(panel->win), ShapeBounding, 0, 0, mask, ShapeSet); #endif if (pixmap) XFreePixmap(dpy, pixmap); if (mask) XFreePixmap(dpy, mask); } { WMPoint center; center = wGetPointToCenterRectInHead(scr, wGetHeadForPointerLocation(scr), - width + 2 * BORDER_SPACE, height + 2 * BORDER_SPACE); + width + 2 * border_space, height + 2 * border_space); WMMoveWidget(panel->win, center.x, center.y); } panel->current = WMGetFirstInArray(panel->windows, curwin); if (panel->current >= 0) changeImage(panel, panel->current, 1, False, False); WMMapWidget(panel->win); return panel; } void wSwitchPanelDestroy(WSwitchPanel *panel) { int i; RImage *image; if (panel->win) { Window info_win = panel->scr->info_window; XEvent ev; ev.xclient.type = ClientMessage; ev.xclient.message_type = w_global.atom.wm.ignore_focus_events; ev.xclient.format = 32; ev.xclient.data.l[0] = True; XSendEvent(dpy, info_win, True, EnterWindowMask, &ev); WMUnmapWidget(panel->win); ev.xclient.data.l[0] = False; XSendEvent(dpy, info_win, True, EnterWindowMask, &ev); } if (panel->images) { WM_ITERATE_ARRAY(panel->images, image, i) { if (image) RReleaseImage(image); } WMFreeArray(panel->images); } if (panel->win) WMDestroyWidget(panel->win); if (panel->icons) WMFreeArray(panel->icons); if (panel->flags) WMFreeArray(panel->flags); WMFreeArray(panel->windows); if (panel->tile) RReleaseImage(panel->tile); if (panel->tileTmp) RReleaseImage(panel->tileTmp); if (panel->bg) RReleaseImage(panel->bg); if (panel->font) WMReleaseFont(panel->font); if (panel->white) WMReleaseColor(panel->white); wfree(panel); } WWindow *wSwitchPanelSelectNext(WSwitchPanel *panel, int back, int ignore_minimized, Bool class_only) { WWindow *wwin, *curwin, *tmpwin; int count = WMGetArrayItemCount(panel->windows); int orig = panel->current; int i; Bool dim = False; if (count == 0) return NULL; if (!wPreferences.cycle_ignore_minimized) ignore_minimized = False; if (ignore_minimized && canReceiveFocus(WMGetFromArray(panel->windows, (count + panel->current) % count)) < 0) ignore_minimized = False; curwin = WMGetFromArray(panel->windows, orig); do { do { if (back) panel->current--; else panel->current++; panel->current = (count + panel->current) % count; wwin = WMGetFromArray(panel->windows, panel->current); if (!class_only) break; if (panel->current == orig) break; } while (!sameWindowClass(wwin, curwin)); } while (ignore_minimized && panel->current != orig && canReceiveFocus(wwin) < 0); WM_ITERATE_ARRAY(panel->windows, tmpwin, i) { if (i == panel->current) continue; if (!class_only || sameWindowClass(tmpwin, curwin)) changeImage(panel, i, 0, False, False); else { if (i == orig) dim = True; changeImage(panel, i, 0, True, False); } } if (panel->current < panel->firstVisible) scrollIcons(panel, panel->current - panel->firstVisible); else if (panel->current - panel->firstVisible >= panel->visibleCount) scrollIcons(panel, panel->current - panel->firstVisible - panel->visibleCount + 1); if (panel->win) { drawTitle(panel, panel->current, wwin->frame->title); if (panel->current != orig) changeImage(panel, orig, 0, dim, False); changeImage(panel, panel->current, 1, False, False); } return wwin; } WWindow *wSwitchPanelSelectFirst(WSwitchPanel *panel, int back) { WWindow *wwin; int count = WMGetArrayItemCount(panel->windows); char *title; int i; if (count == 0) return NULL; if (back) { panel->current = count - 1; scrollIcons(panel, count); } else { panel->current = 0; scrollIcons(panel, -count); } wwin = WMGetFromArray(panel->windows, panel->current); title = wwin->frame->title; if (panel->win) { for (WMArrayFirst(panel->windows, &(i)); (i) != WANotFound; WMArrayNext(panel->windows, &(i))) changeImage(panel, i, i == panel->current, False, False); drawTitle(panel, panel->current, title); } return wwin; } WWindow *wSwitchPanelHandleEvent(WSwitchPanel *panel, XEvent *event) { WMFrame *icon; int i; int focus = -1; if (!panel->win) return NULL; if (event->type == MotionNotify) { WM_ITERATE_ARRAY(panel->icons, icon, i) { if (WMWidgetXID(icon) == event->xmotion.window) { focus = i; break; } } } if (focus >= 0 && panel->current != focus) { WWindow *wwin; WM_ITERATE_ARRAY(panel->windows, wwin, i) { changeImage(panel, i, i == focus, False, False); } panel->current = focus; wwin = WMGetFromArray(panel->windows, focus); drawTitle(panel, panel->current, wwin->frame->title); return wwin; } return NULL; } Window wSwitchPanelGetWindow(WSwitchPanel *swpanel) { if (!swpanel->win) return None; return WMWidgetXID(swpanel->win); }
roblillack/wmaker
4477ae4da46a5553756d368e0fe95e6ccbf1ddda
Prefer TryExec to Exec when generating menu entries from XDG desktop files.
diff --git a/util/wmmenugen_parse_xdg.c b/util/wmmenugen_parse_xdg.c index cc5cbc6..1d8975d 100644 --- a/util/wmmenugen_parse_xdg.c +++ b/util/wmmenugen_parse_xdg.c @@ -1,652 +1,653 @@ /* * wmmenugen - Window Maker PropList menu generator * * Desktop Entry Specification parser functions * * Copyright (c) 2010. Tamas Tevesz <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ /* * http://standards.freedesktop.org/desktop-entry-spec/desktop-entry-spec-1.1.html * http://standards.freedesktop.org/menu-spec/menu-spec-1.1.html * * We will only deal with Type == "Application" entries in [Desktop Entry] * groups. Since there is no passing of file name arguments or anything of * the sort to applications from the menu, execname is determined as follows: * - If `TryExec' is present, use that; * - else use `Exec' with any switches stripped * * Only the (first, though there should not be more than one) `Main Category' * is used to place the entry in a submenu. * * Basic validation of the .desktop file is done. */ #include <sys/types.h> #include <sys/stat.h> #include <ctype.h> #include <ftw.h> #if DEBUG #include <errno.h> #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include "wmmenugen.h" /* LocaleString match levels */ enum { MATCH_DEFAULT, MATCH_LANG, MATCH_LANG_MODIFIER, MATCH_LANG_COUNTRY, MATCH_LANG_COUNTRY_MODIFIER }; typedef struct { char *Name; /* Name */ /* localestring */ int MatchLevel; /* LocaleString match type */ /* int */ char *TryExec; /* TryExec */ /* string */ char *Exec; /* Exec */ /* string */ char *Path; /* Path */ /* string */ int Flags; /* Flags */ char *Category; /* Categories (first item only) */ /* string */ } XDGMenuEntry; static void getKey(char **target, const char *line); static void getStringValue(char **target, const char *line); static void getLocalizedStringValue(char **target, const char *line, int *match_level); static int getBooleanValue(const char *line); static void getMenuHierarchyFor(char **xdgmenuspec); static int compare_matchlevel(int *current_level, const char *found_locale); static Bool xdg_to_wm(XDGMenuEntry *xdg, WMMenuEntry *wmentry); static char *parse_xdg_exec(char *exec); static void init_xdg_storage(XDGMenuEntry *xdg); static void init_wm_storage(WMMenuEntry *wm); void parse_xdg(const char *file, cb_add_menu_entry *addWMMenuEntryCallback) { FILE *fp; char buf[1024]; char *p, *tmp, *key; WMMenuEntry *wm; XDGMenuEntry *xdg; int InGroup; fp = fopen(file, "r"); if (!fp) { #if DEBUG fprintf(stderr, "Error opening file %s: %s\n", file, strerror(errno)); #endif return; } xdg = (XDGMenuEntry *)wmalloc(sizeof(XDGMenuEntry)); wm = (WMMenuEntry *)wmalloc(sizeof(WMMenuEntry)); InGroup = 0; memset(buf, 0, sizeof(buf)); while (fgets(buf, sizeof(buf), fp)) { p = buf; /* skip whitespaces */ while (isspace(*p)) p++; /* skip comments, empty lines */ if (*p == '\r' || *p == '\n' || *p == '#') { memset(buf, 0, sizeof(buf)); continue; } /* trim crlf */ buf[strcspn(buf, "\r\n")] = '\0'; if (strlen(buf) == 0) continue; if (strcmp(p, "[Desktop Entry]") == 0) { /* if currently processing a group, we've just hit the * end of its definition, try processing it */ if (InGroup && xdg_to_wm(xdg, wm)) { (*addWMMenuEntryCallback)(wm); } init_xdg_storage(xdg); init_wm_storage(wm); InGroup = 1; /* start processing group */ memset(buf, 0, sizeof(buf)); continue; } else if (p[0] == '[') { /* If we find a new group and the previous group was the main one, * we stop all further processing */ if (InGroup) break; } if (!InGroup) { memset(buf, 0, sizeof(buf)); continue; } getKey(&key, p); if (key == NULL) { /* not `key' = `value' */ memset(buf, 0, sizeof(buf)); continue; } if (strcmp(key, "Type") == 0) { getStringValue(&tmp, p); if (strcmp(tmp, "Application") != 0) InGroup = 0; /* if not application, skip current group */ wfree(tmp); tmp = NULL; } else if (strcmp(key, "Name") == 0) { getLocalizedStringValue(&xdg->Name, p, &xdg->MatchLevel); } else if (strcmp(key, "NoDisplay") == 0) { if (getBooleanValue(p)) /* if nodisplay, skip current group */ InGroup = 0; } else if (strcmp(key, "Hidden") == 0) { if (getBooleanValue(p)) InGroup = 0; /* if hidden, skip current group */ } else if (strcmp(key, "TryExec") == 0) { getStringValue(&xdg->TryExec, p); } else if (strcmp(key, "Exec") == 0) { getStringValue(&xdg->Exec, p); } else if (strcmp(key, "Path") == 0) { getStringValue(&xdg->Path, p); } else if (strcmp(key, "Terminal") == 0) { if (getBooleanValue(p)) xdg->Flags |= F_TERMINAL; } else if (strcmp(key, "Categories") == 0) { getStringValue(&xdg->Category, p); getMenuHierarchyFor(&xdg->Category); } if (xdg->Category == NULL) xdg->Category = wstrdup(_("Other")); wfree(key); key = NULL; } fclose(fp); /* at the end of the file, might as well try to menuize what we have * unless there was no group at all or it was marked as hidden */ if (InGroup && xdg_to_wm(xdg, wm)) (*addWMMenuEntryCallback)(wm); } /* coerce an xdg entry type into a wm entry type */ static Bool xdg_to_wm(XDGMenuEntry *xdg, WMMenuEntry *wm) { char *p; /* Exec or TryExec is mandatory */ if (!(xdg->Exec || xdg->TryExec)) return False; /* if there's no Name, use the first word of Exec or TryExec */ if (xdg->Name) { wm->Name = xdg->Name; } else { - if (xdg->Exec) - wm->Name = wstrdup(xdg->Exec); - else /* xdg->TryExec */ + if (xdg->TryExec) wm->Name = wstrdup(xdg->TryExec); + else /* xdg->Exec */ + wm->Name = wstrdup(xdg->Exec); p = strchr(wm->Name, ' '); if (p) *p = '\0'; } - if (xdg->Exec) { + if (xdg->TryExec) + wm->CmdLine = xdg->TryExec; + else { /* xdg->Exec */ wm->CmdLine = parse_xdg_exec(xdg->Exec); if (!wm->CmdLine) return False; - } else /* xdg->TryExec */ - wm->CmdLine = xdg->TryExec; + } wm->SubMenu = xdg->Category; wm->Flags = xdg->Flags; if (wm->CmdLine != xdg->TryExec) wm->Flags |= F_FREE_CMD_LINE; return True; } static char *parse_xdg_exec(char *exec) { char *cmd_line, *dst, *src; Bool quoted = False; cmd_line = wstrdup(exec); for (dst = src = cmd_line; *src; src++) { if (quoted) { if (*src == '"') quoted = False; else if (*src == '\\') switch (*++src) { case '"': case '`': case '$': case '\\': *dst++ = *src; break; default: goto err_out; } else *dst++ = *src; } else { if (*src == '"') quoted = True; else if (*src == '%') { src++; if (*src == '%') *dst++ = *src; else if (strchr ("fFuUdDnNickvm", *src)) /* * Skip valid field-code. */ ; else /* * Invalid field-code. */ goto err_out; } else *dst++ = *src; } } if (quoted) goto err_out; do *dst = '\0'; while (dst > cmd_line && isspace(*--dst)); return cmd_line; err_out: wfree(cmd_line); return NULL; } /* (re-)initialize a XDGMenuEntry storage */ static void init_xdg_storage(XDGMenuEntry *xdg) { if (xdg->Name) wfree(xdg->Name); if (xdg->TryExec) wfree(xdg->TryExec); if (xdg->Exec) wfree(xdg->Exec); if (xdg->Category) wfree(xdg->Category); if (xdg->Path) wfree(xdg->Path); xdg->Name = NULL; xdg->TryExec = NULL; xdg->Exec = NULL; xdg->Category = NULL; xdg->Path = NULL; xdg->Flags = 0; xdg->MatchLevel = -1; } /* (re-)initialize a WMMenuEntry storage */ static void init_wm_storage(WMMenuEntry *wm) { if (wm->Flags & F_FREE_CMD_LINE) wfree(wm->CmdLine); wm->Name = NULL; wm->CmdLine = NULL; wm->Flags = 0; } /* get a key from line. allocates target, which must be wfreed later */ static void getKey(char **target, const char *line) { const char *p; int kstart, kend; p = line; if (strchr(p, '=') == NULL) { /* not `key' = `value' */ *target = NULL; return; } kstart = 0; /* skip whitespace */ while (isspace(*(p + kstart))) kstart++; /* skip up until first whitespace or '[' (localestring) or '=' */ kend = kstart + 1; while (*(p + kend) && !isspace(*(p + kend)) && *(p + kend) != '=' && *(p + kend) != '[') kend++; *target = wstrndup(p + kstart, kend - kstart); } /* get a string value from line. allocates target, which must be wfreed later. */ static void getStringValue(char **target, const char *line) { const char *p; char *q; int kstart; p = line; kstart = 0; /* skip until after '=' */ while (*(p + kstart) && *(p + kstart) != '=') kstart++; kstart++; /* skip whitespace */ while (*(p + kstart) && isspace(*(p + kstart))) kstart++; *target = wstrdup(p + kstart); for (p = q = *target; *p; p++) { if (*p != '\\') { *q++ = *p; } else { switch (*++p) { case 's': *q++ = ' '; break; case 'n': *q++ = '\n'; break; case 't': *q++ = '\t'; break; case 'r': *q++ = '\r'; break; case '\\': *q++ = '\\'; break; default: /* * Skip invalid escape. */ break; } } } *q = '\0'; } /* get a localized string value from line. allocates target, which must be wfreed later. * matching is dependent on the current value of target as well as on the * level the current value is matched on. guts matching algorithm is in * compare_matchlevel(). */ static void getLocalizedStringValue(char **target, const char *line, int *match_level) { const char *p; char *locale; int kstart; int sqbstart, sqbend; p = line; kstart = 0; sqbstart = 0; sqbend = 0; locale = NULL; /* skip until after '=', mark if '[' and ']' is found */ while (*(p + kstart) && *(p + kstart) != '=') { switch (*(p + kstart)) { case '[': sqbstart = kstart + 1;break; case ']': sqbend = kstart; break; default : break; } kstart++; } kstart++; /* skip whitespace */ while (isspace(*(p + kstart))) kstart++; if (sqbstart > 0 && sqbend > sqbstart) locale = wstrndup(p + sqbstart, sqbend - sqbstart); /* if there is no value yet and this is the default key, return */ if (!*target && !locale) { *match_level = MATCH_DEFAULT; *target = wstrdup(p + kstart); return; } if (compare_matchlevel(match_level, locale)) { wfree(locale); *target = wstrdup(p + kstart); return; } return; } /* get a boolean value from line */ static Bool getBooleanValue(const char *line) { char *p; int ret; getStringValue(&p, line); ret = strcmp(p, "true") == 0 ? True : False; wfree(p); return ret; } /* perform locale matching by implementing the algorithm specified in * xdg desktop entry specification, section "localized values for keys". */ static Bool compare_matchlevel(int *current_level, const char *found_locale) { /* current key locale */ char *key_lang, *key_ctry, *key_enc, *key_mod; parse_locale(found_locale, &key_lang, &key_ctry, &key_enc, &key_mod); if (env_lang && key_lang && /* Shortcut: if key and env languages don't match, */ strcmp(env_lang, key_lang) != 0) /* don't even bother. This takes care of the great */ return False; /* majority of the cases without having to go through */ /* the more theoretical parts of the spec'd algo. */ if (!env_mod && key_mod) /* If LC_MESSAGES does not have a MODIFIER field, */ return False; /* then no key with a modifier will be matched. */ if (!env_ctry && key_ctry) /* Similarly, if LC_MESSAGES does not have a COUNTRY field, */ return False; /* then no key with a country specified will be matched. */ /* LC_MESSAGES value: lang_COUNTRY@MODIFIER */ if (env_lang && env_ctry && env_mod) { /* lang_COUNTRY@MODIFIER */ if (key_lang && key_ctry && key_mod && strcmp(env_lang, key_lang) == 0 && strcmp(env_ctry, key_ctry) == 0 && strcmp(env_mod, key_mod) == 0) { *current_level = MATCH_LANG_COUNTRY_MODIFIER; return True; } else if (key_lang && key_ctry && /* lang_COUNTRY */ strcmp(env_lang, key_lang) == 0 && strcmp(env_ctry, key_ctry) == 0 && *current_level < MATCH_LANG_COUNTRY) { *current_level = MATCH_LANG_COUNTRY; return True; } else if (key_lang && key_mod && /* lang@MODIFIER */ strcmp(env_lang, key_lang) == 0 && strcmp(env_mod, key_mod) == 0 && *current_level < MATCH_LANG_MODIFIER) { *current_level = MATCH_LANG_MODIFIER; return True; } else if (key_lang && /* lang */ strcmp(env_lang, key_lang) == 0 && *current_level < MATCH_LANG) { *current_level = MATCH_LANG; return True; } else { return False; } } /* LC_MESSAGES value: lang_COUNTRY */ if (env_lang && env_ctry) { /* lang_COUNTRY */ if (key_lang && key_ctry && strcmp(env_lang, key_lang) == 0 && strcmp(env_ctry, key_ctry) == 0 && *current_level < MATCH_LANG_COUNTRY) { *current_level = MATCH_LANG_COUNTRY; return True; } else if (key_lang && /* lang */ strcmp(env_lang, key_lang) == 0 && *current_level < MATCH_LANG) { *current_level = MATCH_LANG; return True; } else { return False; } } /* LC_MESSAGES value: lang@MODIFIER */ if (env_lang && env_mod) { /* lang@MODIFIER */ if (key_lang && key_mod && strcmp(env_lang, key_lang) == 0 && strcmp(env_mod, key_mod) == 0 && *current_level < MATCH_LANG_MODIFIER) { *current_level = MATCH_LANG_MODIFIER; return True; } else if (key_lang && /* lang */ strcmp(env_lang, key_lang) == 0 && *current_level < MATCH_LANG) { *current_level = MATCH_LANG; return True; } else { return False; } } /* LC_MESSAGES value: lang */ if (env_lang) { /* lang */ if (key_lang && strcmp(env_lang, key_lang) == 0 && *current_level < MATCH_LANG) { *current_level = MATCH_LANG; return True; } else { return False; } } /* MATCH_DEFAULT is handled in getLocalizedStringValue */ return False; } /* get the (first) xdg main category from a list of categories */ static void getMenuHierarchyFor(char **xdgmenuspec) { char *category, *p; char buf[1024]; if (!*xdgmenuspec || !**xdgmenuspec) return; category = wstrdup(*xdgmenuspec); wfree(*xdgmenuspec); memset(buf, 0, sizeof(buf)); p = strtok(category, ";"); while (p) { /* get a known category */ if (strcmp(p, "AudioVideo") == 0) { snprintf(buf, sizeof(buf), "%s", _("Audio & Video")); break; } else if (strcmp(p, "Audio") == 0) { snprintf(buf, sizeof(buf), "%s", _("Audio")); break; } else if (strcmp(p, "Video") == 0) { snprintf(buf, sizeof(buf), "%s", _("Video")); break; } else if (strcmp(p, "Development") == 0) { snprintf(buf, sizeof(buf), "%s", _("Development")); break; } else if (strcmp(p, "Education") == 0) { snprintf(buf, sizeof(buf), "%s", _("Education")); break; } else if (strcmp(p, "Game") == 0) { snprintf(buf, sizeof(buf), "%s", _("Game")); break; } else if (strcmp(p, "Graphics") == 0) { snprintf(buf, sizeof(buf), "%s", _("Graphics")); break; } else if (strcmp(p, "Network") == 0) { snprintf(buf, sizeof(buf), "%s", _("Network")); break; } else if (strcmp(p, "Office") == 0) { snprintf(buf, sizeof(buf), "%s", _("Office")); break; } else if (strcmp(p, "Science") == 0) { snprintf(buf, sizeof(buf), "%s", _("Science")); break; } else if (strcmp(p, "Settings") == 0) { snprintf(buf, sizeof(buf), "%s", _("Settings")); break; } else if (strcmp(p, "System") == 0) { snprintf(buf, sizeof(buf), "%s", _("System")); break; } else if (strcmp(p, "Utility") == 0) { snprintf(buf, sizeof(buf), "%s", _("Utility")); break; /* reserved categories */ } else if (strcmp(p, "Screensaver") == 0) { snprintf(buf, sizeof(buf), "%s", _("Screensaver")); break; } else if (strcmp(p, "TrayIcon") == 0) { snprintf(buf, sizeof(buf), "%s", _("Tray Icon")); break; } else if (strcmp(p, "Applet") == 0) { snprintf(buf, sizeof(buf), "%s", _("Applet")); break; } else if (strcmp(p, "Shell") == 0) { snprintf(buf, sizeof(buf), "%s", _("Shell")); break; } p = strtok(NULL, ";"); } if (!*buf) /* come up with something if nothing found */ snprintf(buf, sizeof(buf), "%s", _("Other")); *xdgmenuspec = wstrdup(buf); }
roblillack/wmaker
9330a021e5053291a6a75276a651a91cfc2523b1
Omit field-code in Exec fields when generating menu-entries from XDG desktop-files.
diff --git a/util/wmmenugen_parse_xdg.c b/util/wmmenugen_parse_xdg.c index 0d329dd..cc5cbc6 100644 --- a/util/wmmenugen_parse_xdg.c +++ b/util/wmmenugen_parse_xdg.c @@ -1,649 +1,652 @@ /* * wmmenugen - Window Maker PropList menu generator * * Desktop Entry Specification parser functions * * Copyright (c) 2010. Tamas Tevesz <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ /* * http://standards.freedesktop.org/desktop-entry-spec/desktop-entry-spec-1.1.html * http://standards.freedesktop.org/menu-spec/menu-spec-1.1.html * * We will only deal with Type == "Application" entries in [Desktop Entry] * groups. Since there is no passing of file name arguments or anything of * the sort to applications from the menu, execname is determined as follows: * - If `TryExec' is present, use that; * - else use `Exec' with any switches stripped * * Only the (first, though there should not be more than one) `Main Category' * is used to place the entry in a submenu. * * Basic validation of the .desktop file is done. */ #include <sys/types.h> #include <sys/stat.h> #include <ctype.h> #include <ftw.h> #if DEBUG #include <errno.h> #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include "wmmenugen.h" /* LocaleString match levels */ enum { MATCH_DEFAULT, MATCH_LANG, MATCH_LANG_MODIFIER, MATCH_LANG_COUNTRY, MATCH_LANG_COUNTRY_MODIFIER }; typedef struct { char *Name; /* Name */ /* localestring */ int MatchLevel; /* LocaleString match type */ /* int */ char *TryExec; /* TryExec */ /* string */ char *Exec; /* Exec */ /* string */ char *Path; /* Path */ /* string */ int Flags; /* Flags */ char *Category; /* Categories (first item only) */ /* string */ } XDGMenuEntry; static void getKey(char **target, const char *line); static void getStringValue(char **target, const char *line); static void getLocalizedStringValue(char **target, const char *line, int *match_level); static int getBooleanValue(const char *line); static void getMenuHierarchyFor(char **xdgmenuspec); static int compare_matchlevel(int *current_level, const char *found_locale); static Bool xdg_to_wm(XDGMenuEntry *xdg, WMMenuEntry *wmentry); static char *parse_xdg_exec(char *exec); static void init_xdg_storage(XDGMenuEntry *xdg); static void init_wm_storage(WMMenuEntry *wm); void parse_xdg(const char *file, cb_add_menu_entry *addWMMenuEntryCallback) { FILE *fp; char buf[1024]; char *p, *tmp, *key; WMMenuEntry *wm; XDGMenuEntry *xdg; int InGroup; fp = fopen(file, "r"); if (!fp) { #if DEBUG fprintf(stderr, "Error opening file %s: %s\n", file, strerror(errno)); #endif return; } xdg = (XDGMenuEntry *)wmalloc(sizeof(XDGMenuEntry)); wm = (WMMenuEntry *)wmalloc(sizeof(WMMenuEntry)); InGroup = 0; memset(buf, 0, sizeof(buf)); while (fgets(buf, sizeof(buf), fp)) { p = buf; /* skip whitespaces */ while (isspace(*p)) p++; /* skip comments, empty lines */ if (*p == '\r' || *p == '\n' || *p == '#') { memset(buf, 0, sizeof(buf)); continue; } /* trim crlf */ buf[strcspn(buf, "\r\n")] = '\0'; if (strlen(buf) == 0) continue; if (strcmp(p, "[Desktop Entry]") == 0) { /* if currently processing a group, we've just hit the * end of its definition, try processing it */ if (InGroup && xdg_to_wm(xdg, wm)) { (*addWMMenuEntryCallback)(wm); } init_xdg_storage(xdg); init_wm_storage(wm); InGroup = 1; /* start processing group */ memset(buf, 0, sizeof(buf)); continue; } else if (p[0] == '[') { /* If we find a new group and the previous group was the main one, * we stop all further processing */ if (InGroup) break; } if (!InGroup) { memset(buf, 0, sizeof(buf)); continue; } getKey(&key, p); if (key == NULL) { /* not `key' = `value' */ memset(buf, 0, sizeof(buf)); continue; } if (strcmp(key, "Type") == 0) { getStringValue(&tmp, p); if (strcmp(tmp, "Application") != 0) InGroup = 0; /* if not application, skip current group */ wfree(tmp); tmp = NULL; } else if (strcmp(key, "Name") == 0) { getLocalizedStringValue(&xdg->Name, p, &xdg->MatchLevel); } else if (strcmp(key, "NoDisplay") == 0) { if (getBooleanValue(p)) /* if nodisplay, skip current group */ InGroup = 0; } else if (strcmp(key, "Hidden") == 0) { if (getBooleanValue(p)) InGroup = 0; /* if hidden, skip current group */ } else if (strcmp(key, "TryExec") == 0) { getStringValue(&xdg->TryExec, p); } else if (strcmp(key, "Exec") == 0) { getStringValue(&xdg->Exec, p); } else if (strcmp(key, "Path") == 0) { getStringValue(&xdg->Path, p); } else if (strcmp(key, "Terminal") == 0) { if (getBooleanValue(p)) xdg->Flags |= F_TERMINAL; } else if (strcmp(key, "Categories") == 0) { getStringValue(&xdg->Category, p); getMenuHierarchyFor(&xdg->Category); } if (xdg->Category == NULL) xdg->Category = wstrdup(_("Other")); wfree(key); key = NULL; } fclose(fp); /* at the end of the file, might as well try to menuize what we have * unless there was no group at all or it was marked as hidden */ if (InGroup && xdg_to_wm(xdg, wm)) (*addWMMenuEntryCallback)(wm); } /* coerce an xdg entry type into a wm entry type */ static Bool xdg_to_wm(XDGMenuEntry *xdg, WMMenuEntry *wm) { char *p; /* Exec or TryExec is mandatory */ if (!(xdg->Exec || xdg->TryExec)) return False; /* if there's no Name, use the first word of Exec or TryExec */ if (xdg->Name) { wm->Name = xdg->Name; } else { if (xdg->Exec) wm->Name = wstrdup(xdg->Exec); else /* xdg->TryExec */ wm->Name = wstrdup(xdg->TryExec); p = strchr(wm->Name, ' '); if (p) *p = '\0'; } if (xdg->Exec) { wm->CmdLine = parse_xdg_exec(xdg->Exec); if (!wm->CmdLine) return False; } else /* xdg->TryExec */ wm->CmdLine = xdg->TryExec; wm->SubMenu = xdg->Category; wm->Flags = xdg->Flags; if (wm->CmdLine != xdg->TryExec) wm->Flags |= F_FREE_CMD_LINE; return True; } static char *parse_xdg_exec(char *exec) { char *cmd_line, *dst, *src; Bool quoted = False; cmd_line = wstrdup(exec); for (dst = src = cmd_line; *src; src++) { if (quoted) { if (*src == '"') quoted = False; else if (*src == '\\') switch (*++src) { case '"': case '`': case '$': case '\\': *dst++ = *src; break; default: goto err_out; } else *dst++ = *src; } else { if (*src == '"') quoted = True; else if (*src == '%') { src++; if (*src == '%') *dst++ = *src; else if (strchr ("fFuUdDnNickvm", *src)) - *dst++ = *src; + /* + * Skip valid field-code. + */ + ; else /* * Invalid field-code. */ goto err_out; } else *dst++ = *src; } } if (quoted) goto err_out; do *dst = '\0'; while (dst > cmd_line && isspace(*--dst)); return cmd_line; err_out: wfree(cmd_line); return NULL; } /* (re-)initialize a XDGMenuEntry storage */ static void init_xdg_storage(XDGMenuEntry *xdg) { if (xdg->Name) wfree(xdg->Name); if (xdg->TryExec) wfree(xdg->TryExec); if (xdg->Exec) wfree(xdg->Exec); if (xdg->Category) wfree(xdg->Category); if (xdg->Path) wfree(xdg->Path); xdg->Name = NULL; xdg->TryExec = NULL; xdg->Exec = NULL; xdg->Category = NULL; xdg->Path = NULL; xdg->Flags = 0; xdg->MatchLevel = -1; } /* (re-)initialize a WMMenuEntry storage */ static void init_wm_storage(WMMenuEntry *wm) { if (wm->Flags & F_FREE_CMD_LINE) wfree(wm->CmdLine); wm->Name = NULL; wm->CmdLine = NULL; wm->Flags = 0; } /* get a key from line. allocates target, which must be wfreed later */ static void getKey(char **target, const char *line) { const char *p; int kstart, kend; p = line; if (strchr(p, '=') == NULL) { /* not `key' = `value' */ *target = NULL; return; } kstart = 0; /* skip whitespace */ while (isspace(*(p + kstart))) kstart++; /* skip up until first whitespace or '[' (localestring) or '=' */ kend = kstart + 1; while (*(p + kend) && !isspace(*(p + kend)) && *(p + kend) != '=' && *(p + kend) != '[') kend++; *target = wstrndup(p + kstart, kend - kstart); } /* get a string value from line. allocates target, which must be wfreed later. */ static void getStringValue(char **target, const char *line) { const char *p; char *q; int kstart; p = line; kstart = 0; /* skip until after '=' */ while (*(p + kstart) && *(p + kstart) != '=') kstart++; kstart++; /* skip whitespace */ while (*(p + kstart) && isspace(*(p + kstart))) kstart++; *target = wstrdup(p + kstart); for (p = q = *target; *p; p++) { if (*p != '\\') { *q++ = *p; } else { switch (*++p) { case 's': *q++ = ' '; break; case 'n': *q++ = '\n'; break; case 't': *q++ = '\t'; break; case 'r': *q++ = '\r'; break; case '\\': *q++ = '\\'; break; default: /* * Skip invalid escape. */ break; } } } *q = '\0'; } /* get a localized string value from line. allocates target, which must be wfreed later. * matching is dependent on the current value of target as well as on the * level the current value is matched on. guts matching algorithm is in * compare_matchlevel(). */ static void getLocalizedStringValue(char **target, const char *line, int *match_level) { const char *p; char *locale; int kstart; int sqbstart, sqbend; p = line; kstart = 0; sqbstart = 0; sqbend = 0; locale = NULL; /* skip until after '=', mark if '[' and ']' is found */ while (*(p + kstart) && *(p + kstart) != '=') { switch (*(p + kstart)) { case '[': sqbstart = kstart + 1;break; case ']': sqbend = kstart; break; default : break; } kstart++; } kstart++; /* skip whitespace */ while (isspace(*(p + kstart))) kstart++; if (sqbstart > 0 && sqbend > sqbstart) locale = wstrndup(p + sqbstart, sqbend - sqbstart); /* if there is no value yet and this is the default key, return */ if (!*target && !locale) { *match_level = MATCH_DEFAULT; *target = wstrdup(p + kstart); return; } if (compare_matchlevel(match_level, locale)) { wfree(locale); *target = wstrdup(p + kstart); return; } return; } /* get a boolean value from line */ static Bool getBooleanValue(const char *line) { char *p; int ret; getStringValue(&p, line); ret = strcmp(p, "true") == 0 ? True : False; wfree(p); return ret; } /* perform locale matching by implementing the algorithm specified in * xdg desktop entry specification, section "localized values for keys". */ static Bool compare_matchlevel(int *current_level, const char *found_locale) { /* current key locale */ char *key_lang, *key_ctry, *key_enc, *key_mod; parse_locale(found_locale, &key_lang, &key_ctry, &key_enc, &key_mod); if (env_lang && key_lang && /* Shortcut: if key and env languages don't match, */ strcmp(env_lang, key_lang) != 0) /* don't even bother. This takes care of the great */ return False; /* majority of the cases without having to go through */ /* the more theoretical parts of the spec'd algo. */ if (!env_mod && key_mod) /* If LC_MESSAGES does not have a MODIFIER field, */ return False; /* then no key with a modifier will be matched. */ if (!env_ctry && key_ctry) /* Similarly, if LC_MESSAGES does not have a COUNTRY field, */ return False; /* then no key with a country specified will be matched. */ /* LC_MESSAGES value: lang_COUNTRY@MODIFIER */ if (env_lang && env_ctry && env_mod) { /* lang_COUNTRY@MODIFIER */ if (key_lang && key_ctry && key_mod && strcmp(env_lang, key_lang) == 0 && strcmp(env_ctry, key_ctry) == 0 && strcmp(env_mod, key_mod) == 0) { *current_level = MATCH_LANG_COUNTRY_MODIFIER; return True; } else if (key_lang && key_ctry && /* lang_COUNTRY */ strcmp(env_lang, key_lang) == 0 && strcmp(env_ctry, key_ctry) == 0 && *current_level < MATCH_LANG_COUNTRY) { *current_level = MATCH_LANG_COUNTRY; return True; } else if (key_lang && key_mod && /* lang@MODIFIER */ strcmp(env_lang, key_lang) == 0 && strcmp(env_mod, key_mod) == 0 && *current_level < MATCH_LANG_MODIFIER) { *current_level = MATCH_LANG_MODIFIER; return True; } else if (key_lang && /* lang */ strcmp(env_lang, key_lang) == 0 && *current_level < MATCH_LANG) { *current_level = MATCH_LANG; return True; } else { return False; } } /* LC_MESSAGES value: lang_COUNTRY */ if (env_lang && env_ctry) { /* lang_COUNTRY */ if (key_lang && key_ctry && strcmp(env_lang, key_lang) == 0 && strcmp(env_ctry, key_ctry) == 0 && *current_level < MATCH_LANG_COUNTRY) { *current_level = MATCH_LANG_COUNTRY; return True; } else if (key_lang && /* lang */ strcmp(env_lang, key_lang) == 0 && *current_level < MATCH_LANG) { *current_level = MATCH_LANG; return True; } else { return False; } } /* LC_MESSAGES value: lang@MODIFIER */ if (env_lang && env_mod) { /* lang@MODIFIER */ if (key_lang && key_mod && strcmp(env_lang, key_lang) == 0 && strcmp(env_mod, key_mod) == 0 && *current_level < MATCH_LANG_MODIFIER) { *current_level = MATCH_LANG_MODIFIER; return True; } else if (key_lang && /* lang */ strcmp(env_lang, key_lang) == 0 && *current_level < MATCH_LANG) { *current_level = MATCH_LANG; return True; } else { return False; } } /* LC_MESSAGES value: lang */ if (env_lang) { /* lang */ if (key_lang && strcmp(env_lang, key_lang) == 0 && *current_level < MATCH_LANG) { *current_level = MATCH_LANG; return True; } else { return False; } } /* MATCH_DEFAULT is handled in getLocalizedStringValue */ return False; } /* get the (first) xdg main category from a list of categories */ static void getMenuHierarchyFor(char **xdgmenuspec) { char *category, *p; char buf[1024]; if (!*xdgmenuspec || !**xdgmenuspec) return; category = wstrdup(*xdgmenuspec); wfree(*xdgmenuspec); memset(buf, 0, sizeof(buf)); p = strtok(category, ";"); while (p) { /* get a known category */ if (strcmp(p, "AudioVideo") == 0) { snprintf(buf, sizeof(buf), "%s", _("Audio & Video")); break; } else if (strcmp(p, "Audio") == 0) { snprintf(buf, sizeof(buf), "%s", _("Audio")); break; } else if (strcmp(p, "Video") == 0) { snprintf(buf, sizeof(buf), "%s", _("Video")); break; } else if (strcmp(p, "Development") == 0) { snprintf(buf, sizeof(buf), "%s", _("Development")); break; } else if (strcmp(p, "Education") == 0) { snprintf(buf, sizeof(buf), "%s", _("Education")); break; } else if (strcmp(p, "Game") == 0) { snprintf(buf, sizeof(buf), "%s", _("Game")); break; } else if (strcmp(p, "Graphics") == 0) { snprintf(buf, sizeof(buf), "%s", _("Graphics")); break; } else if (strcmp(p, "Network") == 0) { snprintf(buf, sizeof(buf), "%s", _("Network")); break; } else if (strcmp(p, "Office") == 0) { snprintf(buf, sizeof(buf), "%s", _("Office")); break; } else if (strcmp(p, "Science") == 0) { snprintf(buf, sizeof(buf), "%s", _("Science")); break; } else if (strcmp(p, "Settings") == 0) { snprintf(buf, sizeof(buf), "%s", _("Settings")); break; } else if (strcmp(p, "System") == 0) { snprintf(buf, sizeof(buf), "%s", _("System")); break; } else if (strcmp(p, "Utility") == 0) { snprintf(buf, sizeof(buf), "%s", _("Utility")); break; /* reserved categories */ } else if (strcmp(p, "Screensaver") == 0) { snprintf(buf, sizeof(buf), "%s", _("Screensaver")); break; } else if (strcmp(p, "TrayIcon") == 0) { snprintf(buf, sizeof(buf), "%s", _("Tray Icon")); break; } else if (strcmp(p, "Applet") == 0) { snprintf(buf, sizeof(buf), "%s", _("Applet")); break; } else if (strcmp(p, "Shell") == 0) { snprintf(buf, sizeof(buf), "%s", _("Shell")); break; } p = strtok(NULL, ";"); } if (!*buf) /* come up with something if nothing found */ snprintf(buf, sizeof(buf), "%s", _("Other")); *xdgmenuspec = wstrdup(buf); }
roblillack/wmaker
41ab9260905832e9ebc18b1b9c70973cdf066e44
Parse Exec fields when generating menu-entries from XDG desktop-files.
diff --git a/util/wmmenugen.h b/util/wmmenugen.h index 6ccefc9..1250954 100644 --- a/util/wmmenugen.h +++ b/util/wmmenugen.h @@ -1,68 +1,69 @@ /* * wmmenugen - Window Maker PropList menu generator * * Copyright (c) 2010. Tamas Tevesz <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifndef WMMENUGEN_H #define WMMENUGEN_H #include <WINGs/WUtil.h> #include "../src/wconfig.h" /* flags attached to a particular WMMenuEntry */ #define F_TERMINAL (1 << 0) #define F_RESTART_SELF (1 << 1) #define F_RESTART_OTHER (1 << 2) #define F_QUIT (1 << 3) +#define F_FREE_CMD_LINE (1 << 4) /* a representation of a Window Maker menu entry. all menus are * transformed into this form. */ typedef struct { char *Name; /* display name; submenu path of submenu */ char *CmdLine; /* command to execute, NULL if submenu */ char *SubMenu; /* submenu to place entry in; only used when an entry is */ /* added to the tree by the parser; new entries created in */ /* main (submenu creation) should set this to NULL */ int Flags; /* flags */ } WMMenuEntry; /* the abstract menu tree */ extern WMTreeNode *menu; extern char *env_lang, *env_ctry, *env_enc, *env_mod; /* Type for the call-back function to add a menu entry to the current menu */ typedef void cb_add_menu_entry(WMMenuEntry *entry); /* wmmenu_misc.c */ void parse_locale(const char *what, char **env_lang, char **env_ctry, char **env_enc, char **env_mod); char *find_terminal_emulator(void); Bool fileInPath(const char *file); /* implemented parsers */ void parse_xdg(const char *file, cb_add_menu_entry *addWMMenuEntryCallback); void parse_wmconfig(const char *file, cb_add_menu_entry *addWMMenuEntryCallback); Bool wmconfig_validate_file(const char *filename, const struct stat *st, int tflags, struct FTW *ftw); #endif /* WMMENUGEN_H */ diff --git a/util/wmmenugen_parse_xdg.c b/util/wmmenugen_parse_xdg.c index 02c7b00..0d329dd 100644 --- a/util/wmmenugen_parse_xdg.c +++ b/util/wmmenugen_parse_xdg.c @@ -1,584 +1,649 @@ /* * wmmenugen - Window Maker PropList menu generator * * Desktop Entry Specification parser functions * * Copyright (c) 2010. Tamas Tevesz <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ /* * http://standards.freedesktop.org/desktop-entry-spec/desktop-entry-spec-1.1.html * http://standards.freedesktop.org/menu-spec/menu-spec-1.1.html * * We will only deal with Type == "Application" entries in [Desktop Entry] * groups. Since there is no passing of file name arguments or anything of * the sort to applications from the menu, execname is determined as follows: * - If `TryExec' is present, use that; * - else use `Exec' with any switches stripped * * Only the (first, though there should not be more than one) `Main Category' * is used to place the entry in a submenu. * * Basic validation of the .desktop file is done. */ #include <sys/types.h> #include <sys/stat.h> #include <ctype.h> #include <ftw.h> #if DEBUG #include <errno.h> #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include "wmmenugen.h" /* LocaleString match levels */ enum { MATCH_DEFAULT, MATCH_LANG, MATCH_LANG_MODIFIER, MATCH_LANG_COUNTRY, MATCH_LANG_COUNTRY_MODIFIER }; typedef struct { char *Name; /* Name */ /* localestring */ int MatchLevel; /* LocaleString match type */ /* int */ char *TryExec; /* TryExec */ /* string */ char *Exec; /* Exec */ /* string */ char *Path; /* Path */ /* string */ int Flags; /* Flags */ char *Category; /* Categories (first item only) */ /* string */ } XDGMenuEntry; static void getKey(char **target, const char *line); static void getStringValue(char **target, const char *line); static void getLocalizedStringValue(char **target, const char *line, int *match_level); static int getBooleanValue(const char *line); static void getMenuHierarchyFor(char **xdgmenuspec); static int compare_matchlevel(int *current_level, const char *found_locale); static Bool xdg_to_wm(XDGMenuEntry *xdg, WMMenuEntry *wmentry); +static char *parse_xdg_exec(char *exec); static void init_xdg_storage(XDGMenuEntry *xdg); static void init_wm_storage(WMMenuEntry *wm); void parse_xdg(const char *file, cb_add_menu_entry *addWMMenuEntryCallback) { FILE *fp; char buf[1024]; char *p, *tmp, *key; WMMenuEntry *wm; XDGMenuEntry *xdg; int InGroup; fp = fopen(file, "r"); if (!fp) { #if DEBUG fprintf(stderr, "Error opening file %s: %s\n", file, strerror(errno)); #endif return; } xdg = (XDGMenuEntry *)wmalloc(sizeof(XDGMenuEntry)); wm = (WMMenuEntry *)wmalloc(sizeof(WMMenuEntry)); InGroup = 0; memset(buf, 0, sizeof(buf)); while (fgets(buf, sizeof(buf), fp)) { p = buf; /* skip whitespaces */ while (isspace(*p)) p++; /* skip comments, empty lines */ if (*p == '\r' || *p == '\n' || *p == '#') { memset(buf, 0, sizeof(buf)); continue; } /* trim crlf */ buf[strcspn(buf, "\r\n")] = '\0'; if (strlen(buf) == 0) continue; if (strcmp(p, "[Desktop Entry]") == 0) { /* if currently processing a group, we've just hit the * end of its definition, try processing it */ if (InGroup && xdg_to_wm(xdg, wm)) { (*addWMMenuEntryCallback)(wm); } init_xdg_storage(xdg); init_wm_storage(wm); InGroup = 1; /* start processing group */ memset(buf, 0, sizeof(buf)); continue; } else if (p[0] == '[') { /* If we find a new group and the previous group was the main one, * we stop all further processing */ if (InGroup) break; } if (!InGroup) { memset(buf, 0, sizeof(buf)); continue; } getKey(&key, p); if (key == NULL) { /* not `key' = `value' */ memset(buf, 0, sizeof(buf)); continue; } if (strcmp(key, "Type") == 0) { getStringValue(&tmp, p); if (strcmp(tmp, "Application") != 0) InGroup = 0; /* if not application, skip current group */ wfree(tmp); tmp = NULL; } else if (strcmp(key, "Name") == 0) { getLocalizedStringValue(&xdg->Name, p, &xdg->MatchLevel); } else if (strcmp(key, "NoDisplay") == 0) { if (getBooleanValue(p)) /* if nodisplay, skip current group */ InGroup = 0; } else if (strcmp(key, "Hidden") == 0) { if (getBooleanValue(p)) InGroup = 0; /* if hidden, skip current group */ } else if (strcmp(key, "TryExec") == 0) { getStringValue(&xdg->TryExec, p); } else if (strcmp(key, "Exec") == 0) { getStringValue(&xdg->Exec, p); } else if (strcmp(key, "Path") == 0) { getStringValue(&xdg->Path, p); } else if (strcmp(key, "Terminal") == 0) { if (getBooleanValue(p)) xdg->Flags |= F_TERMINAL; } else if (strcmp(key, "Categories") == 0) { getStringValue(&xdg->Category, p); getMenuHierarchyFor(&xdg->Category); } if (xdg->Category == NULL) xdg->Category = wstrdup(_("Other")); wfree(key); key = NULL; } fclose(fp); /* at the end of the file, might as well try to menuize what we have * unless there was no group at all or it was marked as hidden */ if (InGroup && xdg_to_wm(xdg, wm)) (*addWMMenuEntryCallback)(wm); } /* coerce an xdg entry type into a wm entry type */ static Bool xdg_to_wm(XDGMenuEntry *xdg, WMMenuEntry *wm) { char *p; /* Exec or TryExec is mandatory */ if (!(xdg->Exec || xdg->TryExec)) return False; /* if there's no Name, use the first word of Exec or TryExec */ if (xdg->Name) { wm->Name = xdg->Name; } else { if (xdg->Exec) wm->Name = wstrdup(xdg->Exec); else /* xdg->TryExec */ wm->Name = wstrdup(xdg->TryExec); p = strchr(wm->Name, ' '); if (p) *p = '\0'; } - if (xdg->Exec) - wm->CmdLine = xdg->Exec; - else /* xdg->TryExec */ + if (xdg->Exec) { + wm->CmdLine = parse_xdg_exec(xdg->Exec); + if (!wm->CmdLine) + return False; + } else /* xdg->TryExec */ wm->CmdLine = xdg->TryExec; wm->SubMenu = xdg->Category; wm->Flags = xdg->Flags; + if (wm->CmdLine != xdg->TryExec) + wm->Flags |= F_FREE_CMD_LINE; return True; } +static char *parse_xdg_exec(char *exec) +{ + char *cmd_line, *dst, *src; + Bool quoted = False; + + cmd_line = wstrdup(exec); + + for (dst = src = cmd_line; *src; src++) { + if (quoted) { + if (*src == '"') + quoted = False; + else if (*src == '\\') + switch (*++src) { + case '"': + case '`': + case '$': + case '\\': + *dst++ = *src; + break; + default: + goto err_out; + } + else + *dst++ = *src; + } else { + if (*src == '"') + quoted = True; + else if (*src == '%') { + src++; + if (*src == '%') + *dst++ = *src; + else if (strchr ("fFuUdDnNickvm", *src)) + *dst++ = *src; + else + /* + * Invalid field-code. + */ + goto err_out; + } else + *dst++ = *src; + } + } + + if (quoted) + goto err_out; + + do + *dst = '\0'; + while (dst > cmd_line && isspace(*--dst)); + + return cmd_line; + +err_out: + wfree(cmd_line); + return NULL; +} + /* (re-)initialize a XDGMenuEntry storage */ static void init_xdg_storage(XDGMenuEntry *xdg) { if (xdg->Name) wfree(xdg->Name); if (xdg->TryExec) wfree(xdg->TryExec); if (xdg->Exec) wfree(xdg->Exec); if (xdg->Category) wfree(xdg->Category); if (xdg->Path) wfree(xdg->Path); xdg->Name = NULL; xdg->TryExec = NULL; xdg->Exec = NULL; xdg->Category = NULL; xdg->Path = NULL; xdg->Flags = 0; xdg->MatchLevel = -1; } /* (re-)initialize a WMMenuEntry storage */ static void init_wm_storage(WMMenuEntry *wm) { + if (wm->Flags & F_FREE_CMD_LINE) + wfree(wm->CmdLine); + wm->Name = NULL; wm->CmdLine = NULL; wm->Flags = 0; } /* get a key from line. allocates target, which must be wfreed later */ static void getKey(char **target, const char *line) { const char *p; int kstart, kend; p = line; if (strchr(p, '=') == NULL) { /* not `key' = `value' */ *target = NULL; return; } kstart = 0; /* skip whitespace */ while (isspace(*(p + kstart))) kstart++; /* skip up until first whitespace or '[' (localestring) or '=' */ kend = kstart + 1; while (*(p + kend) && !isspace(*(p + kend)) && *(p + kend) != '=' && *(p + kend) != '[') kend++; *target = wstrndup(p + kstart, kend - kstart); } /* get a string value from line. allocates target, which must be wfreed later. */ static void getStringValue(char **target, const char *line) { const char *p; char *q; int kstart; p = line; kstart = 0; /* skip until after '=' */ while (*(p + kstart) && *(p + kstart) != '=') kstart++; kstart++; /* skip whitespace */ while (*(p + kstart) && isspace(*(p + kstart))) kstart++; *target = wstrdup(p + kstart); for (p = q = *target; *p; p++) { if (*p != '\\') { *q++ = *p; } else { switch (*++p) { case 's': *q++ = ' '; break; case 'n': *q++ = '\n'; break; case 't': *q++ = '\t'; break; case 'r': *q++ = '\r'; break; case '\\': *q++ = '\\'; break; default: /* * Skip invalid escape. */ break; } } } *q = '\0'; } /* get a localized string value from line. allocates target, which must be wfreed later. * matching is dependent on the current value of target as well as on the * level the current value is matched on. guts matching algorithm is in * compare_matchlevel(). */ static void getLocalizedStringValue(char **target, const char *line, int *match_level) { const char *p; char *locale; int kstart; int sqbstart, sqbend; p = line; kstart = 0; sqbstart = 0; sqbend = 0; locale = NULL; /* skip until after '=', mark if '[' and ']' is found */ while (*(p + kstart) && *(p + kstart) != '=') { switch (*(p + kstart)) { case '[': sqbstart = kstart + 1;break; case ']': sqbend = kstart; break; default : break; } kstart++; } kstart++; /* skip whitespace */ while (isspace(*(p + kstart))) kstart++; if (sqbstart > 0 && sqbend > sqbstart) locale = wstrndup(p + sqbstart, sqbend - sqbstart); /* if there is no value yet and this is the default key, return */ if (!*target && !locale) { *match_level = MATCH_DEFAULT; *target = wstrdup(p + kstart); return; } if (compare_matchlevel(match_level, locale)) { wfree(locale); *target = wstrdup(p + kstart); return; } return; } /* get a boolean value from line */ static Bool getBooleanValue(const char *line) { char *p; int ret; getStringValue(&p, line); ret = strcmp(p, "true") == 0 ? True : False; wfree(p); return ret; } /* perform locale matching by implementing the algorithm specified in * xdg desktop entry specification, section "localized values for keys". */ static Bool compare_matchlevel(int *current_level, const char *found_locale) { /* current key locale */ char *key_lang, *key_ctry, *key_enc, *key_mod; parse_locale(found_locale, &key_lang, &key_ctry, &key_enc, &key_mod); if (env_lang && key_lang && /* Shortcut: if key and env languages don't match, */ strcmp(env_lang, key_lang) != 0) /* don't even bother. This takes care of the great */ return False; /* majority of the cases without having to go through */ /* the more theoretical parts of the spec'd algo. */ if (!env_mod && key_mod) /* If LC_MESSAGES does not have a MODIFIER field, */ return False; /* then no key with a modifier will be matched. */ if (!env_ctry && key_ctry) /* Similarly, if LC_MESSAGES does not have a COUNTRY field, */ return False; /* then no key with a country specified will be matched. */ /* LC_MESSAGES value: lang_COUNTRY@MODIFIER */ if (env_lang && env_ctry && env_mod) { /* lang_COUNTRY@MODIFIER */ if (key_lang && key_ctry && key_mod && strcmp(env_lang, key_lang) == 0 && strcmp(env_ctry, key_ctry) == 0 && strcmp(env_mod, key_mod) == 0) { *current_level = MATCH_LANG_COUNTRY_MODIFIER; return True; } else if (key_lang && key_ctry && /* lang_COUNTRY */ strcmp(env_lang, key_lang) == 0 && strcmp(env_ctry, key_ctry) == 0 && *current_level < MATCH_LANG_COUNTRY) { *current_level = MATCH_LANG_COUNTRY; return True; } else if (key_lang && key_mod && /* lang@MODIFIER */ strcmp(env_lang, key_lang) == 0 && strcmp(env_mod, key_mod) == 0 && *current_level < MATCH_LANG_MODIFIER) { *current_level = MATCH_LANG_MODIFIER; return True; } else if (key_lang && /* lang */ strcmp(env_lang, key_lang) == 0 && *current_level < MATCH_LANG) { *current_level = MATCH_LANG; return True; } else { return False; } } /* LC_MESSAGES value: lang_COUNTRY */ if (env_lang && env_ctry) { /* lang_COUNTRY */ if (key_lang && key_ctry && strcmp(env_lang, key_lang) == 0 && strcmp(env_ctry, key_ctry) == 0 && *current_level < MATCH_LANG_COUNTRY) { *current_level = MATCH_LANG_COUNTRY; return True; } else if (key_lang && /* lang */ strcmp(env_lang, key_lang) == 0 && *current_level < MATCH_LANG) { *current_level = MATCH_LANG; return True; } else { return False; } } /* LC_MESSAGES value: lang@MODIFIER */ if (env_lang && env_mod) { /* lang@MODIFIER */ if (key_lang && key_mod && strcmp(env_lang, key_lang) == 0 && strcmp(env_mod, key_mod) == 0 && *current_level < MATCH_LANG_MODIFIER) { *current_level = MATCH_LANG_MODIFIER; return True; } else if (key_lang && /* lang */ strcmp(env_lang, key_lang) == 0 && *current_level < MATCH_LANG) { *current_level = MATCH_LANG; return True; } else { return False; } } /* LC_MESSAGES value: lang */ if (env_lang) { /* lang */ if (key_lang && strcmp(env_lang, key_lang) == 0 && *current_level < MATCH_LANG) { *current_level = MATCH_LANG; return True; } else { return False; } } /* MATCH_DEFAULT is handled in getLocalizedStringValue */ return False; } /* get the (first) xdg main category from a list of categories */ static void getMenuHierarchyFor(char **xdgmenuspec) { char *category, *p; char buf[1024]; if (!*xdgmenuspec || !**xdgmenuspec) return; category = wstrdup(*xdgmenuspec); wfree(*xdgmenuspec); memset(buf, 0, sizeof(buf)); p = strtok(category, ";"); while (p) { /* get a known category */ if (strcmp(p, "AudioVideo") == 0) { snprintf(buf, sizeof(buf), "%s", _("Audio & Video")); break; } else if (strcmp(p, "Audio") == 0) { snprintf(buf, sizeof(buf), "%s", _("Audio")); break; } else if (strcmp(p, "Video") == 0) { snprintf(buf, sizeof(buf), "%s", _("Video")); break; } else if (strcmp(p, "Development") == 0) { snprintf(buf, sizeof(buf), "%s", _("Development")); break; } else if (strcmp(p, "Education") == 0) { snprintf(buf, sizeof(buf), "%s", _("Education")); break; } else if (strcmp(p, "Game") == 0) { snprintf(buf, sizeof(buf), "%s", _("Game")); break; } else if (strcmp(p, "Graphics") == 0) { snprintf(buf, sizeof(buf), "%s", _("Graphics")); break; } else if (strcmp(p, "Network") == 0) { snprintf(buf, sizeof(buf), "%s", _("Network")); break; } else if (strcmp(p, "Office") == 0) { snprintf(buf, sizeof(buf), "%s", _("Office")); break; } else if (strcmp(p, "Science") == 0) { snprintf(buf, sizeof(buf), "%s", _("Science")); break; } else if (strcmp(p, "Settings") == 0) { snprintf(buf, sizeof(buf), "%s", _("Settings")); break; } else if (strcmp(p, "System") == 0) { snprintf(buf, sizeof(buf), "%s", _("System")); break; } else if (strcmp(p, "Utility") == 0) { snprintf(buf, sizeof(buf), "%s", _("Utility")); break; /* reserved categories */ } else if (strcmp(p, "Screensaver") == 0) { snprintf(buf, sizeof(buf), "%s", _("Screensaver")); break; } else if (strcmp(p, "TrayIcon") == 0) { snprintf(buf, sizeof(buf), "%s", _("Tray Icon")); break; } else if (strcmp(p, "Applet") == 0) { snprintf(buf, sizeof(buf), "%s", _("Applet")); break; } else if (strcmp(p, "Shell") == 0) { snprintf(buf, sizeof(buf), "%s", _("Shell")); break; } p = strtok(NULL, ";"); } if (!*buf) /* come up with something if nothing found */ snprintf(buf, sizeof(buf), "%s", _("Other")); *xdgmenuspec = wstrdup(buf); }
roblillack/wmaker
b32ccee5cb128bf234e3d25a87160de1763a0645
Undo XDG string-escaping when generating menu-entries.
diff --git a/util/wmmenugen_parse_xdg.c b/util/wmmenugen_parse_xdg.c index adb47ca..02c7b00 100644 --- a/util/wmmenugen_parse_xdg.c +++ b/util/wmmenugen_parse_xdg.c @@ -1,563 +1,584 @@ /* * wmmenugen - Window Maker PropList menu generator * * Desktop Entry Specification parser functions * * Copyright (c) 2010. Tamas Tevesz <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ /* * http://standards.freedesktop.org/desktop-entry-spec/desktop-entry-spec-1.1.html * http://standards.freedesktop.org/menu-spec/menu-spec-1.1.html * * We will only deal with Type == "Application" entries in [Desktop Entry] * groups. Since there is no passing of file name arguments or anything of * the sort to applications from the menu, execname is determined as follows: * - If `TryExec' is present, use that; * - else use `Exec' with any switches stripped * * Only the (first, though there should not be more than one) `Main Category' * is used to place the entry in a submenu. * * Basic validation of the .desktop file is done. */ #include <sys/types.h> #include <sys/stat.h> #include <ctype.h> #include <ftw.h> #if DEBUG #include <errno.h> #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include "wmmenugen.h" /* LocaleString match levels */ enum { MATCH_DEFAULT, MATCH_LANG, MATCH_LANG_MODIFIER, MATCH_LANG_COUNTRY, MATCH_LANG_COUNTRY_MODIFIER }; typedef struct { char *Name; /* Name */ /* localestring */ int MatchLevel; /* LocaleString match type */ /* int */ char *TryExec; /* TryExec */ /* string */ char *Exec; /* Exec */ /* string */ char *Path; /* Path */ /* string */ int Flags; /* Flags */ char *Category; /* Categories (first item only) */ /* string */ } XDGMenuEntry; static void getKey(char **target, const char *line); static void getStringValue(char **target, const char *line); static void getLocalizedStringValue(char **target, const char *line, int *match_level); static int getBooleanValue(const char *line); static void getMenuHierarchyFor(char **xdgmenuspec); static int compare_matchlevel(int *current_level, const char *found_locale); static Bool xdg_to_wm(XDGMenuEntry *xdg, WMMenuEntry *wmentry); static void init_xdg_storage(XDGMenuEntry *xdg); static void init_wm_storage(WMMenuEntry *wm); void parse_xdg(const char *file, cb_add_menu_entry *addWMMenuEntryCallback) { FILE *fp; char buf[1024]; char *p, *tmp, *key; WMMenuEntry *wm; XDGMenuEntry *xdg; int InGroup; fp = fopen(file, "r"); if (!fp) { #if DEBUG fprintf(stderr, "Error opening file %s: %s\n", file, strerror(errno)); #endif return; } xdg = (XDGMenuEntry *)wmalloc(sizeof(XDGMenuEntry)); wm = (WMMenuEntry *)wmalloc(sizeof(WMMenuEntry)); InGroup = 0; memset(buf, 0, sizeof(buf)); while (fgets(buf, sizeof(buf), fp)) { p = buf; /* skip whitespaces */ while (isspace(*p)) p++; /* skip comments, empty lines */ if (*p == '\r' || *p == '\n' || *p == '#') { memset(buf, 0, sizeof(buf)); continue; } /* trim crlf */ buf[strcspn(buf, "\r\n")] = '\0'; if (strlen(buf) == 0) continue; if (strcmp(p, "[Desktop Entry]") == 0) { /* if currently processing a group, we've just hit the * end of its definition, try processing it */ if (InGroup && xdg_to_wm(xdg, wm)) { (*addWMMenuEntryCallback)(wm); } init_xdg_storage(xdg); init_wm_storage(wm); InGroup = 1; /* start processing group */ memset(buf, 0, sizeof(buf)); continue; } else if (p[0] == '[') { /* If we find a new group and the previous group was the main one, * we stop all further processing */ if (InGroup) break; } if (!InGroup) { memset(buf, 0, sizeof(buf)); continue; } getKey(&key, p); if (key == NULL) { /* not `key' = `value' */ memset(buf, 0, sizeof(buf)); continue; } if (strcmp(key, "Type") == 0) { getStringValue(&tmp, p); if (strcmp(tmp, "Application") != 0) InGroup = 0; /* if not application, skip current group */ wfree(tmp); tmp = NULL; } else if (strcmp(key, "Name") == 0) { getLocalizedStringValue(&xdg->Name, p, &xdg->MatchLevel); } else if (strcmp(key, "NoDisplay") == 0) { if (getBooleanValue(p)) /* if nodisplay, skip current group */ InGroup = 0; } else if (strcmp(key, "Hidden") == 0) { if (getBooleanValue(p)) InGroup = 0; /* if hidden, skip current group */ } else if (strcmp(key, "TryExec") == 0) { getStringValue(&xdg->TryExec, p); } else if (strcmp(key, "Exec") == 0) { getStringValue(&xdg->Exec, p); } else if (strcmp(key, "Path") == 0) { getStringValue(&xdg->Path, p); } else if (strcmp(key, "Terminal") == 0) { if (getBooleanValue(p)) xdg->Flags |= F_TERMINAL; } else if (strcmp(key, "Categories") == 0) { getStringValue(&xdg->Category, p); getMenuHierarchyFor(&xdg->Category); } if (xdg->Category == NULL) xdg->Category = wstrdup(_("Other")); wfree(key); key = NULL; } fclose(fp); /* at the end of the file, might as well try to menuize what we have * unless there was no group at all or it was marked as hidden */ if (InGroup && xdg_to_wm(xdg, wm)) (*addWMMenuEntryCallback)(wm); } /* coerce an xdg entry type into a wm entry type */ static Bool xdg_to_wm(XDGMenuEntry *xdg, WMMenuEntry *wm) { char *p; /* Exec or TryExec is mandatory */ if (!(xdg->Exec || xdg->TryExec)) return False; /* if there's no Name, use the first word of Exec or TryExec */ if (xdg->Name) { wm->Name = xdg->Name; } else { if (xdg->Exec) wm->Name = wstrdup(xdg->Exec); else /* xdg->TryExec */ wm->Name = wstrdup(xdg->TryExec); p = strchr(wm->Name, ' '); if (p) *p = '\0'; } if (xdg->Exec) wm->CmdLine = xdg->Exec; else /* xdg->TryExec */ wm->CmdLine = xdg->TryExec; wm->SubMenu = xdg->Category; wm->Flags = xdg->Flags; return True; } /* (re-)initialize a XDGMenuEntry storage */ static void init_xdg_storage(XDGMenuEntry *xdg) { if (xdg->Name) wfree(xdg->Name); if (xdg->TryExec) wfree(xdg->TryExec); if (xdg->Exec) wfree(xdg->Exec); if (xdg->Category) wfree(xdg->Category); if (xdg->Path) wfree(xdg->Path); xdg->Name = NULL; xdg->TryExec = NULL; xdg->Exec = NULL; xdg->Category = NULL; xdg->Path = NULL; xdg->Flags = 0; xdg->MatchLevel = -1; } /* (re-)initialize a WMMenuEntry storage */ static void init_wm_storage(WMMenuEntry *wm) { wm->Name = NULL; wm->CmdLine = NULL; wm->Flags = 0; } /* get a key from line. allocates target, which must be wfreed later */ static void getKey(char **target, const char *line) { const char *p; int kstart, kend; p = line; if (strchr(p, '=') == NULL) { /* not `key' = `value' */ *target = NULL; return; } kstart = 0; /* skip whitespace */ while (isspace(*(p + kstart))) kstart++; /* skip up until first whitespace or '[' (localestring) or '=' */ kend = kstart + 1; while (*(p + kend) && !isspace(*(p + kend)) && *(p + kend) != '=' && *(p + kend) != '[') kend++; *target = wstrndup(p + kstart, kend - kstart); } /* get a string value from line. allocates target, which must be wfreed later. */ static void getStringValue(char **target, const char *line) { const char *p; + char *q; int kstart; p = line; kstart = 0; /* skip until after '=' */ while (*(p + kstart) && *(p + kstart) != '=') kstart++; kstart++; /* skip whitespace */ while (*(p + kstart) && isspace(*(p + kstart))) kstart++; *target = wstrdup(p + kstart); + + for (p = q = *target; *p; p++) { + if (*p != '\\') { + *q++ = *p; + } else { + switch (*++p) { + case 's': *q++ = ' '; break; + case 'n': *q++ = '\n'; break; + case 't': *q++ = '\t'; break; + case 'r': *q++ = '\r'; break; + case '\\': *q++ = '\\'; break; + default: + /* + * Skip invalid escape. + */ + break; + } + } + } + *q = '\0'; } /* get a localized string value from line. allocates target, which must be wfreed later. * matching is dependent on the current value of target as well as on the * level the current value is matched on. guts matching algorithm is in * compare_matchlevel(). */ static void getLocalizedStringValue(char **target, const char *line, int *match_level) { const char *p; char *locale; int kstart; int sqbstart, sqbend; p = line; kstart = 0; sqbstart = 0; sqbend = 0; locale = NULL; /* skip until after '=', mark if '[' and ']' is found */ while (*(p + kstart) && *(p + kstart) != '=') { switch (*(p + kstart)) { case '[': sqbstart = kstart + 1;break; case ']': sqbend = kstart; break; default : break; } kstart++; } kstart++; /* skip whitespace */ while (isspace(*(p + kstart))) kstart++; if (sqbstart > 0 && sqbend > sqbstart) locale = wstrndup(p + sqbstart, sqbend - sqbstart); /* if there is no value yet and this is the default key, return */ if (!*target && !locale) { *match_level = MATCH_DEFAULT; *target = wstrdup(p + kstart); return; } if (compare_matchlevel(match_level, locale)) { wfree(locale); *target = wstrdup(p + kstart); return; } return; } /* get a boolean value from line */ static Bool getBooleanValue(const char *line) { char *p; int ret; getStringValue(&p, line); ret = strcmp(p, "true") == 0 ? True : False; wfree(p); return ret; } /* perform locale matching by implementing the algorithm specified in * xdg desktop entry specification, section "localized values for keys". */ static Bool compare_matchlevel(int *current_level, const char *found_locale) { /* current key locale */ char *key_lang, *key_ctry, *key_enc, *key_mod; parse_locale(found_locale, &key_lang, &key_ctry, &key_enc, &key_mod); if (env_lang && key_lang && /* Shortcut: if key and env languages don't match, */ strcmp(env_lang, key_lang) != 0) /* don't even bother. This takes care of the great */ return False; /* majority of the cases without having to go through */ /* the more theoretical parts of the spec'd algo. */ if (!env_mod && key_mod) /* If LC_MESSAGES does not have a MODIFIER field, */ return False; /* then no key with a modifier will be matched. */ if (!env_ctry && key_ctry) /* Similarly, if LC_MESSAGES does not have a COUNTRY field, */ return False; /* then no key with a country specified will be matched. */ /* LC_MESSAGES value: lang_COUNTRY@MODIFIER */ if (env_lang && env_ctry && env_mod) { /* lang_COUNTRY@MODIFIER */ if (key_lang && key_ctry && key_mod && strcmp(env_lang, key_lang) == 0 && strcmp(env_ctry, key_ctry) == 0 && strcmp(env_mod, key_mod) == 0) { *current_level = MATCH_LANG_COUNTRY_MODIFIER; return True; } else if (key_lang && key_ctry && /* lang_COUNTRY */ strcmp(env_lang, key_lang) == 0 && strcmp(env_ctry, key_ctry) == 0 && *current_level < MATCH_LANG_COUNTRY) { *current_level = MATCH_LANG_COUNTRY; return True; } else if (key_lang && key_mod && /* lang@MODIFIER */ strcmp(env_lang, key_lang) == 0 && strcmp(env_mod, key_mod) == 0 && *current_level < MATCH_LANG_MODIFIER) { *current_level = MATCH_LANG_MODIFIER; return True; } else if (key_lang && /* lang */ strcmp(env_lang, key_lang) == 0 && *current_level < MATCH_LANG) { *current_level = MATCH_LANG; return True; } else { return False; } } /* LC_MESSAGES value: lang_COUNTRY */ if (env_lang && env_ctry) { /* lang_COUNTRY */ if (key_lang && key_ctry && strcmp(env_lang, key_lang) == 0 && strcmp(env_ctry, key_ctry) == 0 && *current_level < MATCH_LANG_COUNTRY) { *current_level = MATCH_LANG_COUNTRY; return True; } else if (key_lang && /* lang */ strcmp(env_lang, key_lang) == 0 && *current_level < MATCH_LANG) { *current_level = MATCH_LANG; return True; } else { return False; } } /* LC_MESSAGES value: lang@MODIFIER */ if (env_lang && env_mod) { /* lang@MODIFIER */ if (key_lang && key_mod && strcmp(env_lang, key_lang) == 0 && strcmp(env_mod, key_mod) == 0 && *current_level < MATCH_LANG_MODIFIER) { *current_level = MATCH_LANG_MODIFIER; return True; } else if (key_lang && /* lang */ strcmp(env_lang, key_lang) == 0 && *current_level < MATCH_LANG) { *current_level = MATCH_LANG; return True; } else { return False; } } /* LC_MESSAGES value: lang */ if (env_lang) { /* lang */ if (key_lang && strcmp(env_lang, key_lang) == 0 && *current_level < MATCH_LANG) { *current_level = MATCH_LANG; return True; } else { return False; } } /* MATCH_DEFAULT is handled in getLocalizedStringValue */ return False; } /* get the (first) xdg main category from a list of categories */ static void getMenuHierarchyFor(char **xdgmenuspec) { char *category, *p; char buf[1024]; if (!*xdgmenuspec || !**xdgmenuspec) return; category = wstrdup(*xdgmenuspec); wfree(*xdgmenuspec); memset(buf, 0, sizeof(buf)); p = strtok(category, ";"); while (p) { /* get a known category */ if (strcmp(p, "AudioVideo") == 0) { snprintf(buf, sizeof(buf), "%s", _("Audio & Video")); break; } else if (strcmp(p, "Audio") == 0) { snprintf(buf, sizeof(buf), "%s", _("Audio")); break; } else if (strcmp(p, "Video") == 0) { snprintf(buf, sizeof(buf), "%s", _("Video")); break; } else if (strcmp(p, "Development") == 0) { snprintf(buf, sizeof(buf), "%s", _("Development")); break; } else if (strcmp(p, "Education") == 0) { snprintf(buf, sizeof(buf), "%s", _("Education")); break; } else if (strcmp(p, "Game") == 0) { snprintf(buf, sizeof(buf), "%s", _("Game")); break; } else if (strcmp(p, "Graphics") == 0) { snprintf(buf, sizeof(buf), "%s", _("Graphics")); break; } else if (strcmp(p, "Network") == 0) { snprintf(buf, sizeof(buf), "%s", _("Network")); break; } else if (strcmp(p, "Office") == 0) { snprintf(buf, sizeof(buf), "%s", _("Office")); break; } else if (strcmp(p, "Science") == 0) { snprintf(buf, sizeof(buf), "%s", _("Science")); break; } else if (strcmp(p, "Settings") == 0) { snprintf(buf, sizeof(buf), "%s", _("Settings")); break; } else if (strcmp(p, "System") == 0) { snprintf(buf, sizeof(buf), "%s", _("System")); break; } else if (strcmp(p, "Utility") == 0) { snprintf(buf, sizeof(buf), "%s", _("Utility")); break; /* reserved categories */ } else if (strcmp(p, "Screensaver") == 0) { snprintf(buf, sizeof(buf), "%s", _("Screensaver")); break; } else if (strcmp(p, "TrayIcon") == 0) { snprintf(buf, sizeof(buf), "%s", _("Tray Icon")); break; } else if (strcmp(p, "Applet") == 0) { snprintf(buf, sizeof(buf), "%s", _("Applet")); break; } else if (strcmp(p, "Shell") == 0) { snprintf(buf, sizeof(buf), "%s", _("Shell")); break; } p = strtok(NULL, ";"); } if (!*buf) /* come up with something if nothing found */ snprintf(buf, sizeof(buf), "%s", _("Other")); *xdgmenuspec = wstrdup(buf); }
roblillack/wmaker
6734646265775b63d3f4c1eb31c99d2f8aef5545
Use pointers as parameters instead of pointer-to-pointers.
diff --git a/util/wmmenugen_parse_xdg.c b/util/wmmenugen_parse_xdg.c index 3272ee6..adb47ca 100644 --- a/util/wmmenugen_parse_xdg.c +++ b/util/wmmenugen_parse_xdg.c @@ -1,563 +1,563 @@ /* * wmmenugen - Window Maker PropList menu generator * * Desktop Entry Specification parser functions * * Copyright (c) 2010. Tamas Tevesz <[email protected]> * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ /* * http://standards.freedesktop.org/desktop-entry-spec/desktop-entry-spec-1.1.html * http://standards.freedesktop.org/menu-spec/menu-spec-1.1.html * * We will only deal with Type == "Application" entries in [Desktop Entry] * groups. Since there is no passing of file name arguments or anything of * the sort to applications from the menu, execname is determined as follows: * - If `TryExec' is present, use that; * - else use `Exec' with any switches stripped * * Only the (first, though there should not be more than one) `Main Category' * is used to place the entry in a submenu. * * Basic validation of the .desktop file is done. */ #include <sys/types.h> #include <sys/stat.h> #include <ctype.h> #include <ftw.h> #if DEBUG #include <errno.h> #endif #include <stdio.h> #include <stdlib.h> #include <string.h> #include "wmmenugen.h" /* LocaleString match levels */ enum { MATCH_DEFAULT, MATCH_LANG, MATCH_LANG_MODIFIER, MATCH_LANG_COUNTRY, MATCH_LANG_COUNTRY_MODIFIER }; typedef struct { char *Name; /* Name */ /* localestring */ int MatchLevel; /* LocaleString match type */ /* int */ char *TryExec; /* TryExec */ /* string */ char *Exec; /* Exec */ /* string */ char *Path; /* Path */ /* string */ int Flags; /* Flags */ char *Category; /* Categories (first item only) */ /* string */ } XDGMenuEntry; static void getKey(char **target, const char *line); static void getStringValue(char **target, const char *line); static void getLocalizedStringValue(char **target, const char *line, int *match_level); static int getBooleanValue(const char *line); static void getMenuHierarchyFor(char **xdgmenuspec); static int compare_matchlevel(int *current_level, const char *found_locale); -static Bool xdg_to_wm(XDGMenuEntry **xdg, WMMenuEntry **wmentry); -static void init_xdg_storage(XDGMenuEntry **xdg); -static void init_wm_storage(WMMenuEntry **wm); +static Bool xdg_to_wm(XDGMenuEntry *xdg, WMMenuEntry *wmentry); +static void init_xdg_storage(XDGMenuEntry *xdg); +static void init_wm_storage(WMMenuEntry *wm); void parse_xdg(const char *file, cb_add_menu_entry *addWMMenuEntryCallback) { FILE *fp; char buf[1024]; char *p, *tmp, *key; WMMenuEntry *wm; XDGMenuEntry *xdg; int InGroup; fp = fopen(file, "r"); if (!fp) { #if DEBUG fprintf(stderr, "Error opening file %s: %s\n", file, strerror(errno)); #endif return; } xdg = (XDGMenuEntry *)wmalloc(sizeof(XDGMenuEntry)); wm = (WMMenuEntry *)wmalloc(sizeof(WMMenuEntry)); InGroup = 0; memset(buf, 0, sizeof(buf)); while (fgets(buf, sizeof(buf), fp)) { p = buf; /* skip whitespaces */ while (isspace(*p)) p++; /* skip comments, empty lines */ if (*p == '\r' || *p == '\n' || *p == '#') { memset(buf, 0, sizeof(buf)); continue; } /* trim crlf */ buf[strcspn(buf, "\r\n")] = '\0'; if (strlen(buf) == 0) continue; if (strcmp(p, "[Desktop Entry]") == 0) { /* if currently processing a group, we've just hit the * end of its definition, try processing it */ - if (InGroup && xdg_to_wm(&xdg, &wm)) { + if (InGroup && xdg_to_wm(xdg, wm)) { (*addWMMenuEntryCallback)(wm); } - init_xdg_storage(&xdg); - init_wm_storage(&wm); + init_xdg_storage(xdg); + init_wm_storage(wm); InGroup = 1; /* start processing group */ memset(buf, 0, sizeof(buf)); continue; } else if (p[0] == '[') { /* If we find a new group and the previous group was the main one, * we stop all further processing */ if (InGroup) break; } if (!InGroup) { memset(buf, 0, sizeof(buf)); continue; } getKey(&key, p); if (key == NULL) { /* not `key' = `value' */ memset(buf, 0, sizeof(buf)); continue; } if (strcmp(key, "Type") == 0) { getStringValue(&tmp, p); if (strcmp(tmp, "Application") != 0) InGroup = 0; /* if not application, skip current group */ wfree(tmp); tmp = NULL; } else if (strcmp(key, "Name") == 0) { getLocalizedStringValue(&xdg->Name, p, &xdg->MatchLevel); } else if (strcmp(key, "NoDisplay") == 0) { if (getBooleanValue(p)) /* if nodisplay, skip current group */ InGroup = 0; } else if (strcmp(key, "Hidden") == 0) { if (getBooleanValue(p)) InGroup = 0; /* if hidden, skip current group */ } else if (strcmp(key, "TryExec") == 0) { getStringValue(&xdg->TryExec, p); } else if (strcmp(key, "Exec") == 0) { getStringValue(&xdg->Exec, p); } else if (strcmp(key, "Path") == 0) { getStringValue(&xdg->Path, p); } else if (strcmp(key, "Terminal") == 0) { if (getBooleanValue(p)) xdg->Flags |= F_TERMINAL; } else if (strcmp(key, "Categories") == 0) { getStringValue(&xdg->Category, p); getMenuHierarchyFor(&xdg->Category); } if (xdg->Category == NULL) xdg->Category = wstrdup(_("Other")); wfree(key); key = NULL; } fclose(fp); /* at the end of the file, might as well try to menuize what we have * unless there was no group at all or it was marked as hidden */ - if (InGroup && xdg_to_wm(&xdg, &wm)) + if (InGroup && xdg_to_wm(xdg, wm)) (*addWMMenuEntryCallback)(wm); } /* coerce an xdg entry type into a wm entry type */ -static Bool xdg_to_wm(XDGMenuEntry **xdg, WMMenuEntry **wm) +static Bool xdg_to_wm(XDGMenuEntry *xdg, WMMenuEntry *wm) { char *p; /* Exec or TryExec is mandatory */ - if (!((*xdg)->Exec || (*xdg)->TryExec)) + if (!(xdg->Exec || xdg->TryExec)) return False; /* if there's no Name, use the first word of Exec or TryExec */ - if ((*xdg)->Name) { - (*wm)->Name = (*xdg)->Name; + if (xdg->Name) { + wm->Name = xdg->Name; } else { - if ((*xdg)->Exec) - (*wm)->Name = wstrdup((*xdg)->Exec); - else /* (*xdg)->TryExec */ - (*wm)->Name = wstrdup((*xdg)->TryExec); + if (xdg->Exec) + wm->Name = wstrdup(xdg->Exec); + else /* xdg->TryExec */ + wm->Name = wstrdup(xdg->TryExec); - p = strchr((*wm)->Name, ' '); + p = strchr(wm->Name, ' '); if (p) *p = '\0'; } - if ((*xdg)->Exec) - (*wm)->CmdLine = (*xdg)->Exec; - else /* (*xdg)->TryExec */ - (*wm)->CmdLine = (*xdg)->TryExec; + if (xdg->Exec) + wm->CmdLine = xdg->Exec; + else /* xdg->TryExec */ + wm->CmdLine = xdg->TryExec; - (*wm)->SubMenu = (*xdg)->Category; - (*wm)->Flags = (*xdg)->Flags; + wm->SubMenu = xdg->Category; + wm->Flags = xdg->Flags; return True; } /* (re-)initialize a XDGMenuEntry storage */ -static void init_xdg_storage(XDGMenuEntry **xdg) +static void init_xdg_storage(XDGMenuEntry *xdg) { - if ((*xdg)->Name) - wfree((*xdg)->Name); - if ((*xdg)->TryExec) - wfree((*xdg)->TryExec); - if ((*xdg)->Exec) - wfree((*xdg)->Exec); - if ((*xdg)->Category) - wfree((*xdg)->Category); - if ((*xdg)->Path) - wfree((*xdg)->Path); - - (*xdg)->Name = NULL; - (*xdg)->TryExec = NULL; - (*xdg)->Exec = NULL; - (*xdg)->Category = NULL; - (*xdg)->Path = NULL; - (*xdg)->Flags = 0; - (*xdg)->MatchLevel = -1; + if (xdg->Name) + wfree(xdg->Name); + if (xdg->TryExec) + wfree(xdg->TryExec); + if (xdg->Exec) + wfree(xdg->Exec); + if (xdg->Category) + wfree(xdg->Category); + if (xdg->Path) + wfree(xdg->Path); + + xdg->Name = NULL; + xdg->TryExec = NULL; + xdg->Exec = NULL; + xdg->Category = NULL; + xdg->Path = NULL; + xdg->Flags = 0; + xdg->MatchLevel = -1; } /* (re-)initialize a WMMenuEntry storage */ -static void init_wm_storage(WMMenuEntry **wm) +static void init_wm_storage(WMMenuEntry *wm) { - (*wm)->Name = NULL; - (*wm)->CmdLine = NULL; - (*wm)->Flags = 0; + wm->Name = NULL; + wm->CmdLine = NULL; + wm->Flags = 0; } /* get a key from line. allocates target, which must be wfreed later */ static void getKey(char **target, const char *line) { const char *p; int kstart, kend; p = line; if (strchr(p, '=') == NULL) { /* not `key' = `value' */ *target = NULL; return; } kstart = 0; /* skip whitespace */ while (isspace(*(p + kstart))) kstart++; /* skip up until first whitespace or '[' (localestring) or '=' */ kend = kstart + 1; while (*(p + kend) && !isspace(*(p + kend)) && *(p + kend) != '=' && *(p + kend) != '[') kend++; *target = wstrndup(p + kstart, kend - kstart); } /* get a string value from line. allocates target, which must be wfreed later. */ static void getStringValue(char **target, const char *line) { const char *p; int kstart; p = line; kstart = 0; /* skip until after '=' */ while (*(p + kstart) && *(p + kstart) != '=') kstart++; kstart++; /* skip whitespace */ while (*(p + kstart) && isspace(*(p + kstart))) kstart++; *target = wstrdup(p + kstart); } /* get a localized string value from line. allocates target, which must be wfreed later. * matching is dependent on the current value of target as well as on the * level the current value is matched on. guts matching algorithm is in * compare_matchlevel(). */ static void getLocalizedStringValue(char **target, const char *line, int *match_level) { const char *p; char *locale; int kstart; int sqbstart, sqbend; p = line; kstart = 0; sqbstart = 0; sqbend = 0; locale = NULL; /* skip until after '=', mark if '[' and ']' is found */ while (*(p + kstart) && *(p + kstart) != '=') { switch (*(p + kstart)) { case '[': sqbstart = kstart + 1;break; case ']': sqbend = kstart; break; default : break; } kstart++; } kstart++; /* skip whitespace */ while (isspace(*(p + kstart))) kstart++; if (sqbstart > 0 && sqbend > sqbstart) locale = wstrndup(p + sqbstart, sqbend - sqbstart); /* if there is no value yet and this is the default key, return */ if (!*target && !locale) { *match_level = MATCH_DEFAULT; *target = wstrdup(p + kstart); return; } if (compare_matchlevel(match_level, locale)) { wfree(locale); *target = wstrdup(p + kstart); return; } return; } /* get a boolean value from line */ static Bool getBooleanValue(const char *line) { char *p; int ret; getStringValue(&p, line); ret = strcmp(p, "true") == 0 ? True : False; wfree(p); return ret; } /* perform locale matching by implementing the algorithm specified in * xdg desktop entry specification, section "localized values for keys". */ static Bool compare_matchlevel(int *current_level, const char *found_locale) { /* current key locale */ char *key_lang, *key_ctry, *key_enc, *key_mod; parse_locale(found_locale, &key_lang, &key_ctry, &key_enc, &key_mod); if (env_lang && key_lang && /* Shortcut: if key and env languages don't match, */ strcmp(env_lang, key_lang) != 0) /* don't even bother. This takes care of the great */ return False; /* majority of the cases without having to go through */ /* the more theoretical parts of the spec'd algo. */ if (!env_mod && key_mod) /* If LC_MESSAGES does not have a MODIFIER field, */ return False; /* then no key with a modifier will be matched. */ if (!env_ctry && key_ctry) /* Similarly, if LC_MESSAGES does not have a COUNTRY field, */ return False; /* then no key with a country specified will be matched. */ /* LC_MESSAGES value: lang_COUNTRY@MODIFIER */ if (env_lang && env_ctry && env_mod) { /* lang_COUNTRY@MODIFIER */ if (key_lang && key_ctry && key_mod && strcmp(env_lang, key_lang) == 0 && strcmp(env_ctry, key_ctry) == 0 && strcmp(env_mod, key_mod) == 0) { *current_level = MATCH_LANG_COUNTRY_MODIFIER; return True; } else if (key_lang && key_ctry && /* lang_COUNTRY */ strcmp(env_lang, key_lang) == 0 && strcmp(env_ctry, key_ctry) == 0 && *current_level < MATCH_LANG_COUNTRY) { *current_level = MATCH_LANG_COUNTRY; return True; } else if (key_lang && key_mod && /* lang@MODIFIER */ strcmp(env_lang, key_lang) == 0 && strcmp(env_mod, key_mod) == 0 && *current_level < MATCH_LANG_MODIFIER) { *current_level = MATCH_LANG_MODIFIER; return True; } else if (key_lang && /* lang */ strcmp(env_lang, key_lang) == 0 && *current_level < MATCH_LANG) { *current_level = MATCH_LANG; return True; } else { return False; } } /* LC_MESSAGES value: lang_COUNTRY */ if (env_lang && env_ctry) { /* lang_COUNTRY */ if (key_lang && key_ctry && strcmp(env_lang, key_lang) == 0 && strcmp(env_ctry, key_ctry) == 0 && *current_level < MATCH_LANG_COUNTRY) { *current_level = MATCH_LANG_COUNTRY; return True; } else if (key_lang && /* lang */ strcmp(env_lang, key_lang) == 0 && *current_level < MATCH_LANG) { *current_level = MATCH_LANG; return True; } else { return False; } } /* LC_MESSAGES value: lang@MODIFIER */ if (env_lang && env_mod) { /* lang@MODIFIER */ if (key_lang && key_mod && strcmp(env_lang, key_lang) == 0 && strcmp(env_mod, key_mod) == 0 && *current_level < MATCH_LANG_MODIFIER) { *current_level = MATCH_LANG_MODIFIER; return True; } else if (key_lang && /* lang */ strcmp(env_lang, key_lang) == 0 && *current_level < MATCH_LANG) { *current_level = MATCH_LANG; return True; } else { return False; } } /* LC_MESSAGES value: lang */ if (env_lang) { /* lang */ if (key_lang && strcmp(env_lang, key_lang) == 0 && *current_level < MATCH_LANG) { *current_level = MATCH_LANG; return True; } else { return False; } } /* MATCH_DEFAULT is handled in getLocalizedStringValue */ return False; } /* get the (first) xdg main category from a list of categories */ static void getMenuHierarchyFor(char **xdgmenuspec) { char *category, *p; char buf[1024]; if (!*xdgmenuspec || !**xdgmenuspec) return; category = wstrdup(*xdgmenuspec); wfree(*xdgmenuspec); memset(buf, 0, sizeof(buf)); p = strtok(category, ";"); while (p) { /* get a known category */ if (strcmp(p, "AudioVideo") == 0) { snprintf(buf, sizeof(buf), "%s", _("Audio & Video")); break; } else if (strcmp(p, "Audio") == 0) { snprintf(buf, sizeof(buf), "%s", _("Audio")); break; } else if (strcmp(p, "Video") == 0) { snprintf(buf, sizeof(buf), "%s", _("Video")); break; } else if (strcmp(p, "Development") == 0) { snprintf(buf, sizeof(buf), "%s", _("Development")); break; } else if (strcmp(p, "Education") == 0) { snprintf(buf, sizeof(buf), "%s", _("Education")); break; } else if (strcmp(p, "Game") == 0) { snprintf(buf, sizeof(buf), "%s", _("Game")); break; } else if (strcmp(p, "Graphics") == 0) { snprintf(buf, sizeof(buf), "%s", _("Graphics")); break; } else if (strcmp(p, "Network") == 0) { snprintf(buf, sizeof(buf), "%s", _("Network")); break; } else if (strcmp(p, "Office") == 0) { snprintf(buf, sizeof(buf), "%s", _("Office")); break; } else if (strcmp(p, "Science") == 0) { snprintf(buf, sizeof(buf), "%s", _("Science")); break; } else if (strcmp(p, "Settings") == 0) { snprintf(buf, sizeof(buf), "%s", _("Settings")); break; } else if (strcmp(p, "System") == 0) { snprintf(buf, sizeof(buf), "%s", _("System")); break; } else if (strcmp(p, "Utility") == 0) { snprintf(buf, sizeof(buf), "%s", _("Utility")); break; /* reserved categories */ } else if (strcmp(p, "Screensaver") == 0) { snprintf(buf, sizeof(buf), "%s", _("Screensaver")); break; } else if (strcmp(p, "TrayIcon") == 0) { snprintf(buf, sizeof(buf), "%s", _("Tray Icon")); break; } else if (strcmp(p, "Applet") == 0) { snprintf(buf, sizeof(buf), "%s", _("Applet")); break; } else if (strcmp(p, "Shell") == 0) { snprintf(buf, sizeof(buf), "%s", _("Shell")); break; } p = strtok(NULL, ";"); } if (!*buf) /* come up with something if nothing found */ snprintf(buf, sizeof(buf), "%s", _("Other")); *xdgmenuspec = wstrdup(buf); }