<commit_before>#include "connection_manager.hpp"
#include "constants.hpp"
#include "filesystem.hpp"
#include "grabber_alerts_monitor.hpp"
#include "karabiner_version.h"
#include "logger.hpp"
#include "migration.hpp"
#include "process_utility.hpp"
#include "spdlog_utility.hpp"
#include "thread_utility.hpp"
#include "update_utility.hpp"
#include "version_monitor.hpp"
#include "version_monitor_utility.hpp"
#include <spdlog/async.h>
#include <spdlog/sinks/rotating_file_sink.h>

namespace krbn {
class karabiner_console_user_server final {
public:
  karabiner_console_user_server(void) {
    {
      auto log_directory = constants::get_user_log_directory();
      if (!log_directory.empty()) {
        filesystem::create_directory_with_intermediate_directories(log_directory, 0700);

        if (filesystem::is_directory(log_directory)) {
          std::string log_file_path = log_directory + "/console_user_server.log";
          auto l = spdlog::rotating_logger_mt<spdlog::async_factory>("console_user_server",
                                                                     log_file_path.c_str(),
                                                                     256 * 1024,
                                                                     3);
          l->flush_on(spdlog::level::info);
          l->set_pattern(spdlog_utility::get_pattern());
          logger::set_logger(l);
        }
      }
    }

    logger::get_logger().info("version {0}", karabiner_version);

    if (!process_utility::lock_single_application_with_user_pid_file("karabiner_console_user_server.pid")) {
      std::string message("Exit since another process is running.");
      logger::get_logger().info(message);
      std::cerr << message << std::endl;
      exit(0);
    }

    // ========================================

    grabber_alerts_monitor_ = std::make_unique<grabber_alerts_monitor>();

    grabber_alerts_monitor_->alerts_changed.connect([](auto&& alerts) {
      logger::get_logger().info("karabiner_grabber_alerts.json is updated.");
      if (!alerts.empty()) {
        application_launcher::launch_preferences();
      }
    });

    grabber_alerts_monitor_->start(constants::get_grabber_alerts_json_file_path());

    // ========================================

    migration::migrate_v1();

    // ========================================

    krbn::filesystem::create_directory_with_intermediate_directories(constants::get_user_configuration_directory(), 0700);
    krbn::filesystem::create_directory_with_intermediate_directories(constants::get_user_complex_modifications_assets_directory(), 0700);

    connection_manager_ = std::make_unique<connection_manager>();
  }

  ~karabiner_console_user_server(void) {
    connection_manager_ = nullptr;
    grabber_alerts_monitor_ = nullptr;
  }

private:
  std::unique_ptr<grabber_alerts_monitor> grabber_alerts_monitor_;
  std::unique_ptr<connection_manager> connection_manager_;
};
} // namespace krbn

int main(int argc, const char* argv[]) {
  signal(SIGUSR1, SIG_IGN);
  signal(SIGUSR2, SIG_IGN);
  krbn::thread_utility::register_main_thread();

  krbn::karabiner_console_user_server karabiner_console_user_server;

  krbn::update_utility::check_for_updates_on_startup();

  krbn::version_monitor_utility::start_monitor_to_stop_main_run_loop_when_version_changed();
  CFRunLoopRun();

  return 0;
}
<commit_msg>update for grabber_alerts_monitor interface change<commit_after>#include "connection_manager.hpp"
#include "constants.hpp"
#include "filesystem.hpp"
#include "grabber_alerts_monitor.hpp"
#include "karabiner_version.h"
#include "logger.hpp"
#include "migration.hpp"
#include "process_utility.hpp"
#include "spdlog_utility.hpp"
#include "thread_utility.hpp"
#include "update_utility.hpp"
#include <spdlog/async.h>
#include <spdlog/sinks/rotating_file_sink.h>

namespace krbn {
class karabiner_console_user_server final {
public:
  karabiner_console_user_server(void) {
    {
      auto log_directory = constants::get_user_log_directory();
      if (!log_directory.empty()) {
        filesystem::create_directory_with_intermediate_directories(log_directory, 0700);

        if (filesystem::is_directory(log_directory)) {
          std::string log_file_path = log_directory + "/console_user_server.log";
          auto l = spdlog::rotating_logger_mt<spdlog::async_factory>("console_user_server",
                                                                     log_file_path.c_str(),
                                                                     256 * 1024,
                                                                     3);
          l->flush_on(spdlog::level::info);
          l->set_pattern(spdlog_utility::get_pattern());
          logger::set_logger(l);
        }
      }
    }

    logger::get_logger().info("version {0}", karabiner_version);

    if (!process_utility::lock_single_application_with_user_pid_file("karabiner_console_user_server.pid")) {
      std::string message("Exit since another process is running.");
      logger::get_logger().info(message);
      std::cerr << message << std::endl;
      exit(0);
    }

    // ========================================

    grabber_alerts_monitor_ = std::make_unique<grabber_alerts_monitor>(constants::get_grabber_alerts_json_file_path());

    grabber_alerts_monitor_->alerts_changed.connect([](auto&& alerts) {
      logger::get_logger().info("karabiner_grabber_alerts.json is updated.");
      if (!alerts.empty()) {
        application_launcher::launch_preferences();
      }
    });

    grabber_alerts_monitor_->start();

    // ========================================

    migration::migrate_v1();

    // ========================================

    krbn::filesystem::create_directory_with_intermediate_directories(constants::get_user_configuration_directory(), 0700);
    krbn::filesystem::create_directory_with_intermediate_directories(constants::get_user_complex_modifications_assets_directory(), 0700);

    connection_manager_ = std::make_unique<connection_manager>();
  }

  ~karabiner_console_user_server(void) {
    connection_manager_ = nullptr;
    grabber_alerts_monitor_ = nullptr;
  }

private:
  std::unique_ptr<grabber_alerts_monitor> grabber_alerts_monitor_;
  std::unique_ptr<connection_manager> connection_manager_;
};
} // namespace krbn

int main(int argc, const char* argv[]) {
  signal(SIGUSR1, SIG_IGN);
  signal(SIGUSR2, SIG_IGN);
  krbn::thread_utility::register_main_thread();

  krbn::karabiner_console_user_server karabiner_console_user_server;

  krbn::update_utility::check_for_updates_on_startup();

  CFRunLoopRun();

  return 0;
}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: swlbox.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2004-08-12 12:58:39 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  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
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/

#pragma hdrstop

#ifndef _DEBUG_HXX //autogen
#include <tools/debug.hxx>
#endif
#ifndef _UNOTOOLS_CHARCLASS_HXX
#include <unotools/charclass.hxx>
#endif

#ifndef _SWTYPES_HXX
#include <swtypes.hxx>
#endif
#ifndef _SWLBOX_HXX
#include <swlbox.hxx>
#endif

SV_IMPL_PTRARR(SwEntryLst, SwBoxEntry*)

/*--------------------------------------------------------------------
     Beschreibung: Ein ListboxElement
 --------------------------------------------------------------------*/

SwBoxEntry::SwBoxEntry() :
    bModified(FALSE),
    bNew(FALSE),
    nId(LISTBOX_APPEND)
{
}

SwBoxEntry::SwBoxEntry(const String& aNam, USHORT nIdx) :
    bModified(FALSE),
    bNew(FALSE),
    aName(aNam),
    nId(nIdx)
{
}

SwBoxEntry::SwBoxEntry(const SwBoxEntry& rOld) :
    aName(rOld.aName),
    nId(rOld.nId),
    bNew(rOld.bNew),
    bModified(rOld.bModified)
{

}

/*--------------------------------------------------------------------
     Beschreibung:
 --------------------------------------------------------------------*/

/*SwListBox::SwListBox(Window* pParent, const ResId& rId):
    ListBox(pParent, rId)
{
    DBG_ASSERT( 0 == (ListBox::GetStyle() & WB_SORT), "NIE sortiert aus der Resource lesen!" );
    // falls eine Liste ueber die Resource gelesen wurde, die interne
    // entsprechend updaten
    USHORT nCnt = ListBox::GetEntryCount();
    for( USHORT n = 0; n < nCnt; ++n )
    {
        const SwBoxEntry* pTmp = new SwBoxEntry( ListBox::GetEntry( n ), n );
        aEntryLst.Insert( pTmp, n );
    }
}

/*--------------------------------------------------------------------
     Beschreibung: Basisklasse Dtor
 --------------------------------------------------------------------*/

/*SwListBox::~SwListBox()
{
}

/*--------------------------------------------------------------------
     Beschreibung: Listen loeschen und Anzeige loeschen
 --------------------------------------------------------------------*/

/*void SwListBox::Clear()
{
    ListBox::Clear();
    aEntryLst.DeleteAndDestroy( 0, aEntryLst.Count() );
}

/*--------------------------------------------------------------------
     Beschreibung: Rund um die Entries
 --------------------------------------------------------------------*/

/*const SwBoxEntry& SwListBox::GetEntry(USHORT nPos) const
{
    if( nPos < aEntryLst.Count() )
        return *aEntryLst[ nPos ];

    return aDefault;
}

/*--------------------------------------------------------------------
     Beschreibung: aktullen Eintrag zurueckgeben
 --------------------------------------------------------------------*/

/*const SwBoxEntry& SwListBox::GetSelectEntry() const
{
    USHORT nPos = ListBox::GetSelectEntryPos();
    if( nPos < aEntryLst.Count() )
        return *aEntryLst[ nPos ];

    return aDefault;
}

void SwListBox::RemoveEntry( USHORT nPos )
{
    if( nPos < aEntryLst.Count() )
    {
        aEntryLst.DeleteAndDestroy( nPos, 1 );
        ListBox::RemoveEntry( nPos );
    }
}

/*--------------------------------------------------------------------
     Beschreibung: Eintrag in die ListBox aufnehmen
 --------------------------------------------------------------------*/

/*void SwListBox::InsertEntry( const SwBoxEntry& rEntry, USHORT nPos )
{
    if( nPos >= aEntryLst.Count() )
        nPos = aEntryLst.Count();

    SwBoxEntry* pEntry = new SwBoxEntry( rEntry );
    ListBox::InsertEntry( pEntry->aName, nPos );
    aEntryLst.C40_INSERT( SwBoxEntry, pEntry, nPos );
}

/*--------------------------------------------------------------------
     Beschreibung: Sortiert einfuegen
 --------------------------------------------------------------------*/

/*void SwListBox::InsertEntrySort( const SwBoxEntry& rEntry )
{
    USHORT nPos;
    if( !SeekEntry( rEntry, &nPos ) )
    {
        SwBoxEntry* pEntry = new SwBoxEntry( rEntry );
        ListBox::InsertEntry( pEntry->aName, nPos );
        aEntryLst.C40_INSERT( SwBoxEntry, pEntry, nPos );
    }
}

BOOL SwListBox::SeekEntry( const SwBoxEntry& rEntry, USHORT* pPos )
{
    register USHORT nO = aEntryLst.Count(), nM, nU = 0;
    if( nO > 0 )
    {
        nO--;
        while( nU <= nO )
        {
            nM = nU + ( nO - nU ) / 2;
            StringCompare eCmp = aEntryLst[ nM ]->aName.ICompare( rEntry.aName );
            if( COMPARE_EQUAL == eCmp )
            {
                if( pPos ) *pPos = nM;
                return TRUE;
            }
            else if( COMPARE_GREATER == eCmp )
                nU = nM + 1;
            else if( nM == 0 )
                break;
            else
                nO = nM - 1;
        }
    }
    if( pPos ) *pPos = nU;
    return FALSE;
}

/*  */

SwComboBox::SwComboBox(Window* pParent, const ResId& rId, USHORT nStyleBits ):
    ComboBox(pParent, rId),
    nStyle(nStyleBits)
{
    // Verwaltung fuer die Stringlist aus der Resource aufbauen
    USHORT nSize = GetEntryCount();
    for( USHORT i=0; i < nSize; ++i )
    {
        const SwBoxEntry* pTmp = new SwBoxEntry(ComboBox::GetEntry(i), i);
        aEntryLst.Insert(pTmp, aEntryLst.Count() );
    }
}

/*--------------------------------------------------------------------
     Beschreibung: Basisklasse Dtor
 --------------------------------------------------------------------*/

SwComboBox::~SwComboBox()
{
// das erledigen die Listen doch schon selbst im DTOR!
//  aEntryLst.DeleteAndDestroy(0,   aEntryLst.Count());
//  aDelEntryLst.DeleteAndDestroy(0, aDelEntryLst.Count());
}

/*--------------------------------------------------------------------
     Beschreibung: Eintrag in die ComboBox aufnehmen
 --------------------------------------------------------------------*/

void SwComboBox::InsertEntry(const SwBoxEntry& rEntry)
{
    InsertSorted(new SwBoxEntry(rEntry));
}

/*--------------------------------------------------------------------
     Beschreibung: Eintrag aus der Liste loeschen
 --------------------------------------------------------------------*/

void SwComboBox::RemoveEntry(USHORT nPos)
{
    if(nPos >= aEntryLst.Count())
        return;

    // Altes Element austragen
    SwBoxEntry* pEntry = aEntryLst[nPos];
    aEntryLst.Remove(nPos, 1);
    ComboBox::RemoveEntry(nPos);

    // keine neuen Eintraege in die Liste mit aufnehmen
    if(pEntry->bNew)
        return;

    // in DeleteListe eintragen
    aDelEntryLst.C40_INSERT(SwBoxEntry, pEntry, aDelEntryLst.Count());
}

/*--------------------------------------------------------------------
     Beschreibung: Position by Name
 --------------------------------------------------------------------*/

USHORT SwComboBox::GetEntryPos(const SwBoxEntry& rEntry) const
{
    return ComboBox::GetEntryPos(rEntry.aName);
}

/*--------------------------------------------------------------------
     Beschreibung: Rund um die Entries
 --------------------------------------------------------------------*/

const SwBoxEntry& SwComboBox::GetEntry(USHORT nPos) const
{
    if(nPos < aEntryLst.Count())
        return *aEntryLst[nPos];

    return aDefault;
}

/*--------------------------------------------------------------------
     Beschreibung: geloeschte Eintraege
 --------------------------------------------------------------------*/

USHORT SwComboBox::GetRemovedCount() const
{
    return aDelEntryLst.Count();
}

const SwBoxEntry& SwComboBox::GetRemovedEntry(USHORT nPos) const
{
    if(nPos < aDelEntryLst.Count())
        return *aDelEntryLst[nPos];

    return aDefault;
}

/*--------------------------------------------------------------------
     Beschreibung: Sortiert einfuegen
 --------------------------------------------------------------------*/

void SwComboBox::InsertSorted(SwBoxEntry* pEntry)
{
    ComboBox::InsertEntry(pEntry->aName);
    USHORT nPos = ComboBox::GetEntryPos(pEntry->aName);
    aEntryLst.C40_INSERT(SwBoxEntry, pEntry, nPos);
}

/*--------------------------------------------------------------------
    Beschreibung: Je nach Option bestimmte Zeichen ausblenden
 --------------------------------------------------------------------*/

void SwComboBox::KeyInput( const KeyEvent& rKEvt )
{
    USHORT nChar = rKEvt.GetCharCode();

    if(nStyle & CBS_FILENAME)
    {
#ifdef MAC
        if(nChar == ':')
            return;
#elif defined UNX
        if(nChar == '/' || nChar == ' ' )
            return;
#else
        if(nChar == ':' || nChar == '\\' || nChar == '.' || nChar == ' ')
            return;
#endif
    }
    ComboBox::KeyInput(rKEvt);
}

/*--------------------------------------------------------------------
    Beschreibung: Text nach Option konvertieren
 --------------------------------------------------------------------*/

String SwComboBox::GetText() const
{
    String aTxt( ComboBox::GetText() );

    if(nStyle & CBS_LOWER)
        GetAppCharClass().toLower( aTxt );
    else if( nStyle & CBS_UPPER )
        GetAppCharClass().toUpper( aTxt );

    return aTxt;
}

<commit_msg>INTEGRATION: CWS ooo19126 (1.4.600); FILE MERGED 2005/09/05 13:43:11 rt 1.4.600.1: #i54170# Change license header: remove SISSL<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: swlbox.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: rt $ $Date: 2005-09-09 06:34:46 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    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
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#pragma hdrstop

#ifndef _DEBUG_HXX //autogen
#include <tools/debug.hxx>
#endif
#ifndef _UNOTOOLS_CHARCLASS_HXX
#include <unotools/charclass.hxx>
#endif

#ifndef _SWTYPES_HXX
#include <swtypes.hxx>
#endif
#ifndef _SWLBOX_HXX
#include <swlbox.hxx>
#endif

SV_IMPL_PTRARR(SwEntryLst, SwBoxEntry*)

/*--------------------------------------------------------------------
     Beschreibung: Ein ListboxElement
 --------------------------------------------------------------------*/

SwBoxEntry::SwBoxEntry() :
    bModified(FALSE),
    bNew(FALSE),
    nId(LISTBOX_APPEND)
{
}

SwBoxEntry::SwBoxEntry(const String& aNam, USHORT nIdx) :
    bModified(FALSE),
    bNew(FALSE),
    aName(aNam),
    nId(nIdx)
{
}

SwBoxEntry::SwBoxEntry(const SwBoxEntry& rOld) :
    aName(rOld.aName),
    nId(rOld.nId),
    bNew(rOld.bNew),
    bModified(rOld.bModified)
{

}

/*--------------------------------------------------------------------
     Beschreibung:
 --------------------------------------------------------------------*/

/*SwListBox::SwListBox(Window* pParent, const ResId& rId):
    ListBox(pParent, rId)
{
    DBG_ASSERT( 0 == (ListBox::GetStyle() & WB_SORT), "NIE sortiert aus der Resource lesen!" );
    // falls eine Liste ueber die Resource gelesen wurde, die interne
    // entsprechend updaten
    USHORT nCnt = ListBox::GetEntryCount();
    for( USHORT n = 0; n < nCnt; ++n )
    {
        const SwBoxEntry* pTmp = new SwBoxEntry( ListBox::GetEntry( n ), n );
        aEntryLst.Insert( pTmp, n );
    }
}

/*--------------------------------------------------------------------
     Beschreibung: Basisklasse Dtor
 --------------------------------------------------------------------*/

/*SwListBox::~SwListBox()
{
}

/*--------------------------------------------------------------------
     Beschreibung: Listen loeschen und Anzeige loeschen
 --------------------------------------------------------------------*/

/*void SwListBox::Clear()
{
    ListBox::Clear();
    aEntryLst.DeleteAndDestroy( 0, aEntryLst.Count() );
}

/*--------------------------------------------------------------------
     Beschreibung: Rund um die Entries
 --------------------------------------------------------------------*/

/*const SwBoxEntry& SwListBox::GetEntry(USHORT nPos) const
{
    if( nPos < aEntryLst.Count() )
        return *aEntryLst[ nPos ];

    return aDefault;
}

/*--------------------------------------------------------------------
     Beschreibung: aktullen Eintrag zurueckgeben
 --------------------------------------------------------------------*/

/*const SwBoxEntry& SwListBox::GetSelectEntry() const
{
    USHORT nPos = ListBox::GetSelectEntryPos();
    if( nPos < aEntryLst.Count() )
        return *aEntryLst[ nPos ];

    return aDefault;
}

void SwListBox::RemoveEntry( USHORT nPos )
{
    if( nPos < aEntryLst.Count() )
    {
        aEntryLst.DeleteAndDestroy( nPos, 1 );
        ListBox::RemoveEntry( nPos );
    }
}

/*--------------------------------------------------------------------
     Beschreibung: Eintrag in die ListBox aufnehmen
 --------------------------------------------------------------------*/

/*void SwListBox::InsertEntry( const SwBoxEntry& rEntry, USHORT nPos )
{
    if( nPos >= aEntryLst.Count() )
        nPos = aEntryLst.Count();

    SwBoxEntry* pEntry = new SwBoxEntry( rEntry );
    ListBox::InsertEntry( pEntry->aName, nPos );
    aEntryLst.C40_INSERT( SwBoxEntry, pEntry, nPos );
}

/*--------------------------------------------------------------------
     Beschreibung: Sortiert einfuegen
 --------------------------------------------------------------------*/

/*void SwListBox::InsertEntrySort( const SwBoxEntry& rEntry )
{
    USHORT nPos;
    if( !SeekEntry( rEntry, &nPos ) )
    {
        SwBoxEntry* pEntry = new SwBoxEntry( rEntry );
        ListBox::InsertEntry( pEntry->aName, nPos );
        aEntryLst.C40_INSERT( SwBoxEntry, pEntry, nPos );
    }
}

BOOL SwListBox::SeekEntry( const SwBoxEntry& rEntry, USHORT* pPos )
{
    register USHORT nO = aEntryLst.Count(), nM, nU = 0;
    if( nO > 0 )
    {
        nO--;
        while( nU <= nO )
        {
            nM = nU + ( nO - nU ) / 2;
            StringCompare eCmp = aEntryLst[ nM ]->aName.ICompare( rEntry.aName );
            if( COMPARE_EQUAL == eCmp )
            {
                if( pPos ) *pPos = nM;
                return TRUE;
            }
            else if( COMPARE_GREATER == eCmp )
                nU = nM + 1;
            else if( nM == 0 )
                break;
            else
                nO = nM - 1;
        }
    }
    if( pPos ) *pPos = nU;
    return FALSE;
}

/*  */

SwComboBox::SwComboBox(Window* pParent, const ResId& rId, USHORT nStyleBits ):
    ComboBox(pParent, rId),
    nStyle(nStyleBits)
{
    // Verwaltung fuer die Stringlist aus der Resource aufbauen
    USHORT nSize = GetEntryCount();
    for( USHORT i=0; i < nSize; ++i )
    {
        const SwBoxEntry* pTmp = new SwBoxEntry(ComboBox::GetEntry(i), i);
        aEntryLst.Insert(pTmp, aEntryLst.Count() );
    }
}

/*--------------------------------------------------------------------
     Beschreibung: Basisklasse Dtor
 --------------------------------------------------------------------*/

SwComboBox::~SwComboBox()
{
// das erledigen die Listen doch schon selbst im DTOR!
//  aEntryLst.DeleteAndDestroy(0,   aEntryLst.Count());
//  aDelEntryLst.DeleteAndDestroy(0, aDelEntryLst.Count());
}

/*--------------------------------------------------------------------
     Beschreibung: Eintrag in die ComboBox aufnehmen
 --------------------------------------------------------------------*/

void SwComboBox::InsertEntry(const SwBoxEntry& rEntry)
{
    InsertSorted(new SwBoxEntry(rEntry));
}

/*--------------------------------------------------------------------
     Beschreibung: Eintrag aus der Liste loeschen
 --------------------------------------------------------------------*/

void SwComboBox::RemoveEntry(USHORT nPos)
{
    if(nPos >= aEntryLst.Count())
        return;

    // Altes Element austragen
    SwBoxEntry* pEntry = aEntryLst[nPos];
    aEntryLst.Remove(nPos, 1);
    ComboBox::RemoveEntry(nPos);

    // keine neuen Eintraege in die Liste mit aufnehmen
    if(pEntry->bNew)
        return;

    // in DeleteListe eintragen
    aDelEntryLst.C40_INSERT(SwBoxEntry, pEntry, aDelEntryLst.Count());
}

/*--------------------------------------------------------------------
     Beschreibung: Position by Name
 --------------------------------------------------------------------*/

USHORT SwComboBox::GetEntryPos(const SwBoxEntry& rEntry) const
{
    return ComboBox::GetEntryPos(rEntry.aName);
}

/*--------------------------------------------------------------------
     Beschreibung: Rund um die Entries
 --------------------------------------------------------------------*/

const SwBoxEntry& SwComboBox::GetEntry(USHORT nPos) const
{
    if(nPos < aEntryLst.Count())
        return *aEntryLst[nPos];

    return aDefault;
}

/*--------------------------------------------------------------------
     Beschreibung: geloeschte Eintraege
 --------------------------------------------------------------------*/

USHORT SwComboBox::GetRemovedCount() const
{
    return aDelEntryLst.Count();
}

const SwBoxEntry& SwComboBox::GetRemovedEntry(USHORT nPos) const
{
    if(nPos < aDelEntryLst.Count())
        return *aDelEntryLst[nPos];

    return aDefault;
}

/*--------------------------------------------------------------------
     Beschreibung: Sortiert einfuegen
 --------------------------------------------------------------------*/

void SwComboBox::InsertSorted(SwBoxEntry* pEntry)
{
    ComboBox::InsertEntry(pEntry->aName);
    USHORT nPos = ComboBox::GetEntryPos(pEntry->aName);
    aEntryLst.C40_INSERT(SwBoxEntry, pEntry, nPos);
}

/*--------------------------------------------------------------------
    Beschreibung: Je nach Option bestimmte Zeichen ausblenden
 --------------------------------------------------------------------*/

void SwComboBox::KeyInput( const KeyEvent& rKEvt )
{
    USHORT nChar = rKEvt.GetCharCode();

    if(nStyle & CBS_FILENAME)
    {
#ifdef MAC
        if(nChar == ':')
            return;
#elif defined UNX
        if(nChar == '/' || nChar == ' ' )
            return;
#else
        if(nChar == ':' || nChar == '\\' || nChar == '.' || nChar == ' ')
            return;
#endif
    }
    ComboBox::KeyInput(rKEvt);
}

/*--------------------------------------------------------------------
    Beschreibung: Text nach Option konvertieren
 --------------------------------------------------------------------*/

String SwComboBox::GetText() const
{
    String aTxt( ComboBox::GetText() );

    if(nStyle & CBS_LOWER)
        GetAppCharClass().toLower( aTxt );
    else if( nStyle & CBS_UPPER )
        GetAppCharClass().toUpper( aTxt );

    return aTxt;
}

<|endoftext|>


<commit_before>#include <IOKit/hid/IOHIDKeys.h>
#include "CommonData.hpp"
#include "Config.hpp"
#include "EventInputQueue.hpp"
#include "FlagStatus.hpp"
#include "IOLockWrapper.hpp"
#include "ListHookedKeyboard.hpp"
#include "RemapClass.hpp"

namespace org_pqrs_KeyRemap4MacBook {
  namespace {
    ListHookedKeyboard listHookedKeyboard;
  }
  TimerWrapper ListHookedKeyboard::setcapslock_timer_;

  void
  ListHookedKeyboard::static_initialize(IOWorkLoop& workloop)
  {
    setcapslock_timer_.initialize(&workloop, NULL, ListHookedKeyboard::setCapsLock_callback);
  }

  void
  ListHookedKeyboard::static_terminate(void)
  {
    setcapslock_timer_.terminate();
  }

  ListHookedKeyboard&
  ListHookedKeyboard::instance(void)
  {
    return listHookedKeyboard;
  }

  ListHookedKeyboard::Item::Item(IOHIDevice* p) : ListHookedDevice::Item(p),
    orig_keyboardEventAction_(NULL),
    orig_keyboardEventTarget_(NULL),
    orig_updateEventFlagsAction_(NULL),
    orig_updateEventFlagsTarget_(NULL),
    replacerestore_lock_(NULL)
  {
    replacerestore_lock_ = IOLockWrapper::alloc();
  }

  ListHookedKeyboard::Item::~Item(void)
  {
    IOLOG_DEBUG("ListHookedKeyboard::Item::~Item()\n");
    restoreEventAction();
    IOLockWrapper::free(replacerestore_lock_);
  }

  // ======================================================================
  bool
  ListHookedKeyboard::Item::refresh(void)
  {
    if (! device_) goto restore;

    {
      const char* name = device_->getName();
      if (! name) goto restore;

      if (ListHookedDevice::Item::isConsumer(name)) goto restore;
    }

    // ------------------------------------------------------------
    if (! Config::get_initialized()) {
      goto restore;
    }
    if (Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_general_dont_remap_thirdvendor_keyboard) &&
        deviceType_ != DeviceType::APPLE_INTERNAL &&
        deviceType_ != DeviceType::APPLE_EXTERNAL) {
      goto restore;
    }
    if (Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_general_dont_remap_internal) &&
        deviceType_ == DeviceType::APPLE_INTERNAL) {
      goto restore;
    }
    if (Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_general_dont_remap_external) &&
        deviceType_ != DeviceType::APPLE_INTERNAL) {
      goto restore;
    }
    if (Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_general_dont_remap_apple_keyboard) &&
        isEqualVendor(DeviceVendor::APPLE_COMPUTER)) {
      goto restore;
    }

    // Logitech USB Headset
    if (isEqualVendorProduct(DeviceVendor::LOGITECH, DeviceProduct::LOGITECH_USB_HEADSET)) {
      goto restore;
    }
    // Logitech Cordless Presenter
    if (Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_general_dont_remap_logitech_cordless_presenter) &&
        isEqualVendorProduct(DeviceVendor::LOGITECH, DeviceProduct::LOGITECH_CORDLESS_PRESENTER)) {
      goto restore;
    }
    // Kensington Virtual Device (0x0, 0x0)
    if (isEqualVendorProduct(DeviceVendor::PSEUDO, DeviceProduct::PSEUDO)) {
      // Note: USB Overdrive also use 0x0,0x0.
      // We allow to use USB Overdrive.
      if (deviceType_ != DeviceType::USB_OVERDRIVE) {
        goto restore;
      }
    }

#if 0
    // Apple Internal Keyboard
    if (isEqualVendorProduct(DeviceVendor::APPLE_COMPUTER, DeviceProduct::APPLE_INTERNAL_KEYBOARD_TRACKPAD_0x021a)) {
      goto restore;
    }

    // Apple External Keyboard
    if (isEqualVendorProduct(DeviceVendor::APPLE_COMPUTER, DeviceProduct::APPLE_ALUMINUM_KEYBOARD_JIS)) {
      goto restore;
    }
#endif

    // ------------------------------------------------------------
    // NumLock Hacks
    //
    // As for some keypads, NumLock is off when it was connected.
    // We need to call setAlphaLock(true) to activate a device.
    RemapClassManager::remap_forcenumlockon(this);

    // ------------------------------------------------------------
    return replaceEventAction();

  restore:
    return restoreEventAction();
  }

  bool
  ListHookedKeyboard::Item::replaceEventAction(void)
  {
    IOLockWrapper::ScopedLock lk(replacerestore_lock_);
    if (! lk) return false;

    if (! device_) return false;

    IOHIKeyboard* kbd = OSDynamicCast(IOHIKeyboard, device_);
    if (! kbd) return false;

    bool result = false;

    // ------------------------------------------------------------
    {
      KeyboardEventCallback callback = reinterpret_cast<KeyboardEventCallback>(kbd->_keyboardEventAction);
      if (callback != EventInputQueue::push_KeyboardEventCallback) {
        IOLOG_DEBUG("HookedKeyboard::replaceEventAction (KeyboardEventCallback) device_:%p\n", device_);

        orig_keyboardEventAction_ = callback;
        orig_keyboardEventTarget_ = kbd->_keyboardEventTarget;

        kbd->_keyboardEventAction = reinterpret_cast<KeyboardEventAction>(EventInputQueue::push_KeyboardEventCallback);

        result = true;
      }
    }
    {
      UpdateEventFlagsCallback callback = reinterpret_cast<UpdateEventFlagsCallback>(kbd->_updateEventFlagsAction);
      if (callback != EventInputQueue::push_UpdateEventFlagsCallback) {
        IOLOG_DEBUG("HookedKeyboard::replaceEventAction (UpdateEventFlagsCallback) device_:%p\n", device_);

        orig_updateEventFlagsAction_ = callback;
        orig_updateEventFlagsTarget_ = kbd->_updateEventFlagsTarget;

        kbd->_updateEventFlagsAction = reinterpret_cast<UpdateEventFlagsAction>(EventInputQueue::push_UpdateEventFlagsCallback);

        result = true;
      }
    }

    return result;
  }

  bool
  ListHookedKeyboard::Item::restoreEventAction(void)
  {
    IOLockWrapper::ScopedLock lk(replacerestore_lock_);
    if (! lk) return false;

    if (! device_) return false;

    IOHIKeyboard* kbd = OSDynamicCast(IOHIKeyboard, device_);
    if (! kbd) return false;

    bool result = false;

    // ----------------------------------------
    {
      KeyboardEventCallback callback = reinterpret_cast<KeyboardEventCallback>(kbd->_keyboardEventAction);
      if (callback == EventInputQueue::push_KeyboardEventCallback) {
        IOLOG_DEBUG("HookedKeyboard::restoreEventAction (KeyboardEventCallback) device_:%p\n", device_);

        kbd->_keyboardEventAction = reinterpret_cast<KeyboardEventAction>(orig_keyboardEventAction_);

        result = true;
      }
    }
    {
      UpdateEventFlagsCallback callback = reinterpret_cast<UpdateEventFlagsCallback>(kbd->_updateEventFlagsAction);
      if (callback == EventInputQueue::push_UpdateEventFlagsCallback) {
        IOLOG_DEBUG("HookedKeyboard::restoreEventAction (UpdateEventFlagsCallback) device_:%p\n", device_);

        kbd->_updateEventFlagsAction = reinterpret_cast<UpdateEventFlagsAction>(orig_updateEventFlagsAction_);

        result = true;
      }
    }

    orig_keyboardEventAction_ = NULL;
    orig_keyboardEventTarget_ = NULL;
    orig_updateEventFlagsAction_ = NULL;
    orig_updateEventFlagsTarget_ = NULL;

    return result;
  }

  // ======================================================================
  void
  ListHookedKeyboard::Item::apply(const Params_KeyboardEventCallBack& params)
  {
    if (params.key >= KeyCode::VK__BEGIN__) {
      // Invalid keycode
      IOLOG_ERROR("ListHookedKeyboard::Item::apply invalid key:%d eventType:%d\n", params.key.get(), params.eventType.get());
      return;
    }
    if (params.eventType == EventType::MODIFY && ! params.key.isModifier()) {
      // Invalid modifierkeycode
      IOLOG_ERROR("ListHookedKeyboard::Item::apply invalid modifierkey:%08x\n", params.key.get());
      return;
    }
    if (params.flags.isVirtualModifiersOn()) {
      IOLOG_ERROR("%s invalid flags:%d\n", __PRETTY_FUNCTION__, params.flags.get());
      return;
    }

    // ------------------------------------------------------------
    if (RemapClassManager::remap_dropkeyafterremap(params)) return;

    // ------------------------------------------------------------
    KeyboardEventCallback callback = orig_keyboardEventAction_;
    if (! callback) return;

    OSObject* target = orig_keyboardEventTarget_;
    if (! target) return;

    OSObject* sender = OSDynamicCast(OSObject, device_);
    if (! sender) return;

    const AbsoluteTime& ts = CommonData::getcurrent_ts();
    OSObject* refcon = NULL;

    params.log("sending");
    callback(target, params.eventType.get(), params.flags.get(), params.key.get(),
             params.charCode.get(), params.charSet.get(), params.origCharCode.get(), params.origCharSet.get(),
             params.keyboardType.get(), params.repeat, ts, sender, refcon);

    CommonData::setcurrent_keyboardType(params.keyboardType);

    // The CapsLock LED is not designed to turn it on/off frequently.
    // So, we have to use the timer to call a setAlphaLock function at appropriate frequency.
    enum {
      CAPSLOCK_LED_DELAY_MS = 5,
    };
    setcapslock_timer_.setTimeoutMS(CAPSLOCK_LED_DELAY_MS, false);
  }

  void
  ListHookedKeyboard::Item::apply(const Params_UpdateEventFlagsCallback& params)
  {
    if (params.flags.isVirtualModifiersOn()) {
      IOLOG_ERROR("%s invalid flags:%d\n", __PRETTY_FUNCTION__, params.flags.get());
      return;
    }

    // ------------------------------------------------------------
    UpdateEventFlagsCallback callback = orig_updateEventFlagsAction_;
    if (! callback) return;

    OSObject* target = orig_updateEventFlagsTarget_;
    if (! target) return;

    OSObject* sender = OSDynamicCast(OSObject, device_);
    if (! sender) return;

    OSObject* refcon = NULL;

    params.log("sending");
    callback(target, params.flags.get(), sender, refcon);
  }

  void
  ListHookedKeyboard::apply(const Params_KeyboardEventCallBack& params)
  {
    IOLockWrapper::ScopedLock lk(list_lock_);
    if (! lk) return;

    ListHookedKeyboard::Item* p = static_cast<ListHookedKeyboard::Item*>(get_replaced_nolock());
    if (p) {
      p->apply(params);
    }
  }

  void
  ListHookedKeyboard::apply(const Params_UpdateEventFlagsCallback& params)
  {
    IOLockWrapper::ScopedLock lk(list_lock_);
    if (! lk) return;

    ListHookedKeyboard::Item* p = static_cast<ListHookedKeyboard::Item*>(get_replaced_nolock());
    if (p) {
      p->apply(params);
    }
  }

  void
  ListHookedKeyboard::setCapsLock_callback(OSObject* owner, IOTimerEventSource* sender)
  {
    ListHookedKeyboard& self = ListHookedKeyboard::instance();
    IOLockWrapper::ScopedLock lk(self.list_lock_);
    if (! lk) return;

    if (! self.list_) return;

    if (Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_general_passthrough_capslock_led_status)) return;

    Flags flags = FlagStatus::makeFlags();

    for (Item* p = static_cast<Item*>(self.list_->front()); p; p = static_cast<Item*>(p->getnext())) {
      if (! p->isReplaced()) continue;

      IOHIKeyboard* kbd = OSDynamicCast(IOHIKeyboard, p->get());
      if (! kbd) continue;

      // We call setAlphaLock to match a state of CapsLock of the hardware with remapped CapsLock.
      if (flags.isOn(ModifierFlag::CAPSLOCK)) {
        if (! kbd->alphaLock()) {
          kbd->setAlphaLock(true);
        }
      } else {
        if (kbd->alphaLock()) {
          kbd->setAlphaLock(false);
        }
      }

      if (Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_general_capslock_led_hack)) {
        // Set CapsLock LED always.
        // *** Do not use setAlphaLock for this purpose. It changes the flag status of the hardware CapsLock. ***
        enum {
          CAPSLOCK_LED_MASK = 0x2,
        };
        bool isLED = (kbd->getLEDStatus() & CAPSLOCK_LED_MASK);
        if (! isLED) {
          kbd->setAlphaLockFeedback(true);
        }
      }
    }
  }
}
<commit_msg>remove unnecessary CommonData::setcurrent_keyboardType from ListHookedKeyboard::Item::apply<commit_after>#include <IOKit/hid/IOHIDKeys.h>
#include "CommonData.hpp"
#include "Config.hpp"
#include "EventInputQueue.hpp"
#include "FlagStatus.hpp"
#include "IOLockWrapper.hpp"
#include "ListHookedKeyboard.hpp"
#include "RemapClass.hpp"

namespace org_pqrs_KeyRemap4MacBook {
  namespace {
    ListHookedKeyboard listHookedKeyboard;
  }
  TimerWrapper ListHookedKeyboard::setcapslock_timer_;

  void
  ListHookedKeyboard::static_initialize(IOWorkLoop& workloop)
  {
    setcapslock_timer_.initialize(&workloop, NULL, ListHookedKeyboard::setCapsLock_callback);
  }

  void
  ListHookedKeyboard::static_terminate(void)
  {
    setcapslock_timer_.terminate();
  }

  ListHookedKeyboard&
  ListHookedKeyboard::instance(void)
  {
    return listHookedKeyboard;
  }

  ListHookedKeyboard::Item::Item(IOHIDevice* p) : ListHookedDevice::Item(p),
    orig_keyboardEventAction_(NULL),
    orig_keyboardEventTarget_(NULL),
    orig_updateEventFlagsAction_(NULL),
    orig_updateEventFlagsTarget_(NULL),
    replacerestore_lock_(NULL)
  {
    replacerestore_lock_ = IOLockWrapper::alloc();
  }

  ListHookedKeyboard::Item::~Item(void)
  {
    IOLOG_DEBUG("ListHookedKeyboard::Item::~Item()\n");
    restoreEventAction();
    IOLockWrapper::free(replacerestore_lock_);
  }

  // ======================================================================
  bool
  ListHookedKeyboard::Item::refresh(void)
  {
    if (! device_) goto restore;

    {
      const char* name = device_->getName();
      if (! name) goto restore;

      if (ListHookedDevice::Item::isConsumer(name)) goto restore;
    }

    // ------------------------------------------------------------
    if (! Config::get_initialized()) {
      goto restore;
    }
    if (Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_general_dont_remap_thirdvendor_keyboard) &&
        deviceType_ != DeviceType::APPLE_INTERNAL &&
        deviceType_ != DeviceType::APPLE_EXTERNAL) {
      goto restore;
    }
    if (Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_general_dont_remap_internal) &&
        deviceType_ == DeviceType::APPLE_INTERNAL) {
      goto restore;
    }
    if (Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_general_dont_remap_external) &&
        deviceType_ != DeviceType::APPLE_INTERNAL) {
      goto restore;
    }
    if (Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_general_dont_remap_apple_keyboard) &&
        isEqualVendor(DeviceVendor::APPLE_COMPUTER)) {
      goto restore;
    }

    // Logitech USB Headset
    if (isEqualVendorProduct(DeviceVendor::LOGITECH, DeviceProduct::LOGITECH_USB_HEADSET)) {
      goto restore;
    }
    // Logitech Cordless Presenter
    if (Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_general_dont_remap_logitech_cordless_presenter) &&
        isEqualVendorProduct(DeviceVendor::LOGITECH, DeviceProduct::LOGITECH_CORDLESS_PRESENTER)) {
      goto restore;
    }
    // Kensington Virtual Device (0x0, 0x0)
    if (isEqualVendorProduct(DeviceVendor::PSEUDO, DeviceProduct::PSEUDO)) {
      // Note: USB Overdrive also use 0x0,0x0.
      // We allow to use USB Overdrive.
      if (deviceType_ != DeviceType::USB_OVERDRIVE) {
        goto restore;
      }
    }

#if 0
    // Apple Internal Keyboard
    if (isEqualVendorProduct(DeviceVendor::APPLE_COMPUTER, DeviceProduct::APPLE_INTERNAL_KEYBOARD_TRACKPAD_0x021a)) {
      goto restore;
    }

    // Apple External Keyboard
    if (isEqualVendorProduct(DeviceVendor::APPLE_COMPUTER, DeviceProduct::APPLE_ALUMINUM_KEYBOARD_JIS)) {
      goto restore;
    }
#endif

    // ------------------------------------------------------------
    // NumLock Hacks
    //
    // As for some keypads, NumLock is off when it was connected.
    // We need to call setAlphaLock(true) to activate a device.
    RemapClassManager::remap_forcenumlockon(this);

    // ------------------------------------------------------------
    return replaceEventAction();

  restore:
    return restoreEventAction();
  }

  bool
  ListHookedKeyboard::Item::replaceEventAction(void)
  {
    IOLockWrapper::ScopedLock lk(replacerestore_lock_);
    if (! lk) return false;

    if (! device_) return false;

    IOHIKeyboard* kbd = OSDynamicCast(IOHIKeyboard, device_);
    if (! kbd) return false;

    bool result = false;

    // ------------------------------------------------------------
    {
      KeyboardEventCallback callback = reinterpret_cast<KeyboardEventCallback>(kbd->_keyboardEventAction);
      if (callback != EventInputQueue::push_KeyboardEventCallback) {
        IOLOG_DEBUG("HookedKeyboard::replaceEventAction (KeyboardEventCallback) device_:%p\n", device_);

        orig_keyboardEventAction_ = callback;
        orig_keyboardEventTarget_ = kbd->_keyboardEventTarget;

        kbd->_keyboardEventAction = reinterpret_cast<KeyboardEventAction>(EventInputQueue::push_KeyboardEventCallback);

        result = true;
      }
    }
    {
      UpdateEventFlagsCallback callback = reinterpret_cast<UpdateEventFlagsCallback>(kbd->_updateEventFlagsAction);
      if (callback != EventInputQueue::push_UpdateEventFlagsCallback) {
        IOLOG_DEBUG("HookedKeyboard::replaceEventAction (UpdateEventFlagsCallback) device_:%p\n", device_);

        orig_updateEventFlagsAction_ = callback;
        orig_updateEventFlagsTarget_ = kbd->_updateEventFlagsTarget;

        kbd->_updateEventFlagsAction = reinterpret_cast<UpdateEventFlagsAction>(EventInputQueue::push_UpdateEventFlagsCallback);

        result = true;
      }
    }

    return result;
  }

  bool
  ListHookedKeyboard::Item::restoreEventAction(void)
  {
    IOLockWrapper::ScopedLock lk(replacerestore_lock_);
    if (! lk) return false;

    if (! device_) return false;

    IOHIKeyboard* kbd = OSDynamicCast(IOHIKeyboard, device_);
    if (! kbd) return false;

    bool result = false;

    // ----------------------------------------
    {
      KeyboardEventCallback callback = reinterpret_cast<KeyboardEventCallback>(kbd->_keyboardEventAction);
      if (callback == EventInputQueue::push_KeyboardEventCallback) {
        IOLOG_DEBUG("HookedKeyboard::restoreEventAction (KeyboardEventCallback) device_:%p\n", device_);

        kbd->_keyboardEventAction = reinterpret_cast<KeyboardEventAction>(orig_keyboardEventAction_);

        result = true;
      }
    }
    {
      UpdateEventFlagsCallback callback = reinterpret_cast<UpdateEventFlagsCallback>(kbd->_updateEventFlagsAction);
      if (callback == EventInputQueue::push_UpdateEventFlagsCallback) {
        IOLOG_DEBUG("HookedKeyboard::restoreEventAction (UpdateEventFlagsCallback) device_:%p\n", device_);

        kbd->_updateEventFlagsAction = reinterpret_cast<UpdateEventFlagsAction>(orig_updateEventFlagsAction_);

        result = true;
      }
    }

    orig_keyboardEventAction_ = NULL;
    orig_keyboardEventTarget_ = NULL;
    orig_updateEventFlagsAction_ = NULL;
    orig_updateEventFlagsTarget_ = NULL;

    return result;
  }

  // ======================================================================
  void
  ListHookedKeyboard::Item::apply(const Params_KeyboardEventCallBack& params)
  {
    if (params.key >= KeyCode::VK__BEGIN__) {
      // Invalid keycode
      IOLOG_ERROR("ListHookedKeyboard::Item::apply invalid key:%d eventType:%d\n", params.key.get(), params.eventType.get());
      return;
    }
    if (params.eventType == EventType::MODIFY && ! params.key.isModifier()) {
      // Invalid modifierkeycode
      IOLOG_ERROR("ListHookedKeyboard::Item::apply invalid modifierkey:%08x\n", params.key.get());
      return;
    }
    if (params.flags.isVirtualModifiersOn()) {
      IOLOG_ERROR("%s invalid flags:%d\n", __PRETTY_FUNCTION__, params.flags.get());
      return;
    }

    // ------------------------------------------------------------
    if (RemapClassManager::remap_dropkeyafterremap(params)) return;

    // ------------------------------------------------------------
    KeyboardEventCallback callback = orig_keyboardEventAction_;
    if (! callback) return;

    OSObject* target = orig_keyboardEventTarget_;
    if (! target) return;

    OSObject* sender = OSDynamicCast(OSObject, device_);
    if (! sender) return;

    const AbsoluteTime& ts = CommonData::getcurrent_ts();
    OSObject* refcon = NULL;

    params.log("sending");
    callback(target, params.eventType.get(), params.flags.get(), params.key.get(),
             params.charCode.get(), params.charSet.get(), params.origCharCode.get(), params.origCharSet.get(),
             params.keyboardType.get(), params.repeat, ts, sender, refcon);

    // The CapsLock LED is not designed to turn it on/off frequently.
    // So, we have to use the timer to call a setAlphaLock function at appropriate frequency.
    enum {
      CAPSLOCK_LED_DELAY_MS = 5,
    };
    setcapslock_timer_.setTimeoutMS(CAPSLOCK_LED_DELAY_MS, false);
  }

  void
  ListHookedKeyboard::Item::apply(const Params_UpdateEventFlagsCallback& params)
  {
    if (params.flags.isVirtualModifiersOn()) {
      IOLOG_ERROR("%s invalid flags:%d\n", __PRETTY_FUNCTION__, params.flags.get());
      return;
    }

    // ------------------------------------------------------------
    UpdateEventFlagsCallback callback = orig_updateEventFlagsAction_;
    if (! callback) return;

    OSObject* target = orig_updateEventFlagsTarget_;
    if (! target) return;

    OSObject* sender = OSDynamicCast(OSObject, device_);
    if (! sender) return;

    OSObject* refcon = NULL;

    params.log("sending");
    callback(target, params.flags.get(), sender, refcon);
  }

  void
  ListHookedKeyboard::apply(const Params_KeyboardEventCallBack& params)
  {
    IOLockWrapper::ScopedLock lk(list_lock_);
    if (! lk) return;

    ListHookedKeyboard::Item* p = static_cast<ListHookedKeyboard::Item*>(get_replaced_nolock());
    if (p) {
      p->apply(params);
    }
  }

  void
  ListHookedKeyboard::apply(const Params_UpdateEventFlagsCallback& params)
  {
    IOLockWrapper::ScopedLock lk(list_lock_);
    if (! lk) return;

    ListHookedKeyboard::Item* p = static_cast<ListHookedKeyboard::Item*>(get_replaced_nolock());
    if (p) {
      p->apply(params);
    }
  }

  void
  ListHookedKeyboard::setCapsLock_callback(OSObject* owner, IOTimerEventSource* sender)
  {
    ListHookedKeyboard& self = ListHookedKeyboard::instance();
    IOLockWrapper::ScopedLock lk(self.list_lock_);
    if (! lk) return;

    if (! self.list_) return;

    if (Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_general_passthrough_capslock_led_status)) return;

    Flags flags = FlagStatus::makeFlags();

    for (Item* p = static_cast<Item*>(self.list_->front()); p; p = static_cast<Item*>(p->getnext())) {
      if (! p->isReplaced()) continue;

      IOHIKeyboard* kbd = OSDynamicCast(IOHIKeyboard, p->get());
      if (! kbd) continue;

      // We call setAlphaLock to match a state of CapsLock of the hardware with remapped CapsLock.
      if (flags.isOn(ModifierFlag::CAPSLOCK)) {
        if (! kbd->alphaLock()) {
          kbd->setAlphaLock(true);
        }
      } else {
        if (kbd->alphaLock()) {
          kbd->setAlphaLock(false);
        }
      }

      if (Config::get_essential_config(BRIDGE_ESSENTIAL_CONFIG_INDEX_general_capslock_led_hack)) {
        // Set CapsLock LED always.
        // *** Do not use setAlphaLock for this purpose. It changes the flag status of the hardware CapsLock. ***
        enum {
          CAPSLOCK_LED_MASK = 0x2,
        };
        bool isLED = (kbd->getLEDStatus() & CAPSLOCK_LED_MASK);
        if (! isLED) {
          kbd->setAlphaLockFeedback(true);
        }
      }
    }
  }
}
<|endoftext|>


<commit_before>/*
 * Funambol is a mobile platform developed by Funambol, Inc.
 * Copyright (C) 2003 - 2007 Funambol, Inc.
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License version 3 as published by
 * the Free Software Foundation with the addition of the following permission
 * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
 * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE
 * WARRANTY OF NON INFRINGEMENT  OF THIRD PARTY RIGHTS.
 *
 * 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 Affero General Public License
 * along with this program; if not, see http://www.gnu.org/licenses or write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301 USA.
 *
 * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite
 * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.
 *
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU Affero General Public License version 3.
 *
 * In accordance with Section 7(b) of the GNU Affero General Public License
 * version 3, these Appropriate Legal Notices must retain the display of the
 * "Powered by Funambol" logo. If the display of the logo is not reasonably
 * feasible for technical reasons, the Appropriate Legal Notices must display
 * the words "Powered by Funambol".
 */

#include "base/Log.h"
#include "event/SyncItemListener.h"

BEGIN_NAMESPACE

void logEvent(const char* msg, SyncItemEvent& event) {
    LOG.debug("%s: (%s, %s, %s)", msg, event.getItemKey(), event.getSourceName(), event.getSourceURI());
}

// listen for the Item added by Server Event
void SyncItemListener::itemAddedByServer(SyncItemEvent& event) {
    logEvent("item added by server", event);
}

// listen for the Item  deleted by Server Event
void SyncItemListener::itemDeletedByServer(SyncItemEvent& event) {
    logEvent("item deleted by server", event);
}

// listen for the Item updated by Server Event
void SyncItemListener::itemUpdatedByServer(SyncItemEvent& event) {
    logEvent("item updated by server", event);
}

// listen for the Item added by Client Event
void SyncItemListener::itemAddedByClient(SyncItemEvent& event) {
    logEvent("item added by client", event);
}

// listen for the Item deleted by Client Event
void SyncItemListener::itemDeletedByClient(SyncItemEvent& event) {
    logEvent("item deleted by client", event);
}

// listen for the Item updated by Server Event
void SyncItemListener::itemUpdatedByClient(SyncItemEvent& event) {
    logEvent("item updated by server", event);
}

END_NAMESPACE<commit_msg>added newline at eof<commit_after>/*
 * Funambol is a mobile platform developed by Funambol, Inc.
 * Copyright (C) 2003 - 2007 Funambol, Inc.
 *
 * This program is free software; you can redistribute it and/or modify it under
 * the terms of the GNU Affero General Public License version 3 as published by
 * the Free Software Foundation with the addition of the following permission
 * added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
 * WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE
 * WARRANTY OF NON INFRINGEMENT  OF THIRD PARTY RIGHTS.
 *
 * 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 Affero General Public License
 * along with this program; if not, see http://www.gnu.org/licenses or write to
 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
 * MA 02110-1301 USA.
 *
 * You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite
 * 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.
 *
 * The interactive user interfaces in modified source and object code versions
 * of this program must display Appropriate Legal Notices, as required under
 * Section 5 of the GNU Affero General Public License version 3.
 *
 * In accordance with Section 7(b) of the GNU Affero General Public License
 * version 3, these Appropriate Legal Notices must retain the display of the
 * "Powered by Funambol" logo. If the display of the logo is not reasonably
 * feasible for technical reasons, the Appropriate Legal Notices must display
 * the words "Powered by Funambol".
 */

#include "base/Log.h"
#include "event/SyncItemListener.h"

BEGIN_NAMESPACE

void logEvent(const char* msg, SyncItemEvent& event) {
    LOG.debug("%s: (%s, %s, %s)", msg, event.getItemKey(), event.getSourceName(), event.getSourceURI());
}

// listen for the Item added by Server Event
void SyncItemListener::itemAddedByServer(SyncItemEvent& event) {
    logEvent("item added by server", event);
}

// listen for the Item  deleted by Server Event
void SyncItemListener::itemDeletedByServer(SyncItemEvent& event) {
    logEvent("item deleted by server", event);
}

// listen for the Item updated by Server Event
void SyncItemListener::itemUpdatedByServer(SyncItemEvent& event) {
    logEvent("item updated by server", event);
}

// listen for the Item added by Client Event
void SyncItemListener::itemAddedByClient(SyncItemEvent& event) {
    logEvent("item added by client", event);
}

// listen for the Item deleted by Client Event
void SyncItemListener::itemDeletedByClient(SyncItemEvent& event) {
    logEvent("item deleted by client", event);
}

// listen for the Item updated by Server Event
void SyncItemListener::itemUpdatedByClient(SyncItemEvent& event) {
    logEvent("item updated by server", event);
}

END_NAMESPACE
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  $RCSfile: shdwcrsr.hxx,v $
 *
 *  $Revision: 1.1.1.1 $
 *
 *  last change: $Author: hr $ $Date: 2000-09-18 17:14:42 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  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
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _SHDWCRSR_HXX
#define _SHDWCRSR_HXX

#ifndef _GEN_HXX //autogen
#include <tools/gen.hxx>
#endif
#ifndef _SV_COLOR_HXX //autogen
#include <vcl/color.hxx>
#endif
#include  <limits.h>

class Window;

class SwShadowCursor
{
    Window* pWin;
    Color aCol;
    Point aOldPt;
    long nOldHeight;
    USHORT nOldMode;

    void DrawTri( const Point& rPt, long nHeight, BOOL bLeft );
    void DrawCrsr( const Point& rPt, long nHeight, USHORT nMode );

public:
    SwShadowCursor( Window& rWin, const Color& rCol )
        : pWin( &rWin ), nOldMode( USHRT_MAX ), aCol( rCol ) {}
    ~SwShadowCursor();

    void SetPos( const Point& rPt, long nHeight, USHORT nMode );

    void Paint();

    const Point& GetPoint() const   { return aOldPt; }
    long GetHeight() const          { return nOldHeight; }
    USHORT GetMode() const          { return nOldMode; }

    Rectangle GetRect() const;
};

#endif

<commit_msg>INTEGRATION: CWS vclcleanup02 (1.1.1.1.512); FILE MERGED 2003/12/11 09:10:18 mt 1.1.1.1.512.1: #i23061# VCL cleanup, removed headers, methods and types...<commit_after>/*************************************************************************
 *
 *  $RCSfile: shdwcrsr.hxx,v $
 *
 *  $Revision: 1.2 $
 *
 *  last change: $Author: vg $ $Date: 2004-01-06 18:25:13 $
 *
 *  The Contents of this file are made available subject to the terms of
 *  either of the following licenses
 *
 *         - GNU Lesser General Public License Version 2.1
 *         - Sun Industry Standards Source License Version 1.1
 *
 *  Sun Microsystems Inc., October, 2000
 *
 *  GNU Lesser General Public License Version 2.1
 *  =============================================
 *  Copyright 2000 by Sun Microsystems, Inc.
 *  901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *  This library is free software; you can redistribute it and/or
 *  modify it under the terms of the GNU Lesser General Public
 *  License version 2.1, as published by the Free Software Foundation.
 *
 *  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
 *  Lesser General Public License for more details.
 *
 *  You should have received a copy of the GNU Lesser General Public
 *  License along with this library; if not, write to the Free Software
 *  Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *  MA  02111-1307  USA
 *
 *
 *  Sun Industry Standards Source License Version 1.1
 *  =================================================
 *  The contents of this file are subject to the Sun Industry Standards
 *  Source License Version 1.1 (the "License"); You may not use this file
 *  except in compliance with the License. You may obtain a copy of the
 *  License at http://www.openoffice.org/license.html.
 *
 *  Software provided under this License is provided on an "AS IS" basis,
 *  WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 *  WITHOUT LIMITATION, WARRANTIES THAT THE SOFTWARE IS FREE OF DEFECTS,
 *  MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE, OR NON-INFRINGING.
 *  See the License for the specific provisions governing your rights and
 *  obligations concerning the Software.
 *
 *  The Initial Developer of the Original Code is: Sun Microsystems, Inc.
 *
 *  Copyright: 2000 by Sun Microsystems, Inc.
 *
 *  All Rights Reserved.
 *
 *  Contributor(s): _______________________________________
 *
 *
 ************************************************************************/
#ifndef _SHDWCRSR_HXX
#define _SHDWCRSR_HXX

#ifndef _GEN_HXX //autogen
#include <tools/gen.hxx>
#endif
#ifndef _TOOLS_COLOR_HXX
#include <tools/color.hxx>
#endif
#include  <limits.h>

class Window;

class SwShadowCursor
{
    Window* pWin;
    Color aCol;
    Point aOldPt;
    long nOldHeight;
    USHORT nOldMode;

    void DrawTri( const Point& rPt, long nHeight, BOOL bLeft );
    void DrawCrsr( const Point& rPt, long nHeight, USHORT nMode );

public:
    SwShadowCursor( Window& rWin, const Color& rCol )
        : pWin( &rWin ), nOldMode( USHRT_MAX ), aCol( rCol ) {}
    ~SwShadowCursor();

    void SetPos( const Point& rPt, long nHeight, USHORT nMode );

    void Paint();

    const Point& GetPoint() const   { return aOldPt; }
    long GetHeight() const          { return nOldHeight; }
    USHORT GetMode() const          { return nOldMode; }

    Rectangle GetRect() const;
};

#endif

<|endoftext|>


<commit_before>/*-------------------------------------------------------------------------
* Vulkan Conformance Tests
* ------------------------
*
* Copyright (c) 2018 Advanced Micro Devices, Inc.
* Copyright (c) 2018 The Khronos Group Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*//*!
* \file
* \brief VK_KHR_driver_properties tests
*//*--------------------------------------------------------------------*/

#include "vktApiDriverPropertiesTests.hpp"
#include "vktTestGroupUtil.hpp"
#include "vktTestCaseUtil.hpp"
#include "vkQueryUtil.hpp"
#include "vkTypeUtil.hpp"

using namespace vk;

namespace vkt
{
namespace api
{
namespace
{

static const deUint32 knownDriverIds[] =
{
	// Specified in the Vulkan registry (vk.xml)
	1,	// author = "Advanced Micro Devices, Inc."   comment = "AMD proprietary driver"
	2,	// author = "Advanced Micro Devices, Inc."   comment = "AMD open-source driver"
	3,	// author = "Mesa open source project"       comment = "Mesa RADV driver"
	4,	// author = "NVIDIA Corporation"             comment = "NVIDIA proprietary driver"
	5,	// author = "Intel Corporation"              comment = "Intel proprietary Windows driver"
	6,	// author = "Intel Corporation"              comment = "Intel open-source Mesa driver"
	7,	// author = "Imagination Technologies"       comment = "Imagination proprietary driver"
	8,	// author = "Qualcomm Technologies, Inc."    comment = "Qualcomm proprietary driver"
	9,	// author = "Arm Limited"                    comment = "Arm proprietary driver"
};

static const VkConformanceVersionKHR knownConformanceVersions[] =
{
	makeConformanceVersionKHR(1, 1, 2, 3),
	makeConformanceVersionKHR(1, 1, 2, 2),
	makeConformanceVersionKHR(1, 1, 2, 1),
	makeConformanceVersionKHR(1, 1, 2, 0),
	makeConformanceVersionKHR(1, 1, 1, 3),
	makeConformanceVersionKHR(1, 1, 1, 2),
	makeConformanceVersionKHR(1, 1, 1, 1),
	makeConformanceVersionKHR(1, 1, 1, 0),
	makeConformanceVersionKHR(1, 1, 0, 3),
	makeConformanceVersionKHR(1, 0, 2, 6),
	makeConformanceVersionKHR(1, 0, 2, 5),
	makeConformanceVersionKHR(1, 0, 2, 4),
	makeConformanceVersionKHR(1, 0, 2, 3),
	makeConformanceVersionKHR(1, 0, 2, 2),
	makeConformanceVersionKHR(1, 0, 2, 1),
	makeConformanceVersionKHR(1, 0, 2, 0),
};

DE_INLINE bool isNullTerminated(const char* str, const deUint32 maxSize)
{
	return deStrnlen(str, maxSize) < maxSize;
}

DE_INLINE bool operator==(const VkConformanceVersionKHR& a, const VkConformanceVersionKHR& b)
{
	return ((a.major == b.major)		&&
			(a.minor == b.minor)		&&
			(a.subminor == b.subminor)	&&
			(a.patch == b.patch));
}

tcu::TestStatus testQueryProperties (Context& context)
{
	// Check extension support

	if (!isDeviceExtensionSupported(context.getUsedApiVersion(), context.getDeviceExtensions(), "VK_KHR_driver_properties"))
		TCU_THROW(NotSupportedError, "Unsupported extension: VK_KHR_driver_properties");

	// Query the driver properties

	const VkPhysicalDevice				physDevice			= context.getPhysicalDevice();
	const int							memsetPattern		= 0xaa;
	VkPhysicalDeviceProperties2			deviceProperties2;
	VkPhysicalDeviceDriverPropertiesKHR	deviceDriverProperties;

	deMemset(&deviceDriverProperties, memsetPattern, sizeof(deviceDriverProperties));
	deviceDriverProperties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES_KHR;
	deviceDriverProperties.pNext = DE_NULL;

	deMemset(&deviceProperties2, memsetPattern, sizeof(deviceProperties2));
	deviceProperties2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;
	deviceProperties2.pNext = &deviceDriverProperties;

	context.getInstanceInterface().getPhysicalDeviceProperties2(physDevice, &deviceProperties2);

	// Verify the returned values

	bool match = false;

	for (const deUint32* pDriverId = knownDriverIds; (pDriverId != DE_ARRAY_END(knownDriverIds)) && !match; ++pDriverId)
	{
		if (deviceDriverProperties.driverID == *pDriverId)
		{
			match = true;

			if (!isNullTerminated(deviceDriverProperties.driverName, VK_MAX_DRIVER_NAME_SIZE_KHR))
				TCU_FAIL("Driver name is not a null-terminated string");

			if (deviceDriverProperties.driverName[0] == 0)
				TCU_FAIL("Driver name is empty");

			if (!isNullTerminated(deviceDriverProperties.driverInfo, VK_MAX_DRIVER_INFO_SIZE_KHR))
				TCU_FAIL("Driver info is not a null-terminated string");

			bool conformanceVersionMatch = false;

			for (const VkConformanceVersionKHR* pConformanceVersion  = knownConformanceVersions;
												pConformanceVersion != DE_ARRAY_END(knownConformanceVersions);
											  ++pConformanceVersion)
			{
				if (deviceDriverProperties.conformanceVersion == *pConformanceVersion)
				{
					conformanceVersionMatch = true;
					break;
				}
			}

			if (!conformanceVersionMatch)
				TCU_FAIL("Wrong driver conformance version");
		}
	}

	if (!match)
		TCU_FAIL("Driver ID did not match any known driver");

	return tcu::TestStatus::pass("Pass");
}

void createTestCases (tcu::TestCaseGroup* group)
{
	addFunctionCase(group, "properties", "Query VkPhysicalDeviceDriverPropertiesKHR and check its values", testQueryProperties);
}

} // anonymous

tcu::TestCaseGroup*	createDriverPropertiesTests(tcu::TestContext& testCtx)
{
	return createTestGroup(testCtx, "driver_properties", "VK_KHR_driver_properties tests", createTestCases);
}

} // api
} // vkt
<commit_msg>Add 1.1.3.0 to known conformance versions<commit_after>/*-------------------------------------------------------------------------
* Vulkan Conformance Tests
* ------------------------
*
* Copyright (c) 2018 Advanced Micro Devices, Inc.
* Copyright (c) 2018 The Khronos Group Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*      http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*//*!
* \file
* \brief VK_KHR_driver_properties tests
*//*--------------------------------------------------------------------*/

#include "vktApiDriverPropertiesTests.hpp"
#include "vktTestGroupUtil.hpp"
#include "vktTestCaseUtil.hpp"
#include "vkQueryUtil.hpp"
#include "vkTypeUtil.hpp"

using namespace vk;

namespace vkt
{
namespace api
{
namespace
{

static const deUint32 knownDriverIds[] =
{
	// Specified in the Vulkan registry (vk.xml)
	1,	// author = "Advanced Micro Devices, Inc."   comment = "AMD proprietary driver"
	2,	// author = "Advanced Micro Devices, Inc."   comment = "AMD open-source driver"
	3,	// author = "Mesa open source project"       comment = "Mesa RADV driver"
	4,	// author = "NVIDIA Corporation"             comment = "NVIDIA proprietary driver"
	5,	// author = "Intel Corporation"              comment = "Intel proprietary Windows driver"
	6,	// author = "Intel Corporation"              comment = "Intel open-source Mesa driver"
	7,	// author = "Imagination Technologies"       comment = "Imagination proprietary driver"
	8,	// author = "Qualcomm Technologies, Inc."    comment = "Qualcomm proprietary driver"
	9,	// author = "Arm Limited"                    comment = "Arm proprietary driver"
};

static const VkConformanceVersionKHR knownConformanceVersions[] =
{
	makeConformanceVersionKHR(1, 1, 3, 0),
	makeConformanceVersionKHR(1, 1, 2, 3),
	makeConformanceVersionKHR(1, 1, 2, 2),
	makeConformanceVersionKHR(1, 1, 2, 1),
	makeConformanceVersionKHR(1, 1, 2, 0),
	makeConformanceVersionKHR(1, 1, 1, 3),
	makeConformanceVersionKHR(1, 1, 1, 2),
	makeConformanceVersionKHR(1, 1, 1, 1),
	makeConformanceVersionKHR(1, 1, 1, 0),
	makeConformanceVersionKHR(1, 1, 0, 3),
	makeConformanceVersionKHR(1, 0, 2, 6),
	makeConformanceVersionKHR(1, 0, 2, 5),
	makeConformanceVersionKHR(1, 0, 2, 4),
	makeConformanceVersionKHR(1, 0, 2, 3),
	makeConformanceVersionKHR(1, 0, 2, 2),
	makeConformanceVersionKHR(1, 0, 2, 1),
	makeConformanceVersionKHR(1, 0, 2, 0),
};

DE_INLINE bool isNullTerminated(const char* str, const deUint32 maxSize)
{
	return deStrnlen(str, maxSize) < maxSize;
}

DE_INLINE bool operator==(const VkConformanceVersionKHR& a, const VkConformanceVersionKHR& b)
{
	return ((a.major == b.major)		&&
			(a.minor == b.minor)		&&
			(a.subminor == b.subminor)	&&
			(a.patch == b.patch));
}

tcu::TestStatus testQueryProperties (Context& context)
{
	// Check extension support

	if (!isDeviceExtensionSupported(context.getUsedApiVersion(), context.getDeviceExtensions(), "VK_KHR_driver_properties"))
		TCU_THROW(NotSupportedError, "Unsupported extension: VK_KHR_driver_properties");

	// Query the driver properties

	const VkPhysicalDevice				physDevice			= context.getPhysicalDevice();
	const int							memsetPattern		= 0xaa;
	VkPhysicalDeviceProperties2			deviceProperties2;
	VkPhysicalDeviceDriverPropertiesKHR	deviceDriverProperties;

	deMemset(&deviceDriverProperties, memsetPattern, sizeof(deviceDriverProperties));
	deviceDriverProperties.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_DRIVER_PROPERTIES_KHR;
	deviceDriverProperties.pNext = DE_NULL;

	deMemset(&deviceProperties2, memsetPattern, sizeof(deviceProperties2));
	deviceProperties2.sType = VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2;
	deviceProperties2.pNext = &deviceDriverProperties;

	context.getInstanceInterface().getPhysicalDeviceProperties2(physDevice, &deviceProperties2);

	// Verify the returned values

	bool match = false;

	for (const deUint32* pDriverId = knownDriverIds; (pDriverId != DE_ARRAY_END(knownDriverIds)) && !match; ++pDriverId)
	{
		if (deviceDriverProperties.driverID == *pDriverId)
		{
			match = true;

			if (!isNullTerminated(deviceDriverProperties.driverName, VK_MAX_DRIVER_NAME_SIZE_KHR))
				TCU_FAIL("Driver name is not a null-terminated string");

			if (deviceDriverProperties.driverName[0] == 0)
				TCU_FAIL("Driver name is empty");

			if (!isNullTerminated(deviceDriverProperties.driverInfo, VK_MAX_DRIVER_INFO_SIZE_KHR))
				TCU_FAIL("Driver info is not a null-terminated string");

			bool conformanceVersionMatch = false;

			for (const VkConformanceVersionKHR* pConformanceVersion  = knownConformanceVersions;
												pConformanceVersion != DE_ARRAY_END(knownConformanceVersions);
											  ++pConformanceVersion)
			{
				if (deviceDriverProperties.conformanceVersion == *pConformanceVersion)
				{
					conformanceVersionMatch = true;
					break;
				}
			}

			if (!conformanceVersionMatch)
				TCU_FAIL("Wrong driver conformance version");
		}
	}

	if (!match)
		TCU_FAIL("Driver ID did not match any known driver");

	return tcu::TestStatus::pass("Pass");
}

void createTestCases (tcu::TestCaseGroup* group)
{
	addFunctionCase(group, "properties", "Query VkPhysicalDeviceDriverPropertiesKHR and check its values", testQueryProperties);
}

} // anonymous

tcu::TestCaseGroup*	createDriverPropertiesTests(tcu::TestContext& testCtx)
{
	return createTestGroup(testCtx, "driver_properties", "VK_KHR_driver_properties tests", createTestCases);
}

} // api
} // vkt
<|endoftext|>


<commit_before>#include "dummy_video.h"
#include <halley/core/graphics/painter.h>
#include <halley/core/graphics/texture.h>
#include <halley/core/graphics/shader.h>
#include <halley/core/graphics/render_target/render_target_texture.h>
#include "dummy_system.h"

using namespace Halley;

DummyVideoAPI::DummyVideoAPI(SystemAPI&)
{}

void DummyVideoAPI::startRender()
{
}

void DummyVideoAPI::finishRender()
{
}

void DummyVideoAPI::setWindow(WindowDefinition&& windowDescriptor)
{
	//window = system.createWindow(windowDescriptor);
	window = std::make_shared<DummyWindow>(windowDescriptor);
}

const Window& DummyVideoAPI::getWindow() const
{
	Expects(window);
	return *window;
}

bool DummyVideoAPI::hasWindow() const
{
	return static_cast<bool>(window);
}

std::unique_ptr<Texture> DummyVideoAPI::createTexture(Vector2i size)
{
	return std::make_unique<DummyTexture>(size);
}

std::unique_ptr<Shader> DummyVideoAPI::createShader(const ShaderDefinition&)
{
	return std::make_unique<DummyShader>();
}

std::unique_ptr<TextureRenderTarget> DummyVideoAPI::createTextureRenderTarget()
{
	return std::make_unique<TextureRenderTarget>();
}

std::unique_ptr<ScreenRenderTarget> DummyVideoAPI::createScreenRenderTarget()
{
	return std::make_unique<ScreenRenderTarget>(Rect4i({}, getWindow().getWindowRect().getSize()));
}

std::unique_ptr<MaterialConstantBuffer> DummyVideoAPI::createConstantBuffer()
{
	return std::make_unique<DummyMaterialConstantBuffer>();
}

void DummyVideoAPI::init()
{
}

void DummyVideoAPI::deInit()
{
}

std::unique_ptr<Painter> DummyVideoAPI::makePainter(Resources& resources)
{
	return std::make_unique<DummyPainter>(resources);
}

String DummyVideoAPI::getShaderLanguage()
{
	return "glsl";
}

DummyTexture::DummyTexture(Vector2i size)
	: Texture(size)
{
}

void DummyTexture::load(TextureDescriptor&&)
{
	doneLoading();
}

int DummyShader::getUniformLocation(const String&, ShaderType)
{
	return 0;
}

int DummyShader::getBlockLocation(const String&, ShaderType)
{
	return 0;
}

void DummyMaterialConstantBuffer::update(const MaterialDataBlock&) {}

DummyPainter::DummyPainter(Resources& resources)
	: Painter(resources)
{}

void DummyPainter::clear(Colour colour) {}

void DummyPainter::setMaterialPass(const Material&, int) {}

void DummyPainter::doStartRender() {}

void DummyPainter::doEndRender() {}

void DummyPainter::setVertices(const MaterialDefinition&, size_t, void*, size_t, unsigned short*, bool) {}

void DummyPainter::drawTriangles(size_t) {}

void DummyPainter::setViewPort(Rect4i) {}

void DummyPainter::setClip(Rect4i, bool) {}

void DummyPainter::setMaterialData(const Material&) {}

void DummyPainter::onUpdateProjection(Material&) {}
<commit_msg>DummyVideoAPI::finishRender now sleeps for 10 milliseconds to avoid headless clients using 100% CPU<commit_after>#include "dummy_video.h"
#include <halley/core/graphics/painter.h>
#include <halley/core/graphics/texture.h>
#include <halley/core/graphics/shader.h>
#include <halley/core/graphics/render_target/render_target_texture.h>
#include "dummy_system.h"
#include <chrono>

using namespace Halley;

DummyVideoAPI::DummyVideoAPI(SystemAPI&)
{}

void DummyVideoAPI::startRender()
{
}

void DummyVideoAPI::finishRender()
{
	using namespace std::chrono_literals;
	std::this_thread::sleep_for(10ms);
}

void DummyVideoAPI::setWindow(WindowDefinition&& windowDescriptor)
{
	//window = system.createWindow(windowDescriptor);
	window = std::make_shared<DummyWindow>(windowDescriptor);
}

const Window& DummyVideoAPI::getWindow() const
{
	Expects(window);
	return *window;
}

bool DummyVideoAPI::hasWindow() const
{
	return static_cast<bool>(window);
}

std::unique_ptr<Texture> DummyVideoAPI::createTexture(Vector2i size)
{
	return std::make_unique<DummyTexture>(size);
}

std::unique_ptr<Shader> DummyVideoAPI::createShader(const ShaderDefinition&)
{
	return std::make_unique<DummyShader>();
}

std::unique_ptr<TextureRenderTarget> DummyVideoAPI::createTextureRenderTarget()
{
	return std::make_unique<TextureRenderTarget>();
}

std::unique_ptr<ScreenRenderTarget> DummyVideoAPI::createScreenRenderTarget()
{
	return std::make_unique<ScreenRenderTarget>(Rect4i({}, getWindow().getWindowRect().getSize()));
}

std::unique_ptr<MaterialConstantBuffer> DummyVideoAPI::createConstantBuffer()
{
	return std::make_unique<DummyMaterialConstantBuffer>();
}

void DummyVideoAPI::init()
{
}

void DummyVideoAPI::deInit()
{
}

std::unique_ptr<Painter> DummyVideoAPI::makePainter(Resources& resources)
{
	return std::make_unique<DummyPainter>(resources);
}

String DummyVideoAPI::getShaderLanguage()
{
	return "glsl";
}

DummyTexture::DummyTexture(Vector2i size)
	: Texture(size)
{
}

void DummyTexture::load(TextureDescriptor&&)
{
	doneLoading();
}

int DummyShader::getUniformLocation(const String&, ShaderType)
{
	return 0;
}

int DummyShader::getBlockLocation(const String&, ShaderType)
{
	return 0;
}

void DummyMaterialConstantBuffer::update(const MaterialDataBlock&) {}

DummyPainter::DummyPainter(Resources& resources)
	: Painter(resources)
{}

void DummyPainter::clear(Colour colour) {}

void DummyPainter::setMaterialPass(const Material&, int) {}

void DummyPainter::doStartRender() {}

void DummyPainter::doEndRender() {}

void DummyPainter::setVertices(const MaterialDefinition&, size_t, void*, size_t, unsigned short*, bool) {}

void DummyPainter::drawTriangles(size_t) {}

void DummyPainter::setViewPort(Rect4i) {}

void DummyPainter::setClip(Rect4i, bool) {}

void DummyPainter::setMaterialData(const Material&) {}

void DummyPainter::onUpdateProjection(Material&) {}
<|endoftext|>


<commit_before>/***************************************************************************
 *   Copyright (C) 2007 by Lothar May                                      *
 *                                                                         *
 *   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.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/
#include "clientboard.h"

#include "localhand.h"
#include <game_defs.h>

using namespace std;

ClientBoard::ClientBoard()
: playerArray(0), actualHand(0), pot(0), sets(0)
{
}

ClientBoard::~ClientBoard()
{
}

void
ClientBoard::setPlayer(PlayerInterface** p)
{
	playerArray = p;
}

void
ClientBoard::setHand(HandInterface* br)
{
	actualHand = br;
}

void
ClientBoard::collectSets()
{
}

void
ClientBoard::collectPot()
{
	pot += sets;
	sets = 0;
}

<commit_msg>Linefeeds.<commit_after>/***************************************************************************
 *   Copyright (C) 2007 by Lothar May                                      *
 *                                                                         *
 *   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.,                                       *
 *   59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.             *
 ***************************************************************************/
#include "clientboard.h"

#include "localhand.h"
#include <game_defs.h>

using namespace std;

ClientBoard::ClientBoard()
: playerArray(0), actualHand(0), pot(0), sets(0)
{
}

ClientBoard::~ClientBoard()
{
}

void
ClientBoard::setPlayer(PlayerInterface** p)
{
	playerArray = p;
}

void
ClientBoard::setHand(HandInterface* br)
{
	actualHand = br;
}

void
ClientBoard::collectSets()
{
}

void
ClientBoard::collectPot()
{
	pot += sets;
	sets = 0;
}

<|endoftext|>