<commit_before>/*
 * Copyright (c) 2014 Advanced Micro Devices, Inc.
 * Copyright (c) 2003 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Steve Reinhardt
 *          Ron Dreslinski
 *          Ali Saidi
 */

/**
 * @file
 * Definitions of functional page table.
 */
#include "mem/page_table.hh"

#include <string>

#include "base/trace.hh"
#include "debug/MMU.hh"
#include "sim/faults.hh"
#include "sim/serialize.hh"

using namespace std;

void
EmulationPageTable::map(Addr vaddr, Addr paddr, int64_t size, uint64_t flags)
{
    bool clobber = flags & Clobber;
    // starting address must be page aligned
    assert(pageOffset(vaddr) == 0);

    DPRINTF(MMU, "Allocating Page: %#x-%#x\n", vaddr, vaddr + size);

    while (size > 0) {
        auto it = pTable.find(vaddr);
        if (it != pTable.end()) {
            // already mapped
            panic_if(!clobber,
                     "EmulationPageTable::allocate: addr %#x already mapped",
                     vaddr);
            it->second = Entry(paddr, flags);
        } else {
            pTable.emplace(vaddr, Entry(paddr, flags));
        }

        size -= pageSize;
        vaddr += pageSize;
        paddr += pageSize;
    }
}

void
EmulationPageTable::remap(Addr vaddr, int64_t size, Addr new_vaddr)
{
    assert(pageOffset(vaddr) == 0);
    assert(pageOffset(new_vaddr) == 0);

    DPRINTF(MMU, "moving pages from vaddr %08p to %08p, size = %d\n", vaddr,
            new_vaddr, size);

    while (size > 0) {
        auto new_it = pTable.find(new_vaddr);
        auto old_it = pTable.find(vaddr);
        assert(old_it != pTable.end() && new_it == pTable.end());

        new_it->second = old_it->second;
        pTable.erase(old_it);
        size -= pageSize;
        vaddr += pageSize;
        new_vaddr += pageSize;
    }
}

void
EmulationPageTable::getMappings(std::vector<std::pair<Addr, Addr>> *addr_maps)
{
    for (auto &iter : pTable)
        addr_maps->push_back(make_pair(iter.first, iter.second.paddr));
}

void
EmulationPageTable::unmap(Addr vaddr, int64_t size)
{
    assert(pageOffset(vaddr) == 0);

    DPRINTF(MMU, "Unmapping page: %#x-%#x\n", vaddr, vaddr + size);

    while (size > 0) {
        auto it = pTable.find(vaddr);
        assert(it != pTable.end());
        pTable.erase(it);
        size -= pageSize;
        vaddr += pageSize;
    }
}

bool
EmulationPageTable::isUnmapped(Addr vaddr, int64_t size)
{
    // starting address must be page aligned
    assert(pageOffset(vaddr) == 0);

    for (int64_t offset = 0; offset < size; offset += pageSize)
        if (pTable.find(vaddr + offset) != pTable.end())
            return false;

    return true;
}

const EmulationPageTable::Entry *
EmulationPageTable::lookup(Addr vaddr)
{
    Addr page_addr = pageAlign(vaddr);
    PTableItr iter = pTable.find(page_addr);
    if (iter == pTable.end())
        return nullptr;
    return &(iter->second);
}

bool
EmulationPageTable::translate(Addr vaddr, Addr &paddr)
{
    const Entry *entry = lookup(vaddr);
    if (!entry) {
        DPRINTF(MMU, "Couldn't Translate: %#x\n", vaddr);
        return false;
    }
    paddr = pageOffset(vaddr) + entry->paddr;
    DPRINTF(MMU, "Translating: %#x->%#x\n", vaddr, paddr);
    return true;
}

Fault
EmulationPageTable::translate(RequestPtr req)
{
    Addr paddr;
    assert(pageAlign(req->getVaddr() + req->getSize() - 1) ==
           pageAlign(req->getVaddr()));
    if (!translate(req->getVaddr(), paddr))
        return Fault(new GenericPageTableFault(req->getVaddr()));
    req->setPaddr(paddr);
    if ((paddr & (pageSize - 1)) + req->getSize() > pageSize) {
        panic("Request spans page boundaries!\n");
        return NoFault;
    }
    return NoFault;
}

void
EmulationPageTable::serialize(CheckpointOut &cp) const
{
    paramOut(cp, "ptable.size", pTable.size());

    PTable::size_type count = 0;
    for (auto &pte : pTable) {
        ScopedCheckpointSection sec(cp, csprintf("Entry%d", count++));

        paramOut(cp, "vaddr", pte.first);
        paramOut(cp, "paddr", pte.second.paddr);
        paramOut(cp, "flags", pte.second.flags);
    }
    assert(count == pTable.size());
}

void
EmulationPageTable::unserialize(CheckpointIn &cp)
{
    int count;
    paramIn(cp, "ptable.size", count);

    for (int i = 0; i < count; ++i) {
        ScopedCheckpointSection sec(cp, csprintf("Entry%d", i));

        Addr vaddr;
        UNSERIALIZE_SCALAR(vaddr);
        Addr paddr;
        uint64_t flags;
        UNSERIALIZE_SCALAR(paddr);
        UNSERIALIZE_SCALAR(flags);

        pTable.emplace(vaddr, Entry(paddr, flags));
    }
}

<commit_msg>mem, sim-se: Fixed seg-fault in EmulationPageTable::remap<commit_after>/*
 * Copyright (c) 2014 Advanced Micro Devices, Inc.
 * Copyright (c) 2003 The Regents of The University of Michigan
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are
 * met: redistributions of source code must retain the above copyright
 * notice, this list of conditions and the following disclaimer;
 * redistributions in binary form must reproduce the above copyright
 * notice, this list of conditions and the following disclaimer in the
 * documentation and/or other materials provided with the distribution;
 * neither the name of the copyright holders nor the names of its
 * contributors may be used to endorse or promote products derived from
 * this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * Authors: Steve Reinhardt
 *          Ron Dreslinski
 *          Ali Saidi
 */

/**
 * @file
 * Definitions of functional page table.
 */
#include "mem/page_table.hh"

#include <string>

#include "base/trace.hh"
#include "debug/MMU.hh"
#include "sim/faults.hh"
#include "sim/serialize.hh"

using namespace std;

void
EmulationPageTable::map(Addr vaddr, Addr paddr, int64_t size, uint64_t flags)
{
    bool clobber = flags & Clobber;
    // starting address must be page aligned
    assert(pageOffset(vaddr) == 0);

    DPRINTF(MMU, "Allocating Page: %#x-%#x\n", vaddr, vaddr + size);

    while (size > 0) {
        auto it = pTable.find(vaddr);
        if (it != pTable.end()) {
            // already mapped
            panic_if(!clobber,
                     "EmulationPageTable::allocate: addr %#x already mapped",
                     vaddr);
            it->second = Entry(paddr, flags);
        } else {
            pTable.emplace(vaddr, Entry(paddr, flags));
        }

        size -= pageSize;
        vaddr += pageSize;
        paddr += pageSize;
    }
}

void
EmulationPageTable::remap(Addr vaddr, int64_t size, Addr new_vaddr)
{
    assert(pageOffset(vaddr) == 0);
    assert(pageOffset(new_vaddr) == 0);

    DPRINTF(MMU, "moving pages from vaddr %08p to %08p, size = %d\n", vaddr,
            new_vaddr, size);

    while (size > 0) {
        auto new_it = pTable.find(new_vaddr);
        auto old_it = pTable.find(vaddr);
        assert(old_it != pTable.end() && new_it == pTable.end());

        pTable.emplace(new_vaddr, old_it->second);
        pTable.erase(old_it);
        size -= pageSize;
        vaddr += pageSize;
        new_vaddr += pageSize;
    }
}

void
EmulationPageTable::getMappings(std::vector<std::pair<Addr, Addr>> *addr_maps)
{
    for (auto &iter : pTable)
        addr_maps->push_back(make_pair(iter.first, iter.second.paddr));
}

void
EmulationPageTable::unmap(Addr vaddr, int64_t size)
{
    assert(pageOffset(vaddr) == 0);

    DPRINTF(MMU, "Unmapping page: %#x-%#x\n", vaddr, vaddr + size);

    while (size > 0) {
        auto it = pTable.find(vaddr);
        assert(it != pTable.end());
        pTable.erase(it);
        size -= pageSize;
        vaddr += pageSize;
    }
}

bool
EmulationPageTable::isUnmapped(Addr vaddr, int64_t size)
{
    // starting address must be page aligned
    assert(pageOffset(vaddr) == 0);

    for (int64_t offset = 0; offset < size; offset += pageSize)
        if (pTable.find(vaddr + offset) != pTable.end())
            return false;

    return true;
}

const EmulationPageTable::Entry *
EmulationPageTable::lookup(Addr vaddr)
{
    Addr page_addr = pageAlign(vaddr);
    PTableItr iter = pTable.find(page_addr);
    if (iter == pTable.end())
        return nullptr;
    return &(iter->second);
}

bool
EmulationPageTable::translate(Addr vaddr, Addr &paddr)
{
    const Entry *entry = lookup(vaddr);
    if (!entry) {
        DPRINTF(MMU, "Couldn't Translate: %#x\n", vaddr);
        return false;
    }
    paddr = pageOffset(vaddr) + entry->paddr;
    DPRINTF(MMU, "Translating: %#x->%#x\n", vaddr, paddr);
    return true;
}

Fault
EmulationPageTable::translate(RequestPtr req)
{
    Addr paddr;
    assert(pageAlign(req->getVaddr() + req->getSize() - 1) ==
           pageAlign(req->getVaddr()));
    if (!translate(req->getVaddr(), paddr))
        return Fault(new GenericPageTableFault(req->getVaddr()));
    req->setPaddr(paddr);
    if ((paddr & (pageSize - 1)) + req->getSize() > pageSize) {
        panic("Request spans page boundaries!\n");
        return NoFault;
    }
    return NoFault;
}

void
EmulationPageTable::serialize(CheckpointOut &cp) const
{
    paramOut(cp, "ptable.size", pTable.size());

    PTable::size_type count = 0;
    for (auto &pte : pTable) {
        ScopedCheckpointSection sec(cp, csprintf("Entry%d", count++));

        paramOut(cp, "vaddr", pte.first);
        paramOut(cp, "paddr", pte.second.paddr);
        paramOut(cp, "flags", pte.second.flags);
    }
    assert(count == pTable.size());
}

void
EmulationPageTable::unserialize(CheckpointIn &cp)
{
    int count;
    paramIn(cp, "ptable.size", count);

    for (int i = 0; i < count; ++i) {
        ScopedCheckpointSection sec(cp, csprintf("Entry%d", i));

        Addr vaddr;
        UNSERIALIZE_SCALAR(vaddr);
        Addr paddr;
        uint64_t flags;
        UNSERIALIZE_SCALAR(paddr);
        UNSERIALIZE_SCALAR(flags);

        pTable.emplace(vaddr, Entry(paddr, flags));
    }
}

<|endoftext|>


<commit_before>//------------------------------------------------------------------------------
//  ModuleWindow.cc
//------------------------------------------------------------------------------
#include "ModuleWindow.h"
#include "IMUI/IMUI.h"
#include "yakc_core/roms.h"

OryolClassImpl(ModuleWindow);

using namespace Oryol;
using namespace yakc;

//------------------------------------------------------------------------------
void
ModuleWindow::Setup(kc85& kc) {
    this->setupModules(kc);
    this->setName("Expansion Modules");
}

//------------------------------------------------------------------------------
void
ModuleWindow::drawModuleSlot(kc85& kc, ubyte slot_addr) {
    ImGui::PushID(slot_addr);
    ImGui::AlignFirstTextHeightToWidgets();
    ImGui::Text("SLOT %02X:", slot_addr); ImGui::SameLine();
    const kc85::module_slot& slot = kc.get_module_slot(slot_addr);
    if (ImGui::Button(slot.desc.name, ImVec2(192, 0))) {
        ImGui::OpenPopup("select");
    }
    if (ImGui::IsItemHovered()) {
        ImGui::SetTooltip(slot.desc.help);
    }
    ImGui::SameLine();
    ImGui::Text("type:%02X ctrl:%02X", slot.desc.type, slot.control_byte);
    if (ImGui::BeginPopup("select")) {
        for (const auto& mod : this->modules) {
            if (ImGui::Selectable(mod.name)) {
                kc.insert_module(slot_addr, mod);
            }
        }
        ImGui::EndPopup();
    }
    ImGui::PopID();
}

//------------------------------------------------------------------------------
bool
ModuleWindow::Draw(kc85& kc) {
    if (ImGui::Begin(this->title.AsCStr(), &this->Visible, ImGuiWindowFlags_AlwaysAutoResize)) {
        this->drawModuleSlot(kc, 0x08);     // base device, right expansion slot
        this->drawModuleSlot(kc, 0x0C);     // base device, left expansion slot
        ImGui::TextWrapped("Hover over slot buttons to get help about inserted module!");
    }
    ImGui::End();
    return this->Visible;
}

//------------------------------------------------------------------------------
void
ModuleWindow::setupModules(kc85& kc) {

    kc85::module_desc mod;

    // empty module slot
    mod.help = "Click to select module!";
    kc.insert_module(0x08, mod);    // just set the help text...
    kc.insert_module(0x0C, mod);    // just set the help text...
    this->modules.Add(mod);

    // M022 EXPANDER RAM
    mod.name = "M022 EXPANDER-RAM (16KB)";
    mod.help = "A 16 KByte RAM expansion module.\n\n"
        "SWITCH [SLOT] 43: map to address 0x4000\n"
        "SWITCH [SLOT] 83: map to address 0x8000\n"
        "SWITCH [SLOT] 00: switch module off\n\n"
        "...where [SLOT] is 08 or 0C";
    mod.type = 0xF4;
    mod.writable = true;
    mod.size = 0x4000;
    this->modules.Add(mod);

    // M026 FORTH
    YAKC_ASSERT(sizeof(rom_forth) == 0x2000);
    mod.name = "M026 FORTH";
    mod.help = "FORTH language expansion module.\n\n"
        "First deactivate the BASIC ROM with:\n"
        "SWITCH 02 00\n\n"
        "Then activate FORTH with:\n"
        "SWITCH [SLOT] C1\n\n"
        "...where [SLOT] is 08 or 0C";
    mod.type = 0xFB;
    mod.writable = false;
    mod.size = 0x2000;
    mod.ptr = rom_forth;
    this->modules.Add(mod);
}<commit_msg>Module window UI tweaks<commit_after>//------------------------------------------------------------------------------
//  ModuleWindow.cc
//------------------------------------------------------------------------------
#include "ModuleWindow.h"
#include "IMUI/IMUI.h"
#include "yakc_core/roms.h"

OryolClassImpl(ModuleWindow);

using namespace Oryol;
using namespace yakc;

//------------------------------------------------------------------------------
void
ModuleWindow::Setup(kc85& kc) {
    this->setupModules(kc);
    this->setName("Expansion Modules");
}

//------------------------------------------------------------------------------
void
ModuleWindow::drawModuleSlot(kc85& kc, ubyte slot_addr) {
    ImGui::PushID(slot_addr);
    ImGui::AlignFirstTextHeightToWidgets();
    ImGui::Text("SLOT %02X:", slot_addr); ImGui::SameLine();
    const kc85::module_slot& slot = kc.get_module_slot(slot_addr);
    if (ImGui::Button(slot.desc.name, ImVec2(192, 0))) {
        ImGui::OpenPopup("select");
    }
    if (ImGui::IsItemHovered()) {
        ImGui::SetTooltip(slot.desc.help);
    }
    ImGui::SameLine();
    ImGui::Text("type:%02X ctrl:%02X", slot.desc.type, slot.control_byte);
    if (ImGui::BeginPopup("select")) {
        for (const auto& mod : this->modules) {
            if (ImGui::Selectable(mod.name)) {
                kc.insert_module(slot_addr, mod);
            }
        }
        ImGui::EndPopup();
    }
    ImGui::PopID();
}

//------------------------------------------------------------------------------
bool
ModuleWindow::Draw(kc85& kc) {
    ImGui::SetNextWindowSize(ImVec2(384, 116), ImGuiSetCond_Once);
    if (ImGui::Begin(this->title.AsCStr(), &this->Visible, ImGuiWindowFlags_NoResize)) {
        this->drawModuleSlot(kc, 0x08);     // base device, right expansion slot
        this->drawModuleSlot(kc, 0x0C);     // base device, left expansion slot
        ImGui::TextWrapped("Hover over slot buttons to get help about inserted module!");
    }
    ImGui::End();
    return this->Visible;
}

//------------------------------------------------------------------------------
void
ModuleWindow::setupModules(kc85& kc) {

    kc85::module_desc mod;

    // empty module slot
    mod.help = "Click to select module!";
    kc.insert_module(0x08, mod);    // just set the help text...
    kc.insert_module(0x0C, mod);    // just set the help text...
    this->modules.Add(mod);

    // M022 EXPANDER RAM
    mod.name = "M022 EXPANDER-RAM (16KB)";
    mod.help = "A 16 KByte RAM expansion module.\n\n"
        "SWITCH [SLOT] 43: map to address 0x4000\n"
        "SWITCH [SLOT] 83: map to address 0x8000\n"
        "SWITCH [SLOT] 00: switch module off\n\n"
        "...where [SLOT] is 08 or 0C";
    mod.type = 0xF4;
    mod.writable = true;
    mod.size = 0x4000;
    this->modules.Add(mod);

    // M026 FORTH
    YAKC_ASSERT(sizeof(rom_forth) == 0x2000);
    mod.name = "M026 FORTH";
    mod.help = "FORTH language expansion module.\n\n"
        "First deactivate the BASIC ROM with:\n"
        "SWITCH 02 00\n\n"
        "Then activate FORTH with:\n"
        "SWITCH [SLOT] C1\n\n"
        "...where [SLOT] is 08 or 0C";
    mod.type = 0xFB;
    mod.writable = false;
    mod.size = 0x2000;
    mod.ptr = rom_forth;
    this->modules.Add(mod);
}<|endoftext|>


<commit_before>#include <stdio.h>
#include <stdlib.h>

#include "App.h"
#include <Directory.h>
#include <NodeMonitor.h>
#include <Entry.h>
#include <Path.h>
#include <String.h>
#include <File.h>

/*
* Sets up the Node Monitoring for Dropbox folder and contents
* and creates data structure for determining which files are deleted or edited
*/
App::App(void)
  : BApplication("application/x-vnd.lh-MyDropboxClient")
{
  //start watching ~/Dropbox folder contents (create, delete, move)
  BDirectory dir("/boot/home/Dropbox"); //don't use ~ here
  node_ref nref;
  status_t err;
  if(dir.InitCheck() == B_OK){
    dir.GetNodeRef(&nref);
    err = watch_node(&nref, B_WATCH_DIRECTORY, BMessenger(this));
    if(err != B_OK)
      printf("Watch Node: Not OK\n");
  }

  // record each file in the folder so that we know the name on deletion
  BEntry *entry = new BEntry;
  status_t err2;
  err = dir.GetNextEntry(entry);
  BPath *path;
  BFile *file;
  while(err == B_OK) //loop over files
  {
    file = new BFile(entry, B_READ_ONLY);
    this->tracked_files.AddItem((void*)(file)); //add file to my list
    path = new BPath;
    entry->GetPath(path);
    printf("tracking: %s\n",path->Path());
    this->tracked_filepaths.AddItem((void*)path);
    err2 = entry->GetNodeRef(&nref);
    if(err2 == B_OK)
    {
      err2 = watch_node(&nref, B_WATCH_STAT, be_app_messenger); //watch for edits
      if(err2 != B_OK)
        printf("Watch file Node: Not OK\n");
    }
    entry = new BEntry;
    err = dir.GetNextEntry(entry);
  }
  //delete that last BEntry...
}

/*
* Runs a command in the terminal, given the string you'd type
*/
int
run_script(const char *cmd)
{
  char buf[BUFSIZ];
  FILE *ptr;

  if ((ptr = popen(cmd, "r")) != NULL)
    while (fgets(buf, BUFSIZ, ptr) != NULL)
      (void) printf("RAWR%s", buf);
  (void) pclose(ptr);
  return 0;
}

/*
* Given a local file path,
* call the script to delete the corresponding Dropbox file
*/
void
delete_file_on_dropbox(const char * filepath)
{
  printf("Telling Dropbox to Delete\n");
  BString s, dbfp;
  s = BString(filepath);
  s.RemoveFirst("/boot/home/Dropbox");
  dbfp << "python db_rm.py " << s;
  printf("%s\n",dbfp.String());
  run_script(dbfp);
}

/*
* Convert a local absolute filepath to a Dropbox one
* by removing the <path to Dropbox> from the beginning
*/
BString local_to_db_filepath(const char * local_path)
{
  BString s;
  s = BString(local_path);
  s.RemoveFirst("/boot/home/Dropbox/");
  return s;
}

/*
* Given the local file path of a new file,
* run the script to upload it to Dropbox
*/
void
add_file_to_dropbox(const char * filepath)
{
  BString s, dbfp;
  dbfp = local_to_db_filepath(filepath);
  s << "python db_put.py " << BString(filepath) << " " << dbfp;
  printf("local filepath:%s\n",filepath);
  printf("dropbox filepath:%s\n",dbfp.String());
  run_script(s.String());
}

/*
* Given the local file path of a new folder,
* run the script to mkdir on Dropbox
*/
void
add_folder_to_dropbox(const char * filepath)
{
  BString s;
  s << "python db_mkdir.py " << local_to_db_filepath(filepath);
  printf("local filepath: %s\n", filepath);
  printf("db filepath: %s\n", local_to_db_filepath(filepath).String());
  run_script(s.String());
}

/*
* TODO
* Given a "file/folder moved" message,
* figure out whether to call add or delete
* and with what file path
* and then call add/delete.
*/
void
moved_file(BMessage *msg)
{
  //is this file being move into or out of ~/Dropbox?
  run_script("python db_ls.py");
}

/*
* Given a local file path,
* update the corresponding file on Dropbox
*/
void
update_file_in_dropbox(const char * filepath)
{
  add_file_to_dropbox(filepath); //just put it?
}

/*
* Message Handling Function
* If it's a node monitor message,
* then figure out what to do based on it.
* Otherwise, let BApplication handle it.
*/
void
App::MessageReceived(BMessage *msg)
{
  switch(msg->what)
  {
    case B_NODE_MONITOR:
    {
      printf("Received Node Monitor Alert\n");
      status_t err;
      int32 opcode;
      err = msg->FindInt32("opcode",&opcode);
      if(err == B_OK)
      {
        printf("what:%d\topcode:%d\n",msg->what, opcode);
        switch(opcode)
        {
          case B_ENTRY_CREATED:
          {
            printf("NEW FILE\n");
            entry_ref ref;
            BPath path;
            const char * name;
            msg->FindInt32("device",&ref.device);
            msg->FindInt64("directory",&ref.directory);
            msg->FindString("name",&name);
            printf("name:%s\n",name);
            ref.set_name(name);
            BEntry new_file = BEntry(&ref);
            new_file.GetPath(&path);
            add_file_to_dropbox(path.Path());
            break;
          }
          case B_ENTRY_MOVED:
          {
            printf("MOVED FILE\n");
            moved_file(msg);
            break;
          }
          case B_ENTRY_REMOVED:
          {
            printf("DELETED FILE\n");
            node_ref nref, cref;
            msg->FindInt32("device",&nref.device);
            msg->FindInt64("node",&nref.node);
            BFile *filePtr;
            int32 ktr = 0;
            int32 limit = this->tracked_files.CountItems();
            printf("About to loop %d times\n", limit);
            while((filePtr = (BFile*)this->tracked_files.ItemAt(ktr))&&(ktr<limit))
            {
              printf("In loop.\n");
              filePtr->GetNodeRef(&cref);
              printf("GotNodeRef\n");
              if(nref == cref)
              {
                printf("Deleting it\n");
                BPath *path = (BPath*)this->tracked_filepaths.ItemAt(ktr);
                printf("%s\n",path->Path());
                delete_file_on_dropbox(path->Path());
                break; //break out of loop
              }
              ktr++;
            }
            break;
          }
          case B_STAT_CHANGED:
          {
            printf("EDITED FILE\n");
            node_ref nref1,nref2;
            msg->FindInt32("device",&nref1.device);
            msg->FindInt64("node",&nref1.node);
            BEntry * entryPtr;
            int32 ktr = 0;
            while((entryPtr = (BEntry *)this->tracked_files.ItemAt(ktr++)))
            {
              entryPtr->GetNodeRef(&nref2);
              if(nref1 == nref2)
              {
                BPath path;
                entryPtr->GetPath(&path);
                update_file_in_dropbox(path.Path());
                break;
              }
            }
            break;
          }
          default:
          {
            printf("default case opcode...\n");
          }
        }
      }
      break;
    }
    default:
    {
      printf("default msg\n");
      BApplication::MessageReceived(msg);
      break;
    }
  }
}

int
main(void)
{
  //set up application (watch Dropbox folder & contents)
  App *app = new App();

  //start the application
  app->Run();

  //clean up now that we're shutting down
  delete app;
  return 0;
}
<commit_msg>When a new local file is created, add it and it's filepath to the tracking data structures.<commit_after>#include <stdio.h>
#include <stdlib.h>

#include "App.h"
#include <Directory.h>
#include <NodeMonitor.h>
#include <Entry.h>
#include <Path.h>
#include <String.h>
#include <File.h>

/*
* Sets up the Node Monitoring for Dropbox folder and contents
* and creates data structure for determining which files are deleted or edited
*/
App::App(void)
  : BApplication("application/x-vnd.lh-MyDropboxClient")
{
  //start watching ~/Dropbox folder contents (create, delete, move)
  BDirectory dir("/boot/home/Dropbox"); //don't use ~ here
  node_ref nref;
  status_t err;
  if(dir.InitCheck() == B_OK){
    dir.GetNodeRef(&nref);
    err = watch_node(&nref, B_WATCH_DIRECTORY, BMessenger(this));
    if(err != B_OK)
      printf("Watch Node: Not OK\n");
  }

  // record each file in the folder so that we know the name on deletion
  BEntry *entry = new BEntry;
  status_t err2;
  err = dir.GetNextEntry(entry);
  BPath *path;
  BFile *file;
  while(err == B_OK) //loop over files
  {
    file = new BFile(entry, B_READ_ONLY);
    this->tracked_files.AddItem((void*)(file)); //add file to my list
    path = new BPath;
    entry->GetPath(path);
    printf("tracking: %s\n",path->Path());
    this->tracked_filepaths.AddItem((void*)path);
    err2 = entry->GetNodeRef(&nref);
    if(err2 == B_OK)
    {
      err2 = watch_node(&nref, B_WATCH_STAT, be_app_messenger); //watch for edits
      if(err2 != B_OK)
        printf("Watch file Node: Not OK\n");
    }
    entry = new BEntry;
    err = dir.GetNextEntry(entry);
  }
  //delete that last BEntry...
}

/*
* Runs a command in the terminal, given the string you'd type
*/
int
run_script(const char *cmd)
{
  char buf[BUFSIZ];
  FILE *ptr;

  if ((ptr = popen(cmd, "r")) != NULL)
    while (fgets(buf, BUFSIZ, ptr) != NULL)
      (void) printf("RAWR%s", buf);
  (void) pclose(ptr);
  return 0;
}

/*
* Given a local file path,
* call the script to delete the corresponding Dropbox file
*/
void
delete_file_on_dropbox(const char * filepath)
{
  printf("Telling Dropbox to Delete\n");
  BString s, dbfp;
  s = BString(filepath);
  s.RemoveFirst("/boot/home/Dropbox");
  dbfp << "python db_rm.py " << s;
  printf("%s\n",dbfp.String());
  run_script(dbfp);
}

/*
* Convert a local absolute filepath to a Dropbox one
* by removing the <path to Dropbox> from the beginning
*/
BString local_to_db_filepath(const char * local_path)
{
  BString s;
  s = BString(local_path);
  s.RemoveFirst("/boot/home/Dropbox/");
  return s;
}

/*
* Given the local file path of a new file,
* run the script to upload it to Dropbox
*/
void
add_file_to_dropbox(const char * filepath)
{
  BString s, dbfp;
  dbfp = local_to_db_filepath(filepath);
  s << "python db_put.py " << BString(filepath) << " " << dbfp;
  printf("local filepath:%s\n",filepath);
  printf("dropbox filepath:%s\n",dbfp.String());
  run_script(s.String());
}

/*
* Given the local file path of a new folder,
* run the script to mkdir on Dropbox
*/
void
add_folder_to_dropbox(const char * filepath)
{
  BString s;
  s << "python db_mkdir.py " << local_to_db_filepath(filepath);
  printf("local filepath: %s\n", filepath);
  printf("db filepath: %s\n", local_to_db_filepath(filepath).String());
  run_script(s.String());
}

/*
* TODO
* Given a "file/folder moved" message,
* figure out whether to call add or delete
* and with what file path
* and then call add/delete.
*/
void
moved_file(BMessage *msg)
{
  //is this file being move into or out of ~/Dropbox?
  run_script("python db_ls.py");
}

/*
* Given a local file path,
* update the corresponding file on Dropbox
*/
void
update_file_in_dropbox(const char * filepath)
{
  add_file_to_dropbox(filepath); //just put it?
}

/*
* Message Handling Function
* If it's a node monitor message,
* then figure out what to do based on it.
* Otherwise, let BApplication handle it.
*/
void
App::MessageReceived(BMessage *msg)
{
  switch(msg->what)
  {
    case B_NODE_MONITOR:
    {
      printf("Received Node Monitor Alert\n");
      status_t err;
      int32 opcode;
      err = msg->FindInt32("opcode",&opcode);
      if(err == B_OK)
      {
        printf("what:%d\topcode:%d\n",msg->what, opcode);
        switch(opcode)
        {
          case B_ENTRY_CREATED:
          {
            printf("NEW FILE\n");
            entry_ref ref;
            BPath path;
            const char * name;
            msg->FindInt32("device",&ref.device);
            msg->FindInt64("directory",&ref.directory);
            msg->FindString("name",&name);
            printf("name:%s\n",name);
            ref.set_name(name);
            BEntry new_file = BEntry(&ref);
            new_file.GetPath(&path);
            add_file_to_dropbox(path.Path());

            BFile *file = new BFile(&new_file, B_READ_ONLY);
            this->tracked_files.AddItem((void*)file);
            BPath *path2 = new BPath;
            new_file.GetPath(path2);
            this->tracked_filepaths.AddItem((void*)path2);
            break;
          }
          case B_ENTRY_MOVED:
          {
            printf("MOVED FILE\n");
            moved_file(msg);
            break;
          }
          case B_ENTRY_REMOVED:
          {
            printf("DELETED FILE\n");
            node_ref nref, cref;
            msg->FindInt32("device",&nref.device);
            msg->FindInt64("node",&nref.node);
            BFile *filePtr;
            int32 ktr = 0;
            int32 limit = this->tracked_files.CountItems();
            printf("About to loop %d times\n", limit);
            while((filePtr = (BFile*)this->tracked_files.ItemAt(ktr))&&(ktr<limit))
            {
              printf("In loop.\n");
              filePtr->GetNodeRef(&cref);
              printf("GotNodeRef\n");
              if(nref == cref)
              {
                printf("Deleting it\n");
                BPath *path = (BPath*)this->tracked_filepaths.ItemAt(ktr);
                printf("%s\n",path->Path());
                delete_file_on_dropbox(path->Path());
                break; //break out of loop
              }
              ktr++;
            }
            break;
          }
          case B_STAT_CHANGED:
          {
            printf("EDITED FILE\n");
            node_ref nref1,nref2;
            msg->FindInt32("device",&nref1.device);
            msg->FindInt64("node",&nref1.node);
            BEntry * entryPtr;
            int32 ktr = 0;
            while((entryPtr = (BEntry *)this->tracked_files.ItemAt(ktr++)))
            {
              entryPtr->GetNodeRef(&nref2);
              if(nref1 == nref2)
              {
                BPath path;
                entryPtr->GetPath(&path);
                update_file_in_dropbox(path.Path());
                break;
              }
            }
            break;
          }
          default:
          {
            printf("default case opcode...\n");
          }
        }
      }
      break;
    }
    default:
    {
      printf("default msg\n");
      BApplication::MessageReceived(msg);
      break;
    }
  }
}

int
main(void)
{
  //set up application (watch Dropbox folder & contents)
  App *app = new App();

  //start the application
  app->Run();

  //clean up now that we're shutting down
  delete app;
  return 0;
}
<|endoftext|>


<commit_before>#include "BUBBLES.H"

#include "DRAW.H"
#include "GPU.H"
#include "ROOMLOAD.H"
#include "SPECIFIC.H"
#include "GTEREG.H"
#include "DRAWSPKS.H"
#include "LARA.H"

#include <LIBGPU.H>

void DrawFlash()
{
	UNIMPLEMENTED();
}

void insert_psx_clip_window(long x, long y, long w, long h, long arg_10)
{
#if 0
	DRAWENV env;//0x1F800000
	int v0;

	v0 = db.current_buffer;

	if (db.current_buffer != 0)
	{
		v0 = 0xF00000;
		y += SCREEN_HEIGHT;
	}
	//loc_8FDCC
	SetDefDrawEnv(&env, x, y, w, h);
	((int*)&env.ofs)[0] = v0;
	env.dtd = 1;
	env.isbg = 0;
	SetDrawEnv((DR_ENV*)db.polyptr, &env);
	db.ot[2563] = (unsigned int)db.polyptr;
	((unsigned int*)db.polyptr)[0] = (unsigned int)db.ot[2563] | 0x6000000;
	db.polyptr += 0x1C;
#endif
}

void CalcClipWindow_ONGTE(short room_number, long unknown)//8F374,
{
	int t2;
	int t5;
	int t4;
	int t7;
	int a0;
	int a1;
	int a2;
	int a3;
	int t3;
	short* t1;
	int t0;
	struct room_info* r;//v1
	int v0;

	t2 = unknown & 0xFFFF;
	t5 = room_number & 0xFFFF;
	//t7 = lara_item;
	t4 = number_draw_rooms;
	//t6 = room;
	t7 = ((int*)lara_item)[6];
	a0 = 512;
	a1 = 0;
	a2 = 256;
	a3 = 0;

	t3 = 0;
	if (t4 > 0)
	{
		t1 = &draw_rooms[0];

		//loc_8F3AC
		do
		{
			t0 = t1[0];
			t3++;

			r = &room[t0];

			if (t2 != 0)
			{
				if (!(r->flags & (RF_WIND_BLOWS_PONYTAIL | RF_SKYBOX_VISIBLE)))
				{
					goto loc_8F440;
				}
			}//loc_8F3DC

			if (t0 == t5)
			{
				if (t2 == 0)
				{
					goto loc_8F440;
				}
			}

			//loc_8F3EC
			if (t0 == t7)
			{
				if (t2 == 0)
				{
					goto loc_8F440;
				}
			}

			//loc_8F3FC
			t0 = r->left;
			v0 = r->right;

			if (t0 < a0)
			{
				a0 = t0 + 1;
			}
			//loc_8F414
			t0 = r->top;
			if (a1 < v0)
			{
				a1 = v0 - 1;
			}
			//loc_8F420
			v0 = r->bottom;

			if (t0 < a2)
			{
				a2 = t0 + 1;
			}

			if (a3 < v0)
			{
				a3 = v0 - 1;
			}

loc_8F440:
			t1++;
		} while (t3 < t4);

		a0 <<= 16;
		a1 <<= 16;
		a2 <<= 16;
		a3 <<= 16;

		R = a0 & 0xFF;
		G = (a0 >> 8) & 0xFF;
		B = (a0 >> 16) & 0xFF;
		CODE = (a0 >> 24) & 0xFF;
		RGB0 = a1;
		RGB1 = a2;
		RGB2 = a3;

	}//locret_8F46C
}

void DrawPsxTile(long a0, long a1, long a2, long a3, long var_10)//8F770(<), 917B4(<) (F)
{
	if ((unsigned long)db.polyptr < (unsigned long)db.polybuf_limit)
	{
		char* ptr = db.polyptr;
		setDrawTPage(ptr, 0, 1, (a3 & 3) << 5);

#if defined(USE_32_BIT_ADDR)
		setlen(ptr, 6);
#else
		setlen(ptr, 5);
#endif
		ptr += sizeof(DR_TPAGE);
		setTile(ptr);
		setSemiTrans(ptr, 1);
		setRGB0((TILE*)ptr, getR(a2), getG(a2), getB(a2));
		setXY0((TILE*)ptr, a0 & 0xFFFF, (a0 >> 16) & 0xFFFF);
		setWH((TILE*)ptr, a1 & 0xFFFF, (a1 >> 16) & 0xFFFF);
		ptr += sizeof(TILE);
#if defined(USE_32_BIT_ADDR)
		addPrim(db.ot + (var_10 * 2), db.polyptr);
#else
		addPrim(db.ot + var_10);
#endif
		db.polyptr = ptr;
	}
	//locret_8F7D0
}

void TriggerDynamic(long x, long y, long z, int falloff, int r, int g, int b)
{
	UNIMPLEMENTED();
}

void DEL_ApplyMatrixSV(int v0, int v1, short* m)//(F)
{
	VX0 = (v0 & 0xFFFF);
	VY0 = (v0 >> 16) & 0xFFFF;
	VZ0 = v1;

	docop2(0x486012);

	m[0] = IR1;
	m[1] = IR2;
	m[2] = IR3;
}

void SetInventoryLighting(int rgb0, int rgb1, int rgb2, int rgb3)//(F)
{
	int t5 = rgb0;
	int t6 = rgb1;
	int t7 = rgb2;
	int t8 = rgb3;
	int t0 = R11 | ((R12 & 0xFFFF) << 16);
	int t1 = R13 | ((R21 & 0xFFFF) << 16);
	int t2 = R22 | ((R23 & 0xFFFF) << 16);
	int t3 = R31 | ((R32 & 0xFFFF) << 16);
	int t4 = R33;

	int at = ((int*)&CamGTE.m00)[0];
	int v0 = ((int*)&CamGTE.m00)[1];
	int v1 = ((int*)&CamGTE.m00)[2];
	int a1 = ((int*)&CamGTE.m00)[3];
	int a0 = ((int*)&CamGTE.m00)[4];

	R11 = at & 0xFFFF;
	R12 = (at >> 16) & 0xFFFF;
	R13 = v0 & 0xFFFF;
	R21 = (v0 >> 16) & 0xFFFF;
	R22 = v1 & 0xFFFF;
	R23 = (v1 >> 16) & 0xFFFF;
	R31 = a1 & 0xFFFF;
	R32 = (a1 >> 16) & 0xFFFF;
	R33 = a0;

	DEL_ApplyMatrixSV(0xF000F000, 0x1000, &LightPos.m00);
	DEL_ApplyMatrixSV(0xF0001000, 0xFFFFF000, &LightPos.m10);
	DEL_ApplyMatrixSV(0x10000000, 0xFFFFF000, &LightPos.m20);

	R11 = t0 & 0xFFFF;
	R12 = (t0 >> 16) & 0xFFFF;
	R13 = t1 & 0xFFFF;
	R21 = (t1 >> 16) & 0xFFFF;
	R22 = t2 & 0xFFFF;
	R23 = (t2 >> 16) & 0xFFFF;
	R31 = t3 & 0xFFFF;
	R32 = (t3 >> 16) & 0xFFFF;
	R33 = t4;

	v0 = (t5 & 0xFF) << 4;
	v1 = (t6 & 0xFF) << 20;
	v0 |= v1;

	LR1 = v0 & 0xFFFF;
	LR2 = v0 >> 16;

	v0 = (t7 & 0xFF) << 4;
	v1 = (t5 & 0xFF00) << 12;
	v0 |= v1;

	LR3 = v0 & 0xFFFF;
	LG1 = v0 >> 16;

	v0 = (t6 >> 4) & 0xFF0;
	v1 = (t7 & 0xFF00) << 12;
	v0 |= v1;
	LG2 = v0 & 0xFFFF;
	LG3 = v0 >> 16;

	v0 = (t5 >> 12) & 0xFF0;
	v1 = ((t6 >> 12) & 0xFF0) << 16;
	v0 |= v1;

	LB1 = v0 & 0xFFFF;
	LB2 = v0 >> 16;

	v0 = (t7 >> 12) & 0xFF0;
	LB3 = v0;

	a0 = (t8 & 0xFF) << 4;
	a1 = (t8 >> 4) & 0xFF0;
	int a2 = (t8 >> 12) & 0xFF0;
	RBK = a0;
	GBK = a1;
	BBK = a2;

	R = 128;
	G = 128;
	B = 128;
	CODE = 0;
	DQB = 0;
}

void DrawMonoScreen(int a0)
{
	int i = 0;
	int j = 0;
	unsigned long* pp = db.ot;//a2
#if defined(USE_32_BIT_ADDR)
	unsigned long t5 = db.ot[2000*2];
#else
	unsigned long t5 = db.ot[2000];
#endif
	char* a00 = db.polyptr;

	//loc_8F17C
	for(i = 0; i < 4; i++)
	{
		//loc_8F180
		for (j = 0; j < 8; j++)
		{
#if defined(USE_32_BIT_ADDR)
			((int*)a00)[3] = 0;
			((int*)a00)[4] = 0;
			((int*)a00)[5] = a0 | 0x64000000;
			((int*)a00)[6] = ((i << 6) << 16) | (j << 6);
			((int*)a00)[8] = 0x400040;

			((int*)a00)[0] = t5;
			setlen(a00, 7);
			((int*)a00)[2] = (((j << 6) >> 8) + 13) | 0xE1000610;
			((short*)a00)[14] = (((i << 6) & 0xFF) << 8) | ((j << 6) & 0xFF);
			((short*)a00)[15] = (ClutStartY << 6) | 0x3C;
#else
			((int*)a00)[2] = 0;
			((int*)a00)[3] = a0 | 0x64000000;
			((int*)a00)[4] = ((i << 6) << 16) | (j << 6);
			((int*)a00)[6] = 0x400040;

			((int*)a00)[0] = t5 | 0x6000000;
			((int*)a00)[1] = (((j << 6) >> 8) + 13) | 0xE1000610;
			((short*)a00)[10] = (((i << 6) & 0xFF) << 8) | ((j << 6) & 0xFF);
			((short*)a00)[11] = (ClutStartY << 6) | 0x3C;
#endif

			t5 = (unsigned long)a00;
			a00 += sizeof(DR_TPAGE) + sizeof(SPRT);//TODO actual polytype
		}
		j = 0;
	}
#if defined(USE_32_BIT_ADDR)
	db.ot[2000*2] = (unsigned long)t5;
#else
	db.ot[2000] = (unsigned long)t5;
#endif
	db.polyptr = (char*)a00;

	return;
}<commit_msg>[Specific-PSXPC_N] Implement TriggerDynamic.<commit_after>#include "BUBBLES.H"

#include "CAMERA.H"
#include "DRAW.H"
#include "GPU.H"
#include "ROOMLOAD.H"
#include "SPECIFIC.H"
#include "GTEREG.H"
#include "DRAWSPKS.H"
#include "LARA.H"
#include "EFFECT2.H"

#include <LIBGPU.H>

void DrawFlash()
{
	UNIMPLEMENTED();
}

void insert_psx_clip_window(long x, long y, long w, long h, long arg_10)
{
#if 0
	DRAWENV env;//0x1F800000
	int v0;

	v0 = db.current_buffer;

	if (db.current_buffer != 0)
	{
		v0 = 0xF00000;
		y += SCREEN_HEIGHT;
	}
	//loc_8FDCC
	SetDefDrawEnv(&env, x, y, w, h);
	((int*)&env.ofs)[0] = v0;
	env.dtd = 1;
	env.isbg = 0;
	SetDrawEnv((DR_ENV*)db.polyptr, &env);
	db.ot[2563] = (unsigned int)db.polyptr;
	((unsigned int*)db.polyptr)[0] = (unsigned int)db.ot[2563] | 0x6000000;
	db.polyptr += 0x1C;
#endif
}

void CalcClipWindow_ONGTE(short room_number, long unknown)//8F374,
{
	int t2;
	int t5;
	int t4;
	int t7;
	int a0;
	int a1;
	int a2;
	int a3;
	int t3;
	short* t1;
	int t0;
	struct room_info* r;//v1
	int v0;

	t2 = unknown & 0xFFFF;
	t5 = room_number & 0xFFFF;
	//t7 = lara_item;
	t4 = number_draw_rooms;
	//t6 = room;
	t7 = ((int*)lara_item)[6];
	a0 = 512;
	a1 = 0;
	a2 = 256;
	a3 = 0;

	t3 = 0;
	if (t4 > 0)
	{
		t1 = &draw_rooms[0];

		//loc_8F3AC
		do
		{
			t0 = t1[0];
			t3++;

			r = &room[t0];

			if (t2 != 0)
			{
				if (!(r->flags & (RF_WIND_BLOWS_PONYTAIL | RF_SKYBOX_VISIBLE)))
				{
					goto loc_8F440;
				}
			}//loc_8F3DC

			if (t0 == t5)
			{
				if (t2 == 0)
				{
					goto loc_8F440;
				}
			}

			//loc_8F3EC
			if (t0 == t7)
			{
				if (t2 == 0)
				{
					goto loc_8F440;
				}
			}

			//loc_8F3FC
			t0 = r->left;
			v0 = r->right;

			if (t0 < a0)
			{
				a0 = t0 + 1;
			}
			//loc_8F414
			t0 = r->top;
			if (a1 < v0)
			{
				a1 = v0 - 1;
			}
			//loc_8F420
			v0 = r->bottom;

			if (t0 < a2)
			{
				a2 = t0 + 1;
			}

			if (a3 < v0)
			{
				a3 = v0 - 1;
			}

loc_8F440:
			t1++;
		} while (t3 < t4);

		a0 <<= 16;
		a1 <<= 16;
		a2 <<= 16;
		a3 <<= 16;

		R = a0 & 0xFF;
		G = (a0 >> 8) & 0xFF;
		B = (a0 >> 16) & 0xFF;
		CODE = (a0 >> 24) & 0xFF;
		RGB0 = a1;
		RGB1 = a2;
		RGB2 = a3;

	}//locret_8F46C
}

void DrawPsxTile(long a0, long a1, long a2, long a3, long var_10)//8F770(<), 917B4(<) (F)
{
	if ((unsigned long)db.polyptr < (unsigned long)db.polybuf_limit)
	{
		char* ptr = db.polyptr;
		setDrawTPage(ptr, 0, 1, (a3 & 3) << 5);

#if defined(USE_32_BIT_ADDR)
		setlen(ptr, 6);
#else
		setlen(ptr, 5);
#endif
		ptr += sizeof(DR_TPAGE);
		setTile(ptr);
		setSemiTrans(ptr, 1);
		setRGB0((TILE*)ptr, getR(a2), getG(a2), getB(a2));
		setXY0((TILE*)ptr, a0 & 0xFFFF, (a0 >> 16) & 0xFFFF);
		setWH((TILE*)ptr, a1 & 0xFFFF, (a1 >> 16) & 0xFFFF);
		ptr += sizeof(TILE);
#if defined(USE_32_BIT_ADDR)
		addPrim(db.ot + (var_10 * 2), db.polyptr);
#else
		addPrim(db.ot + var_10);
#endif
		db.polyptr = ptr;
	}
	//locret_8F7D0
}

void TriggerDynamic(long x, long y, long z, int falloff, int r, int g, int b)
{
	struct DYNAMIC* t3 = NULL;
	struct DYNAMIC* t0 = NULL;
	int t1 = 0;
	int t2 = 0;
	int v1 = 0;

	if (x >= 0 && falloff >= 0 && falloff != 0)
	{
		t3 = &dynamics[0];
		v1 = number_dynamics;
		t0 = t3;
		if (number_dynamics == 32)
		{
			t1 = 0;
			t2 = 0;

			//loc_8FE50
			do
			{
				IR1 = camera.pos.x - t3->x;
				IR2 = camera.pos.y - t3->y;
				IR3 = camera.pos.z - t3->z;

				docop2(0xA00428);

				t2++;
				if (t1 < MAC3 + MAC1 + MAC2)
				{
					t1 = MAC3 + MAC1 + MAC2;
					t0 = t3;
				}
				t3++;
				//loc_8FEB0
			} while (t2 < 32);

			t3 = t0;
			v1 = number_dynamics - 1;

		}
		else
		{
			//loc_8FECC
			t3 = &dynamics[v1];
		}

		//loc_8FEDC
		t3->falloff = falloff << 8;
		t3->on = 1;
		t3->x = x;
		t3->y = y;
		t3->z = z;

		number_dynamics = v1 + 1;

		t3->r = r;
		t3->g = g;
		t3->b = b;

		if (falloff >= 8)
		{
			t3->FalloffScale = 0x200000 / (falloff << 8);
			t3->r = (r * falloff) >> 3;
			t3->g = (g * falloff) >> 3;
			t3->b = (b * falloff) >> 3;
		}//locret_8FF68
	}
	//locret_8FF68
}

void DEL_ApplyMatrixSV(int v0, int v1, short* m)//(F)
{
	VX0 = (v0 & 0xFFFF);
	VY0 = (v0 >> 16) & 0xFFFF;
	VZ0 = v1;

	docop2(0x486012);

	m[0] = IR1;
	m[1] = IR2;
	m[2] = IR3;
}

void SetInventoryLighting(int rgb0, int rgb1, int rgb2, int rgb3)//(F)
{
	int t5 = rgb0;
	int t6 = rgb1;
	int t7 = rgb2;
	int t8 = rgb3;
	int t0 = R11 | ((R12 & 0xFFFF) << 16);
	int t1 = R13 | ((R21 & 0xFFFF) << 16);
	int t2 = R22 | ((R23 & 0xFFFF) << 16);
	int t3 = R31 | ((R32 & 0xFFFF) << 16);
	int t4 = R33;

	int at = ((int*)&CamGTE.m00)[0];
	int v0 = ((int*)&CamGTE.m00)[1];
	int v1 = ((int*)&CamGTE.m00)[2];
	int a1 = ((int*)&CamGTE.m00)[3];
	int a0 = ((int*)&CamGTE.m00)[4];

	R11 = at & 0xFFFF;
	R12 = (at >> 16) & 0xFFFF;
	R13 = v0 & 0xFFFF;
	R21 = (v0 >> 16) & 0xFFFF;
	R22 = v1 & 0xFFFF;
	R23 = (v1 >> 16) & 0xFFFF;
	R31 = a1 & 0xFFFF;
	R32 = (a1 >> 16) & 0xFFFF;
	R33 = a0;

	DEL_ApplyMatrixSV(0xF000F000, 0x1000, &LightPos.m00);
	DEL_ApplyMatrixSV(0xF0001000, 0xFFFFF000, &LightPos.m10);
	DEL_ApplyMatrixSV(0x10000000, 0xFFFFF000, &LightPos.m20);

	R11 = t0 & 0xFFFF;
	R12 = (t0 >> 16) & 0xFFFF;
	R13 = t1 & 0xFFFF;
	R21 = (t1 >> 16) & 0xFFFF;
	R22 = t2 & 0xFFFF;
	R23 = (t2 >> 16) & 0xFFFF;
	R31 = t3 & 0xFFFF;
	R32 = (t3 >> 16) & 0xFFFF;
	R33 = t4;

	v0 = (t5 & 0xFF) << 4;
	v1 = (t6 & 0xFF) << 20;
	v0 |= v1;

	LR1 = v0 & 0xFFFF;
	LR2 = v0 >> 16;

	v0 = (t7 & 0xFF) << 4;
	v1 = (t5 & 0xFF00) << 12;
	v0 |= v1;

	LR3 = v0 & 0xFFFF;
	LG1 = v0 >> 16;

	v0 = (t6 >> 4) & 0xFF0;
	v1 = (t7 & 0xFF00) << 12;
	v0 |= v1;
	LG2 = v0 & 0xFFFF;
	LG3 = v0 >> 16;

	v0 = (t5 >> 12) & 0xFF0;
	v1 = ((t6 >> 12) & 0xFF0) << 16;
	v0 |= v1;

	LB1 = v0 & 0xFFFF;
	LB2 = v0 >> 16;

	v0 = (t7 >> 12) & 0xFF0;
	LB3 = v0;

	a0 = (t8 & 0xFF) << 4;
	a1 = (t8 >> 4) & 0xFF0;
	int a2 = (t8 >> 12) & 0xFF0;
	RBK = a0;
	GBK = a1;
	BBK = a2;

	R = 128;
	G = 128;
	B = 128;
	CODE = 0;
	DQB = 0;
}

void DrawMonoScreen(int a0)
{
	int i = 0;
	int j = 0;
	unsigned long* pp = db.ot;//a2
#if defined(USE_32_BIT_ADDR)
	unsigned long t5 = db.ot[2000*2];
#else
	unsigned long t5 = db.ot[2000];
#endif
	char* a00 = db.polyptr;

	//loc_8F17C
	for(i = 0; i < 4; i++)
	{
		//loc_8F180
		for (j = 0; j < 8; j++)
		{
#if defined(USE_32_BIT_ADDR)
			((int*)a00)[3] = 0;
			((int*)a00)[4] = 0;
			((int*)a00)[5] = a0 | 0x64000000;
			((int*)a00)[6] = ((i << 6) << 16) | (j << 6);
			((int*)a00)[8] = 0x400040;

			((int*)a00)[0] = t5;
			setlen(a00, 7);
			((int*)a00)[2] = (((j << 6) >> 8) + 13) | 0xE1000610;
			((short*)a00)[14] = (((i << 6) & 0xFF) << 8) | ((j << 6) & 0xFF);
			((short*)a00)[15] = (ClutStartY << 6) | 0x3C;
#else
			((int*)a00)[2] = 0;
			((int*)a00)[3] = a0 | 0x64000000;
			((int*)a00)[4] = ((i << 6) << 16) | (j << 6);
			((int*)a00)[6] = 0x400040;

			((int*)a00)[0] = t5 | 0x6000000;
			((int*)a00)[1] = (((j << 6) >> 8) + 13) | 0xE1000610;
			((short*)a00)[10] = (((i << 6) & 0xFF) << 8) | ((j << 6) & 0xFF);
			((short*)a00)[11] = (ClutStartY << 6) | 0x3C;
#endif

			t5 = (unsigned long)a00;
			a00 += sizeof(DR_TPAGE) + sizeof(SPRT);//TODO actual polytype
		}
		j = 0;
	}
#if defined(USE_32_BIT_ADDR)
	db.ot[2000*2] = (unsigned long)t5;
#else
	db.ot[2000] = (unsigned long)t5;
#endif
	db.polyptr = (char*)a00;

	return;
}<|endoftext|>


<commit_before>/*
 * This file is part of crash-reporter
 *
 * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
 *
 * Contact: Ville Ilvonen <ville.p.ilvonen@nokia.com>
 * Author: Riku Halonen <riku.halonen@nokia.com>
 *
 * This program 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 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser 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
 *
 */

#include "stdlib.h"

#include <QSignalSpy>
#include <QDir>
#include <QSettings>
#include <QCoreApplication>
#include <QProcess>
#include <QDBusConnection>
#include <QDBusConnectionInterface>

#include "ut_creporterdaemon.h"
#include "creportercoreregistry.h"
#include "creportertestutils.h"
#include "creporterdaemon.h"
#include "creporterdaemon_p.h"
#include "creporterprivacysettingsmodel.h"
#include "creporternamespace.h"
#include "creporterdialogserverdbusadaptor.h"
#include "creportersettingsinit_p.h"
#include "creporternotification.h"

static const char* test_files1[] = {
	"test_core.rcore.lzo",
	"test_1234.rcore.lzo",
	"test_5678_core.rcore.lzo",
	};

static const char* test_files_invalid1[] = {
	".test_core.rcore.lzo",
    /*"crash-reporter-daemon.rcore.lzo",
    "crash-reporter-ui.rcore.lzo",*/
	};

static bool serviceRegisteredReply;
// Overridden here to able to fake UI launch failing. Otherwise the Qt implementation seems
// to return true always in unit tests.
QDBusReply<bool> QDBusConnectionInterface::isServiceRegistered(const QString &serviceName) const
{
    Q_UNUSED(serviceName);
    QDBusMessage reply;
    reply << serviceRegisteredReply;
    return reply;
}

static bool notificationCreated;
static bool notificationUpdated;

// CReporterNotification mock object.
CReporterNotification::CReporterNotification(const QString &eventType,
                                             const QString &summary, const QString &body,
                                             QObject *parent)
{
    Q_UNUSED(eventType);
    Q_UNUSED(summary);
    Q_UNUSED(body);
    notificationCreated = true;
    Q_UNUSED(parent);
}

CReporterNotification::CReporterNotification(const QString &eventType, int id,
                                             QObject *parent)
{
    Q_UNUSED(eventType);
    Q_UNUSED(id);
    Q_UNUSED(parent);

    notificationCreated = true;
}

CReporterNotification::~CReporterNotification()
{}

int CReporterNotification::id()
{
    return 10;
}

void CReporterNotification::update(const QString &summary, const QString &body,
                                   int count)
{
    notificationUpdated = true;
    Q_UNUSED(body);
    Q_UNUSED(count)
}

void CReporterNotification::remove()
{}

void CReporterNotification::setTimeout(int ms)
{
    Q_UNUSED(ms);
}

const QString testSettingsFile("/tmp/crash-reporter-tests/user_settings/crash-reporter-settings/crash-reporter-privacy.conf");

TestDialogServer::TestDialogServer()
{
    callReceivedCalled = false;
    quitCalled = false;

    new CReporterDialogServerDBusAdaptor(this);
    QDBusConnection::sessionBus().registerService(CReporter::DialogServerServiceName);
    QDBusConnection::sessionBus().registerObject(CReporter::DialogServerObjectPath, this);
}

TestDialogServer::~TestDialogServer()
{
}

QDBusError::ErrorType TestDialogServer::callReceived(const QString &dialogName,
                                const QVariantList &arguments, const QDBusMessage &message) {

    requestedDialog = dialogName;
    callArguments = arguments;
    requestMessage = message;
    callReceivedCalled = true;

    return QDBusError::NoError;
}

void TestDialogServer::quit()
{
    quitCalled = true;
}

void Ut_CReporterDaemon::initTestCase()
{
	CReporterTestUtils::createTestMountpoints();
    daemon = 0;
    paths = 0;
    settings = 0;

    QDir dir;
    dir.mkpath("/tmp/crash-reporter-tests/user_settings");
}

void Ut_CReporterDaemon::init()
{
    notificationCreated = false;
    notificationUpdated = false;
    serviceRegisteredReply = true;

    static QCoreApplication *app = 0;

    if (app == 0) {
        int argc = 1;
        const char *argv[] = {"./ut_creporterdaemon", 0};
        app = new QCoreApplication(argc, (char **)argv);
    }

    settings = new QSettings(testSettingsFile, QSettings::NativeFormat);

    // Create test settings.
    settings->setValue(Settings::ValueNotifications, true);
    settings->setValue(Settings::ValueCoreDumping, true);
    settings->setValue(Settings::ValueAutoDeleteDuplicates, true);
    settings->setValue(Settings::ValueAutomaticSending, false);
    settings->setValue(Settings::ValueLifelog, false);

    settings->setValue(Privacy::ValueIncludeCore, true);
    settings->setValue(Privacy::ValueIncludeSysLog, true);
    settings->setValue(Privacy::ValueIncludePkgList, true);
    settings->sync();

    testDialogServer = new TestDialogServer();
    creporterSettingsInit(QString(), "/tmp/crash-reporter-tests/user_settings");
}

void Ut_CReporterDaemon::testInitiateDaemon()
{
    QStringList compareFiles;

    // Check that daemon is initiated successfully, registered to D-Bus and UI is launched.
    daemon = new CReporterDaemon;

    paths = daemon->d_ptr->registry->getCoreLocationPaths();
    CReporterTestUtils::createTestDataFiles(*paths, compareFiles, test_files1);

    QVERIFY(daemon->initiateDaemon() == true);

    QProcess dbusSend;
    dbusSend.start(QString("dbus-send --session --print-reply --dest=%1 %2 %3 string:%4")
                   .arg("org.freedesktop.DBus").arg("/").arg("org.freedesktop.DBus.GetConnectionUnixProcessID")
                   .arg(CReporter::DaemonServiceName));

    dbusSend.waitForFinished();
    QVERIFY(dbusSend.exitCode() == 0);

    daemon->stopService();

    dbusSend.start(QString("dbus-send --session --print-reply --dest=%1 %2 %3 string:%4")
                   .arg("org.freedesktop.DBus").arg("/").arg("org.freedesktop.DBus.GetConnectionUnixProcessID")
                   .arg(CReporter::DaemonServiceName));

    dbusSend.waitForFinished();
    QVERIFY(dbusSend.exitCode() != 0);

    QVERIFY(testDialogServer->callReceivedCalled == true);
    QVERIFY(testDialogServer->callArguments.at(0).type() == QVariant::StringList);
    QVERIFY(testDialogServer->requestedDialog == CReporter::SendSelectedDialogType);
    QStringList files = testDialogServer->callArguments.at(0).toStringList();
    QCOMPARE(files, compareFiles);

}

void Ut_CReporterDaemon::testDelayedStartup()
{
    // Check that daemon is initiated successfully after delay. UI is not launched, since no
    // cores are found.
    daemon = new CReporterDaemon;
    daemon->setDelayedStartup(5000);
    QVERIFY(daemon->d_ptr->timerId != 0);

    QTest::qWait(6000);

    QProcess dbusSend;
    dbusSend.start(QString("dbus-send --session --print-reply --dest=%1 %2 %3 string:%4")
                   .arg("org.freedesktop.DBus").arg("/").arg("org.freedesktop.DBus.GetConnectionUnixProcessID")
                   .arg(CReporter::DaemonServiceName));

    dbusSend.waitForFinished();
    QVERIFY(dbusSend.exitCode() == 0);

    daemon->stopService();

    dbusSend.start(QString("dbus-send --session --print-reply --dest=%1 %2 %3 string:%4")
                   .arg("org.freedesktop.DBus").arg("/").arg("org.freedesktop.DBus.GetConnectionUnixProcessID")
                   .arg(CReporter::DaemonServiceName));

    dbusSend.waitForFinished();
    QVERIFY(dbusSend.exitCode() != 0);
    QVERIFY(testDialogServer->callReceivedCalled == false);
}

void Ut_CReporterDaemon::testCollectAllCoreFiles()
{
    QStringList compareFiles;

    daemon = new CReporterDaemon;
    QVERIFY(daemon->initiateDaemon() == true);

    paths = daemon->d_ptr->registry->getCoreLocationPaths();

    CReporterTestUtils::createTestDataFiles(*paths, compareFiles, test_files1);

    QStringList files = daemon->collectAllCoreFiles();

    QCOMPARE(files.count(), compareFiles.count());

    QCOMPARE(files, compareFiles);

    CReporterTestUtils::removeDirectories(*paths);
}

void Ut_CReporterDaemon::testCollectAllCoreFilesNotValidFiles()
{
	QStringList compareFiles;
	QFile file;

    daemon = new CReporterDaemon;
    QVERIFY(daemon->initiateDaemon() == true);

    paths = daemon->d_ptr->registry->getCoreLocationPaths();

    CReporterTestUtils::createTestDataFiles(*paths, compareFiles, test_files_invalid1);

    QStringList files = daemon->collectAllCoreFiles();

    QCOMPARE(files.count(), 0);

    CReporterTestUtils::removeDirectories(*paths);
}

void Ut_CReporterDaemon::testMonitoringEnabledFromSettings()
{
    daemon = new CReporterDaemon;
    QVERIFY(daemon->initiateDaemon() == true);

    paths = daemon->d_ptr->registry->getCoreLocationPaths();

    QString filePath(paths->at(0));
    filePath.append("/foobar_core.rcore.lzo");

    QDir::setCurrent(paths->at(0));

    QFile file;
    file.setFileName("foobar_core.rcore.lzo");
    file.open(QIODevice::ReadWrite);
    file.close();

    QTest::qWait(50);

    QVERIFY(testDialogServer->callReceivedCalled == true);
    QVERIFY(testDialogServer->callArguments.at(0).type() == QVariant::String);
    QVERIFY(testDialogServer->requestedDialog == CReporter::NotifyNewDialogType);
    QString argument = testDialogServer->callArguments.at(0).toString();
    QCOMPARE(argument, filePath);

    QFile::remove(testSettingsFile);

    CReporterTestUtils::removeDirectories(*paths);
}

void Ut_CReporterDaemon::testMonitoringDisabledFromSettings()
{
    // Disable monitoring.
    settings->setValue(Settings::ValueNotifications, false);
    settings->sync();

    daemon = new CReporterDaemon;
    QVERIFY(daemon->initiateDaemon() == true);

    paths = daemon->d_ptr->registry->getCoreLocationPaths();

    QString filePath(paths->at(0));
    filePath.append("/foobar_core.rcore.lzo");

    QDir::setCurrent(paths->at(0));

    QFile file;
    file.setFileName("foobar_core.rcore.lzo");
    file.open(QIODevice::ReadWrite);
    file.close();

    QTest::qWait(50);

    QVERIFY(testDialogServer->callReceivedCalled == false);
    QFile::remove(testSettingsFile);

    CReporterTestUtils::removeDirectories(*paths);
}

void Ut_CReporterDaemon::testLaunchingUIFailed()
{
    // Test situation, when UI is tried to launch, but it fails.
    // In this case error notification is created.
    QStringList compareFiles;
    daemon = new CReporterDaemon;
    paths = daemon->d_ptr->registry->getCoreLocationPaths();
    CReporterTestUtils::createTestDataFiles(*paths, compareFiles, test_files1);

    // Destroy UI.
    delete testDialogServer;
    testDialogServer = 0;

    serviceRegisteredReply = false;

    QVERIFY(daemon->initiateDaemon() == true);

    QTest::qWait(100);

    QVERIFY(notificationCreated == true);
}

void Ut_CReporterDaemon::cleanupTestCase()
{
    CReporterTestUtils::removeTestMountpoints();

    UNUSED_RESULT(system("rm -rf /tmp/crash-reporter-tests"));
}

void Ut_CReporterDaemon::cleanup()
{
    if (daemon != 0) {
        delete daemon;
        daemon = 0;
    }

    if (paths != 0) {
        CReporterTestUtils::removeDirectories(*paths);
        delete paths;
        paths = 0;
    }

    if (settings != 0) {
        delete settings;
        settings = 0;
    }

    if (testDialogServer != 0) {
        delete testDialogServer;
        testDialogServer = 0;
    }
}

QTEST_APPLESS_MAIN(Ut_CReporterDaemon)

<commit_msg>Fix -Wunused-parameter in ut_creporterdaemon.cpp<commit_after>/*
 * This file is part of crash-reporter
 *
 * Copyright (C) 2010 Nokia Corporation and/or its subsidiary(-ies).
 *
 * Contact: Ville Ilvonen <ville.p.ilvonen@nokia.com>
 * Author: Riku Halonen <riku.halonen@nokia.com>
 *
 * This program 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 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
 * Lesser General Public License for more details.
 *
 * You should have received a copy of the GNU Lesser 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
 *
 */

#include "stdlib.h"

#include <QSignalSpy>
#include <QDir>
#include <QSettings>
#include <QCoreApplication>
#include <QProcess>
#include <QDBusConnection>
#include <QDBusConnectionInterface>

#include "ut_creporterdaemon.h"
#include "creportercoreregistry.h"
#include "creportertestutils.h"
#include "creporterdaemon.h"
#include "creporterdaemon_p.h"
#include "creporterprivacysettingsmodel.h"
#include "creporternamespace.h"
#include "creporterdialogserverdbusadaptor.h"
#include "creportersettingsinit_p.h"
#include "creporternotification.h"

static const char* test_files1[] = {
	"test_core.rcore.lzo",
	"test_1234.rcore.lzo",
	"test_5678_core.rcore.lzo",
	};

static const char* test_files_invalid1[] = {
	".test_core.rcore.lzo",
    /*"crash-reporter-daemon.rcore.lzo",
    "crash-reporter-ui.rcore.lzo",*/
	};

static bool serviceRegisteredReply;
// Overridden here to able to fake UI launch failing. Otherwise the Qt implementation seems
// to return true always in unit tests.
QDBusReply<bool> QDBusConnectionInterface::isServiceRegistered(const QString &serviceName) const
{
    Q_UNUSED(serviceName);
    QDBusMessage reply;
    reply << serviceRegisteredReply;
    return reply;
}

static bool notificationCreated;
static bool notificationUpdated;

// CReporterNotification mock object.
CReporterNotification::CReporterNotification(const QString &eventType,
                                             const QString &summary, const QString &body,
                                             QObject *parent)
{
    Q_UNUSED(eventType);
    Q_UNUSED(summary);
    Q_UNUSED(body);
    notificationCreated = true;
    Q_UNUSED(parent);
}

CReporterNotification::CReporterNotification(const QString &eventType, int id,
                                             QObject *parent)
{
    Q_UNUSED(eventType);
    Q_UNUSED(id);
    Q_UNUSED(parent);

    notificationCreated = true;
}

CReporterNotification::~CReporterNotification()
{}

int CReporterNotification::id()
{
    return 10;
}

void CReporterNotification::update(const QString &summary, const QString &body,
                                   int count)
{
    notificationUpdated = true;
    Q_UNUSED(summary)
    Q_UNUSED(body);
    Q_UNUSED(count)
}

void CReporterNotification::remove()
{}

void CReporterNotification::setTimeout(int ms)
{
    Q_UNUSED(ms);
}

const QString testSettingsFile("/tmp/crash-reporter-tests/user_settings/crash-reporter-settings/crash-reporter-privacy.conf");

TestDialogServer::TestDialogServer()
{
    callReceivedCalled = false;
    quitCalled = false;

    new CReporterDialogServerDBusAdaptor(this);
    QDBusConnection::sessionBus().registerService(CReporter::DialogServerServiceName);
    QDBusConnection::sessionBus().registerObject(CReporter::DialogServerObjectPath, this);
}

TestDialogServer::~TestDialogServer()
{
}

QDBusError::ErrorType TestDialogServer::callReceived(const QString &dialogName,
                                const QVariantList &arguments, const QDBusMessage &message) {

    requestedDialog = dialogName;
    callArguments = arguments;
    requestMessage = message;
    callReceivedCalled = true;

    return QDBusError::NoError;
}

void TestDialogServer::quit()
{
    quitCalled = true;
}

void Ut_CReporterDaemon::initTestCase()
{
	CReporterTestUtils::createTestMountpoints();
    daemon = 0;
    paths = 0;
    settings = 0;

    QDir dir;
    dir.mkpath("/tmp/crash-reporter-tests/user_settings");
}

void Ut_CReporterDaemon::init()
{
    notificationCreated = false;
    notificationUpdated = false;
    serviceRegisteredReply = true;

    static QCoreApplication *app = 0;

    if (app == 0) {
        int argc = 1;
        const char *argv[] = {"./ut_creporterdaemon", 0};
        app = new QCoreApplication(argc, (char **)argv);
    }

    settings = new QSettings(testSettingsFile, QSettings::NativeFormat);

    // Create test settings.
    settings->setValue(Settings::ValueNotifications, true);
    settings->setValue(Settings::ValueCoreDumping, true);
    settings->setValue(Settings::ValueAutoDeleteDuplicates, true);
    settings->setValue(Settings::ValueAutomaticSending, false);
    settings->setValue(Settings::ValueLifelog, false);

    settings->setValue(Privacy::ValueIncludeCore, true);
    settings->setValue(Privacy::ValueIncludeSysLog, true);
    settings->setValue(Privacy::ValueIncludePkgList, true);
    settings->sync();

    testDialogServer = new TestDialogServer();
    creporterSettingsInit(QString(), "/tmp/crash-reporter-tests/user_settings");
}

void Ut_CReporterDaemon::testInitiateDaemon()
{
    QStringList compareFiles;

    // Check that daemon is initiated successfully, registered to D-Bus and UI is launched.
    daemon = new CReporterDaemon;

    paths = daemon->d_ptr->registry->getCoreLocationPaths();
    CReporterTestUtils::createTestDataFiles(*paths, compareFiles, test_files1);

    QVERIFY(daemon->initiateDaemon() == true);

    QProcess dbusSend;
    dbusSend.start(QString("dbus-send --session --print-reply --dest=%1 %2 %3 string:%4")
                   .arg("org.freedesktop.DBus").arg("/").arg("org.freedesktop.DBus.GetConnectionUnixProcessID")
                   .arg(CReporter::DaemonServiceName));

    dbusSend.waitForFinished();
    QVERIFY(dbusSend.exitCode() == 0);

    daemon->stopService();

    dbusSend.start(QString("dbus-send --session --print-reply --dest=%1 %2 %3 string:%4")
                   .arg("org.freedesktop.DBus").arg("/").arg("org.freedesktop.DBus.GetConnectionUnixProcessID")
                   .arg(CReporter::DaemonServiceName));

    dbusSend.waitForFinished();
    QVERIFY(dbusSend.exitCode() != 0);

    QVERIFY(testDialogServer->callReceivedCalled == true);
    QVERIFY(testDialogServer->callArguments.at(0).type() == QVariant::StringList);
    QVERIFY(testDialogServer->requestedDialog == CReporter::SendSelectedDialogType);
    QStringList files = testDialogServer->callArguments.at(0).toStringList();
    QCOMPARE(files, compareFiles);

}

void Ut_CReporterDaemon::testDelayedStartup()
{
    // Check that daemon is initiated successfully after delay. UI is not launched, since no
    // cores are found.
    daemon = new CReporterDaemon;
    daemon->setDelayedStartup(5000);
    QVERIFY(daemon->d_ptr->timerId != 0);

    QTest::qWait(6000);

    QProcess dbusSend;
    dbusSend.start(QString("dbus-send --session --print-reply --dest=%1 %2 %3 string:%4")
                   .arg("org.freedesktop.DBus").arg("/").arg("org.freedesktop.DBus.GetConnectionUnixProcessID")
                   .arg(CReporter::DaemonServiceName));

    dbusSend.waitForFinished();
    QVERIFY(dbusSend.exitCode() == 0);

    daemon->stopService();

    dbusSend.start(QString("dbus-send --session --print-reply --dest=%1 %2 %3 string:%4")
                   .arg("org.freedesktop.DBus").arg("/").arg("org.freedesktop.DBus.GetConnectionUnixProcessID")
                   .arg(CReporter::DaemonServiceName));

    dbusSend.waitForFinished();
    QVERIFY(dbusSend.exitCode() != 0);
    QVERIFY(testDialogServer->callReceivedCalled == false);
}

void Ut_CReporterDaemon::testCollectAllCoreFiles()
{
    QStringList compareFiles;

    daemon = new CReporterDaemon;
    QVERIFY(daemon->initiateDaemon() == true);

    paths = daemon->d_ptr->registry->getCoreLocationPaths();

    CReporterTestUtils::createTestDataFiles(*paths, compareFiles, test_files1);

    QStringList files = daemon->collectAllCoreFiles();

    QCOMPARE(files.count(), compareFiles.count());

    QCOMPARE(files, compareFiles);

    CReporterTestUtils::removeDirectories(*paths);
}

void Ut_CReporterDaemon::testCollectAllCoreFilesNotValidFiles()
{
	QStringList compareFiles;
	QFile file;

    daemon = new CReporterDaemon;
    QVERIFY(daemon->initiateDaemon() == true);

    paths = daemon->d_ptr->registry->getCoreLocationPaths();

    CReporterTestUtils::createTestDataFiles(*paths, compareFiles, test_files_invalid1);

    QStringList files = daemon->collectAllCoreFiles();

    QCOMPARE(files.count(), 0);

    CReporterTestUtils::removeDirectories(*paths);
}

void Ut_CReporterDaemon::testMonitoringEnabledFromSettings()
{
    daemon = new CReporterDaemon;
    QVERIFY(daemon->initiateDaemon() == true);

    paths = daemon->d_ptr->registry->getCoreLocationPaths();

    QString filePath(paths->at(0));
    filePath.append("/foobar_core.rcore.lzo");

    QDir::setCurrent(paths->at(0));

    QFile file;
    file.setFileName("foobar_core.rcore.lzo");
    file.open(QIODevice::ReadWrite);
    file.close();

    QTest::qWait(50);

    QVERIFY(testDialogServer->callReceivedCalled == true);
    QVERIFY(testDialogServer->callArguments.at(0).type() == QVariant::String);
    QVERIFY(testDialogServer->requestedDialog == CReporter::NotifyNewDialogType);
    QString argument = testDialogServer->callArguments.at(0).toString();
    QCOMPARE(argument, filePath);

    QFile::remove(testSettingsFile);

    CReporterTestUtils::removeDirectories(*paths);
}

void Ut_CReporterDaemon::testMonitoringDisabledFromSettings()
{
    // Disable monitoring.
    settings->setValue(Settings::ValueNotifications, false);
    settings->sync();

    daemon = new CReporterDaemon;
    QVERIFY(daemon->initiateDaemon() == true);

    paths = daemon->d_ptr->registry->getCoreLocationPaths();

    QString filePath(paths->at(0));
    filePath.append("/foobar_core.rcore.lzo");

    QDir::setCurrent(paths->at(0));

    QFile file;
    file.setFileName("foobar_core.rcore.lzo");
    file.open(QIODevice::ReadWrite);
    file.close();

    QTest::qWait(50);

    QVERIFY(testDialogServer->callReceivedCalled == false);
    QFile::remove(testSettingsFile);

    CReporterTestUtils::removeDirectories(*paths);
}

void Ut_CReporterDaemon::testLaunchingUIFailed()
{
    // Test situation, when UI is tried to launch, but it fails.
    // In this case error notification is created.
    QStringList compareFiles;
    daemon = new CReporterDaemon;
    paths = daemon->d_ptr->registry->getCoreLocationPaths();
    CReporterTestUtils::createTestDataFiles(*paths, compareFiles, test_files1);

    // Destroy UI.
    delete testDialogServer;
    testDialogServer = 0;

    serviceRegisteredReply = false;

    QVERIFY(daemon->initiateDaemon() == true);

    QTest::qWait(100);

    QVERIFY(notificationCreated == true);
}

void Ut_CReporterDaemon::cleanupTestCase()
{
    CReporterTestUtils::removeTestMountpoints();

    UNUSED_RESULT(system("rm -rf /tmp/crash-reporter-tests"));
}

void Ut_CReporterDaemon::cleanup()
{
    if (daemon != 0) {
        delete daemon;
        daemon = 0;
    }

    if (paths != 0) {
        CReporterTestUtils::removeDirectories(*paths);
        delete paths;
        paths = 0;
    }

    if (settings != 0) {
        delete settings;
        settings = 0;
    }

    if (testDialogServer != 0) {
        delete testDialogServer;
        testDialogServer = 0;
    }
}

QTEST_APPLESS_MAIN(Ut_CReporterDaemon)

<|endoftext|>


<commit_before>#include "SPHERES.H"

#include "DRAW.H"
#include "CONTROL.H"
#include "SPECIFIC.H"
#include "GETSTUFF.H"

int GetSpheres(struct ITEM_INFO* item, struct SPHERE* sptr, int worldspace)
{
	UNIMPLEMENTED();
	return 0;
}

void GetJointAbsPosition(struct ITEM_INFO* item, struct PHD_VECTOR* pos, int joint)
{
	UNIMPLEMENTED();
	return;
}

int IsRoomOutside(long x, long y, long z)//(F)
{
	int v1;
	int a0;
	int v0;
	short roomOffset;//v0
	int t0;
	struct room_info* r;//s1
	short room_number;
	struct FLOOR_INFO* floor;//s0
	int h;//v1
	int c;//v0
	int i;
	//s3 = x
	//s2 = y
	//s4 = z

	v1 = x >> 12;
	a0 = z >> 12;

	v0 = v1 << 3;
	v0 -= v1;
	v0 <<= 2;
	v0 -= v1;
	v0 += a0;
	//v1 = OutsideRoomOffsets
	if (x < 0 && z < 0)
	{
		return -2;
	}

	//loc_8EF54
	roomOffset = OutsideRoomOffsets[v0];

	if (roomOffset == -1)
	{
		return -2;
	}

	t0 = roomOffset & 0x7FFF;

	if (roomOffset < 0)
	{
		r = &room[t0];

		if (y < r->maxceiling)
		{
			return -2;
		}

		if (r->minfloor < y)
		{
			return -2;
		}

		if (z < (r->z + 1024))
		{
			return -2;
		}

		if (r->z + ((r->x_size - 1) << 10) < z)
		{
			return -2;
		}

		if (x < (r->x + 1024))
		{
			return -2;
		}

		if (r->x + ((r->y_size - 1) << 10) < x)
		{
			return -2;
		}

		room_number = t0;
		floor = GetFloor(x, y, z, &room_number);
		h = GetHeight(floor, x, y, z);

		if (h == -32512 || h < y)
		{
			return -2;
		}

		c = GetCeiling(floor, x, y, z);

		if (y < c)
		{
			return -2;
		}

		if ((r->flags & (RF_FILL_WATER | RF_WIND_BLOWS_PONYTAIL)))
		{
			return 1;
		}

		return -3;
	}
	else
	{
		//loc_8EFF4
		if (OutsideRoomTable[roomOffset] == -1)
		{
			return -2;
		}

		//loc_8F000
		i = 0;
		while(i++)
		{
			r = &room[OutsideRoomTable[roomOffset]];

			if (y > r->maxceiling && r->minfloor > y &&
				z > (r->z + 1024) && r->z + ((r->x_size - 1) << 10) > z &&
				x > (r->x + 1024) && r->x + ((r->y_size - 1) << 10) > x)
			{
				//loc_8F07C
				IsRoomOutsideNo = OutsideRoomTable[roomOffset];
				room_number = IsRoomOutsideNo;
				floor = GetFloor(x, y, z, &room_number);
				h = GetHeight(floor, x, y, z);

				if (h == -32512 || h < y)
				{
					return -2;
				}

				c = GetCeiling(floor, x, y, z);

				if (y < c)
				{
					return -2;
				}

				if (r->flags & (RF_WIND_BLOWS_PONYTAIL | RF_FILL_WATER))
				{
					return 1;
				}

				return -3;

			}//loc_8F104

			if (OutsideRoomTable[roomOffset + i] == -1)
			{
				return -2;
			}
		}
	}

	return 0;
}<commit_msg>[Specific-PSXPC_N] - Implement GetJointAbsPosition<commit_after>#include "SPHERES.H"

#include "DRAW.H"
#include "CONTROL.H"
#include "SPECIFIC.H"
#include "GETSTUFF.H"
#include "GTEREG.H"
#include "LOAD_LEV.H"
#include "SETUP.H"
#include "MATHS.H"
#include <assert.h>

int GetSpheres(struct ITEM_INFO* item, struct SPHERE* sptr, int worldspace)
{
	UNIMPLEMENTED();
	return 0;
}

void GetJointAbsPosition(struct ITEM_INFO* item, struct PHD_VECTOR* pos, int joint)//8E860(<) 908A4(<) (F)
{
	struct object_info* object;//s1
	short* frames[2];//var_38
	int rate;//var_30
	int frac;//s0
	long* bone;//s0
	short* frameptr;//var_2C
	short* frameptr2;//var_28
	short* item_data;
	int t0;
	int t1;
	int t2;
	struct MATRIX3D* mat;//var_24

	object = &objects[item->object_number];
	mat = Matrix;
	frac = GetFrames(item, frames, &rate);
	mPushUnitMatrix();
	mSetTrans(0, 0, 0);
	mRotYXZ(item->pos.y_rot, item->pos.x_rot, item->pos.z_rot);

	item_data = (short*)item->data;
	bone = &bones[object->bone_index];

	if (frac == 0)
	{
		frameptr = &frames[0][9];
		mTranslateXYZ(frames[0][6], frames[0][7], frames[0][8]);///@FIXME reporting bad matrix here.
		mRotSuperPackedYXZ(&frameptr, 0);

		if (joint > 0)
		{
			//loc_8E92C
			do
			{
				if ((*bone & 1))
				{
					mPopMatrix();
				}//loc_8E94C

				if ((*bone & 2))
				{
					mPushMatrix();
				}
				//loc_8E95C
				mTranslateXYZ(bone[1], bone[2], bone[3]);
				mRotSuperPackedYXZ(&frameptr, 0);

				if (item_data != NULL && (*bone & 0x1C) && (*bone & 0x8))
				{
					mRotY(*item_data++);

					//loc_8E9A0
					if ((*bone & 0x4))
					{
						mRotX(*item_data++);
					}

					//loc_8E9B8
					if ((*bone & 0x10))
					{
						mRotZ(*item_data++);
					}
				}

				bone += 4;

			} while (joint--);
		}
		//loc_8E9D8
		mTranslateXYZ(pos->x, pos->y, pos->z);
	}
	else
	{
		//Math functions not impl
		assert(0);
#if 0
		//loc_8E9EC
		//a2 = &iMatrixStack[16];
		InitInterpolation(frac, rate, &iMatrixStack[16]);
		//v1 = frames[0]
		//t0 = frames[1]

		//v0 = &frames[0][9]
		frameptr = &frames[0][9];

		//v0 = &frames[1][9]
		iTranslateXYZ2(frames[0][6], frames[0][7], frames[0][8], frames[1][6], frames[1][7], frames[1][8]);
		mRotSuperPackedYXZ(&frameptr, 0);
		//iRotSuperPackedYXZ(&frameptr + 1, 0);

		//s1 = joint
		if (joint > 0)
		{
			//loc_8EA5C
			do
			{
				if ((*bone & 1))
				{
					iPopMatrix();
				}//loc_8EA7C

				if ((*bone & 2))
				{
					iPushMatrix();
				}
				//loc_8EA8C
				iTranslateXYZ(bone[1], bone[2], bone[3]);
				mRotSuperPackedYXZ(&frameptr, 0);
				iRotSuperPackedYXZ(&frameptr2, 0);

				if (item->data != NULL && (*bone & 0x1C) && (*bone & 0x8))
				{
					mRotY(*item_data);
					iRotY(*item_data++);
				}//loc_8EAE8

				if ((*bone & 0x4))
				{
					mRotX(*item_data);
					iRotX(*item_data++);
				}

				if ((*bone & 0x10))
				{
					mRotZ(*item_data);
					iRotZ(*item_data++);
				}
				bone += 4;
			} while (joint--);
		}//loc_8EB38
		iTranslateXYZ(pos->x, pos->y, pos->z);
		InterpolateMatrix();
#endif
	}

	pos->x = item->pos.x_pos + TRX;
	pos->y = item->pos.y_pos + TRY;
	pos->z = item->pos.z_pos + TRZ;

	Matrix = mat;
	mCopyMatrix(mat);

	return;
}

int IsRoomOutside(long x, long y, long z)//(F)
{
	int v1;
	int a0;
	int v0;
	short roomOffset;//v0
	int t0;
	struct room_info* r;//s1
	short room_number;
	struct FLOOR_INFO* floor;//s0
	int h;//v1
	int c;//v0
	int i;
	//s3 = x
	//s2 = y
	//s4 = z

	v1 = x >> 12;
	a0 = z >> 12;

	v0 = v1 << 3;
	v0 -= v1;
	v0 <<= 2;
	v0 -= v1;
	v0 += a0;
	//v1 = OutsideRoomOffsets
	if (x < 0 && z < 0)
	{
		return -2;
	}

	//loc_8EF54
	roomOffset = OutsideRoomOffsets[v0];

	if (roomOffset == -1)
	{
		return -2;
	}

	t0 = roomOffset & 0x7FFF;

	if (roomOffset < 0)
	{
		r = &room[t0];

		if (y < r->maxceiling)
		{
			return -2;
		}

		if (r->minfloor < y)
		{
			return -2;
		}

		if (z < (r->z + 1024))
		{
			return -2;
		}

		if (r->z + ((r->x_size - 1) << 10) < z)
		{
			return -2;
		}

		if (x < (r->x + 1024))
		{
			return -2;
		}

		if (r->x + ((r->y_size - 1) << 10) < x)
		{
			return -2;
		}

		room_number = t0;
		floor = GetFloor(x, y, z, &room_number);
		h = GetHeight(floor, x, y, z);

		if (h == -32512 || h < y)
		{
			return -2;
		}

		c = GetCeiling(floor, x, y, z);

		if (y < c)
		{
			return -2;
		}

		if ((r->flags & (RF_FILL_WATER | RF_WIND_BLOWS_PONYTAIL)))
		{
			return 1;
		}

		return -3;
	}
	else
	{
		//loc_8EFF4
		if (OutsideRoomTable[roomOffset] == -1)
		{
			return -2;
		}

		//loc_8F000
		i = 0;
		while(i++)
		{
			r = &room[OutsideRoomTable[roomOffset]];

			if (y > r->maxceiling && r->minfloor > y &&
				z > (r->z + 1024) && r->z + ((r->x_size - 1) << 10) > z &&
				x > (r->x + 1024) && r->x + ((r->y_size - 1) << 10) > x)
			{
				//loc_8F07C
				IsRoomOutsideNo = OutsideRoomTable[roomOffset];
				room_number = IsRoomOutsideNo;
				floor = GetFloor(x, y, z, &room_number);
				h = GetHeight(floor, x, y, z);

				if (h == -32512 || h < y)
				{
					return -2;
				}

				c = GetCeiling(floor, x, y, z);

				if (y < c)
				{
					return -2;
				}

				if (r->flags & (RF_WIND_BLOWS_PONYTAIL | RF_FILL_WATER))
				{
					return 1;
				}

				return -3;

			}//loc_8F104

			if (OutsideRoomTable[roomOffset + i] == -1)
			{
				return -2;
			}
		}
	}

	return 0;
}<|endoftext|>


<commit_before>/**
 * PANDA 3D SOFTWARE
 * Copyright (c) Carnegie Mellon University.  All rights reserved.
 *
 * All use of this software is subject to the terms of the revised BSD
 * license.  You should have received a copy of this license along
 * with this source code in a file named "LICENSE."
 *
 * @file vector_string.cxx
 * @author drose
 * @date 2000-05-15
 */

#include "vector_string.h"

#define EXPCL EXPCL_DTOOLCONFIG
#define EXPTP EXPTP_DTOOLCONFIG
#define TYPE std::string
#define NAME vector_string

#include "vector_src.cxx"

// Tell GCC that we'll take care of the instantiation explicitly here.
#ifdef __GNUC__
#pragma implementation
#endif
<commit_msg>dtool: Fix an inconsistent EXPCL/EXPTP<commit_after>/**
 * PANDA 3D SOFTWARE
 * Copyright (c) Carnegie Mellon University.  All rights reserved.
 *
 * All use of this software is subject to the terms of the revised BSD
 * license.  You should have received a copy of this license along
 * with this source code in a file named "LICENSE."
 *
 * @file vector_string.cxx
 * @author drose
 * @date 2000-05-15
 */

#include "vector_string.h"

#define EXPCL EXPCL_DTOOL
#define EXPTP EXPTP_DTOOL
#define TYPE std::string
#define NAME vector_string

#include "vector_src.cxx"

// Tell GCC that we'll take care of the instantiation explicitly here.
#ifdef __GNUC__
#pragma implementation
#endif
<|endoftext|>


<commit_before>#include "FileHelper.h"
#include "StringHelper.h"
#include "Config.h"

#include <wx/dir.h>
#include <wx/filename.h>
#ifndef _DEBUG
#include <wx/stdpaths.h>
#endif // _DEBUG

#include <set>

namespace ee
{

bool FileHelper::MkDir(const std::string& dir, bool rm)
{
	bool ret = true;
	if (wxDir::Exists(dir)) {
		if (rm) {
			wxFileName::Rmdir(dir, wxPATH_RMDIR_RECURSIVE);
			ret = wxFileName::Mkdir(dir, wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL);
		}
	} else {
		ret = wxFileName::Mkdir(dir, wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL);
	}
	return ret;
}

bool FileHelper::RmFile(const std::string& filepath)
{
	return wxRemoveFile(filepath);
}

bool FileHelper::IsFileExist(const std::string& filepath)
{
	return wxFileName::FileExists(filepath);
}

bool FileHelper::IsDirExist(const std::string& filepath)
{
	return wxFileName::DirExists(filepath);
}

void FileHelper::FetchAllFiles(const std::string& dirpath, wxArrayString& files)
{
	class DirTraverser : public wxDirTraverser
	{
	public:
		DirTraverser(wxArrayString& files)
			: m_files(files) {}

		virtual wxDirTraverseResult OnFile(const wxString& filename)
		{
			m_files.Add(filename);
			return wxDIR_CONTINUE;
		}

		virtual wxDirTraverseResult OnDir(const wxString& dirname)
		{
			return wxDIR_CONTINUE;
		}

	private:
		wxArrayString& m_files;

	}; // DirTraverser

	DirTraverser traverser(files);

	wxDir dir(dirpath);
	dir.Traverse(traverser);
}

void FileHelper::FetchAllFiles(const std::string& dirpath, const std::string& ignore_dir, wxArrayString& files)
{
	class DirTraverser : public wxDirTraverser
	{
	public:
		DirTraverser(wxArrayString& files, const wxString& ignore_dir)
			: m_files(files)
			, m_ignore_dir(ignore_dir)
		{}

		virtual wxDirTraverseResult OnFile(const wxString& filename)
		{
			m_files.Add(filename);
			return wxDIR_CONTINUE;
		}

		virtual wxDirTraverseResult OnDir(const wxString& dirname)
		{
			if (dirname == m_ignore_dir) {
				return wxDIR_IGNORE;
			} else {
				return wxDIR_CONTINUE;
			}
		}

	private:
		wxArrayString& m_files;
		std::string m_ignore_dir;

	}; // DirTraverser

	DirTraverser traverser(files, ignore_dir);

	wxDir dir(dirpath);
	dir.Traverse(traverser);
}

void FileHelper::FetchAllFiles(const std::string& dirpath, wxArrayString& files, FileType::Type type)
{
	class DirTraverser : public wxDirTraverser
	{
	public:
		DirTraverser(wxArrayString& files, FileType::Type type)
			: files(files), type(type) {}

		virtual wxDirTraverseResult OnFile(const wxString& filename)
		{
			if (FileType::IsType(filename.ToStdString(), type)) {
				files.Add(filename);
			}
			return wxDIR_CONTINUE;
		}

		virtual wxDirTraverseResult OnDir(const wxString& dirname)
		{
			return wxDIR_CONTINUE;
		}

	private:
		wxArrayString& files;
		FileType::Type type;

	}; // DirTraverser

	DirTraverser traverser(files, type);

	wxDir dir(dirpath);
	dir.Traverse(traverser);
}

void FileHelper::FetchCurrDirs(const std::string& dirpath, wxArrayString& dirs)
{
	class DirTraverser : public wxDirTraverser
	{
	public:
		DirTraverser(wxArrayString& files)
			: m_files(files) {}

		virtual wxDirTraverseResult OnFile(const wxString& filename)
		{
			return wxDIR_CONTINUE;
		}

		virtual wxDirTraverseResult OnDir(const wxString& dirname)
		{
			m_files.Add(dirname);
			return wxDIR_IGNORE;
		}

	private:
		wxArrayString& m_files;

	}; // DirTraverser

	DirTraverser traverser(dirs);

	wxDir dir(dirpath);
	dir.Traverse(traverser);
}

std::string FileHelper::GetFilenameAddTag(const std::string& filename, const std::string& tag,
									   const std::string& extension)
{
	std::string fixed;
	int start = filename.find_last_of('_');
	if (start != -1)
	{
		std::string check = filename.substr(start + 1, filename.find_last_of('.') - start - 1);
		if (check == tag) {
			fixed = filename;
		} else if (filename[0] == '.') {
			fixed = filename + wxT("_" + tag + "." + extension);
		} else {
			fixed = filename.substr(0, filename.find_last_of('.')) + wxT("_" + tag + "." + extension);
		}
	}
	else
	{
		if (filename[0] == '.') {
			fixed = filename.substr(0, filename.find_last_of('.')) + wxT("_" + tag + "." + extension);
		} else {
			int dot_pos = filename.find_last_of('.');
			if (dot_pos == -1) {
				fixed = filename + wxT("_" + tag + "." + extension);
			} else {
				fixed = filename;
				fixed.insert(dot_pos, "_" + tag);
			}
		}
	}
	return fixed;
}

std::string FileHelper::GetFilenameTag(const std::string& filepath)
{
	const size_t start = filepath.find_last_of('_') + 1,
		end = filepath.find_last_of('.');
	return filepath.substr(start, end - start);
}

std::string FileHelper::GetFilename(const std::string& filepath)
{
	int pos_divide = std::max((int)filepath.find_last_of('/'), (int)filepath.find_last_of('\\'));
	const size_t start = pos_divide + 1,
		end = filepath.find_last_of('.');
	return filepath.substr(start, end - start);
}

std::string FileHelper::GetFilenameWithExtension(const std::string& filepath)
{
	int pos_divide = std::max((int)filepath.find_last_of('/'), (int)filepath.find_last_of('\\'));
	return filepath.substr(pos_divide + 1);
}

std::string FileHelper::GetDirName(const std::string& dir)
{
	return GetFilenameWithExtension(dir);
}

std::string FileHelper::GetRelativePath(const std::string& dir, const std::string& absolute)
{
	wxFileName filename(absolute);
	filename.MakeRelativeTo(dir);
	return filename.GetFullPath().Lower().ToStdString();
}

std::string FileHelper::GetAbsolutePath(const std::string& dir, const std::string& relative)
{
	wxFileName filename(relative);
	filename.MakeAbsolute(dir);
	filename.Normalize();
	return filename.GetFullPath().ToStdString();
}

std::string FileHelper::GetAbsolutePath(const std::string& filepath)
{
	wxFileName filename(filepath);
#ifndef _DEBUG
	wxStandardPathsBase& stdp = wxStandardPaths::Get();
	std::string exe_path = stdp.GetExecutablePath();
	filename.MakeAbsolute(GetFileDir(exe_path));
#endif
	filename.Normalize();
	return filename.GetFullPath().ToStdString();
}

std::string FileHelper::GetAbsolutePathFromFile(const std::string& base, const std::string& relative)
{
	std::string dir = FileHelper::GetFileDir(base);
	return FileHelper::GetAbsolutePath(dir, relative);
}

std::string FileHelper::GetFilePathExceptExtension(const std::string& filepath)
{
	return filepath.substr(0, filepath.find_last_of('.'));
}

std::string FileHelper::GetExtension(const std::string& filepath)
{
	return filepath.substr(filepath.find_last_of('.') + 1);
}

std::string FileHelper::GetFileDir(const std::string& filepath)
{
	int pos_divide = std::max((int)filepath.find_last_of('/'), (int)filepath.find_last_of('\\'));
	if (pos_divide == -1) {
		return ".";
	} else {
		return filepath.substr(0, pos_divide);
	}
}

std::string FileHelper::GetExistFilepath(const std::string& filepath, const std::string& dir /*= wxEmptyString*/)
{
	std::string fixed = filepath;
	if (!IsFileExist(fixed))
	{
		std::string filename = fixed = GetFilenameWithExtension(fixed);
		if (!IsFileExist(fixed))
		{
			std::string cwd = wxFileName::GetCwd();

			Config* cfg = Config::Instance();
			std::set<std::string>::const_iterator
				itr = cfg->GetResPathes().begin();
			for ( ; itr != cfg->GetResPathes().end(); ++itr)
			{
				fixed = *itr + filename;
				if (IsFileExist(fixed))
					return fixed;

				fixed = cwd + *itr + filename;
				if (IsFileExist(fixed))
					return fixed;
			}
			if (dir != wxEmptyString)
			{
				fixed = dir + filename;
				if (IsFileExist(fixed))
					return fixed;
			}
// 			throw Exception("File: %s don't exist!", filepath.ToStdString().c_str());
			return "";
		}
		else
		{
			return fixed;
		}
	}
	else
	{
		return fixed;
	}
}

void FileHelper::FormatSeparators(std::string& filepath)
{
	const std::string oldVal = "/", newVal = "\\";
	for(std::string::size_type pos(0); pos != std::string::npos; pos += oldVal.length())
	{
		if((pos = filepath.find(oldVal, pos)) != std::string::npos)
			filepath.replace(pos, oldVal.length(), newVal);
		else
			break;
	}
}

std::string FileHelper::FormatFilepath(const std::string& filepath)
{
	std::string ret = filepath;
	StringHelper::ToLower(ret);
	FormatSeparators(ret);
	return ret;
}

std::string FileHelper::FormatFilepathAbsolute(const std::string& filepath)
{
	wxFileName filename(FormatFilepath(filepath));
	filename.Normalize();
	return filename.GetFullPath().Lower().ToStdString();
}

}<commit_msg>[FIXED] filepath in release<commit_after>#include "FileHelper.h"
#include "StringHelper.h"
#include "Config.h"

#include <wx/dir.h>
#include <wx/filename.h>
#ifndef _DEBUG
#include <wx/stdpaths.h>
#endif // _DEBUG

#include <set>

namespace ee
{

bool FileHelper::MkDir(const std::string& dir, bool rm)
{
	bool ret = true;
	if (wxDir::Exists(dir)) {
		if (rm) {
			wxFileName::Rmdir(dir, wxPATH_RMDIR_RECURSIVE);
			ret = wxFileName::Mkdir(dir, wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL);
		}
	} else {
		ret = wxFileName::Mkdir(dir, wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL);
	}
	return ret;
}

bool FileHelper::RmFile(const std::string& filepath)
{
	return wxRemoveFile(filepath);
}

bool FileHelper::IsFileExist(const std::string& filepath)
{
	return wxFileName::FileExists(filepath);
}

bool FileHelper::IsDirExist(const std::string& filepath)
{
	return wxFileName::DirExists(filepath);
}

void FileHelper::FetchAllFiles(const std::string& dirpath, wxArrayString& files)
{
	class DirTraverser : public wxDirTraverser
	{
	public:
		DirTraverser(wxArrayString& files)
			: m_files(files) {}

		virtual wxDirTraverseResult OnFile(const wxString& filename)
		{
			m_files.Add(filename);
			return wxDIR_CONTINUE;
		}

		virtual wxDirTraverseResult OnDir(const wxString& dirname)
		{
			return wxDIR_CONTINUE;
		}

	private:
		wxArrayString& m_files;

	}; // DirTraverser

	DirTraverser traverser(files);

	wxDir dir(dirpath);
	dir.Traverse(traverser);
}

void FileHelper::FetchAllFiles(const std::string& dirpath, const std::string& ignore_dir, wxArrayString& files)
{
	class DirTraverser : public wxDirTraverser
	{
	public:
		DirTraverser(wxArrayString& files, const wxString& ignore_dir)
			: m_files(files)
			, m_ignore_dir(ignore_dir)
		{}

		virtual wxDirTraverseResult OnFile(const wxString& filename)
		{
			m_files.Add(filename);
			return wxDIR_CONTINUE;
		}

		virtual wxDirTraverseResult OnDir(const wxString& dirname)
		{
			if (dirname == m_ignore_dir) {
				return wxDIR_IGNORE;
			} else {
				return wxDIR_CONTINUE;
			}
		}

	private:
		wxArrayString& m_files;
		std::string m_ignore_dir;

	}; // DirTraverser

	DirTraverser traverser(files, ignore_dir);

	wxDir dir(dirpath);
	dir.Traverse(traverser);
}

void FileHelper::FetchAllFiles(const std::string& dirpath, wxArrayString& files, FileType::Type type)
{
	class DirTraverser : public wxDirTraverser
	{
	public:
		DirTraverser(wxArrayString& files, FileType::Type type)
			: files(files), type(type) {}

		virtual wxDirTraverseResult OnFile(const wxString& filename)
		{
			if (FileType::IsType(filename.ToStdString(), type)) {
				files.Add(filename);
			}
			return wxDIR_CONTINUE;
		}

		virtual wxDirTraverseResult OnDir(const wxString& dirname)
		{
			return wxDIR_CONTINUE;
		}

	private:
		wxArrayString& files;
		FileType::Type type;

	}; // DirTraverser

	DirTraverser traverser(files, type);

	wxDir dir(dirpath);
	dir.Traverse(traverser);
}

void FileHelper::FetchCurrDirs(const std::string& dirpath, wxArrayString& dirs)
{
	class DirTraverser : public wxDirTraverser
	{
	public:
		DirTraverser(wxArrayString& files)
			: m_files(files) {}

		virtual wxDirTraverseResult OnFile(const wxString& filename)
		{
			return wxDIR_CONTINUE;
		}

		virtual wxDirTraverseResult OnDir(const wxString& dirname)
		{
			m_files.Add(dirname);
			return wxDIR_IGNORE;
		}

	private:
		wxArrayString& m_files;

	}; // DirTraverser

	DirTraverser traverser(dirs);

	wxDir dir(dirpath);
	dir.Traverse(traverser);
}

std::string FileHelper::GetFilenameAddTag(const std::string& filename, const std::string& tag,
									   const std::string& extension)
{
	std::string fixed;
	int start = filename.find_last_of('_');
	if (start != -1)
	{
		std::string check = filename.substr(start + 1, filename.find_last_of('.') - start - 1);
		if (check == tag) {
			fixed = filename;
		} else if (filename[0] == '.') {
			fixed = filename + wxT("_" + tag + "." + extension);
		} else {
			fixed = filename.substr(0, filename.find_last_of('.')) + wxT("_" + tag + "." + extension);
		}
	}
	else
	{
		if (filename[0] == '.') {
			fixed = filename.substr(0, filename.find_last_of('.')) + wxT("_" + tag + "." + extension);
		} else {
			int dot_pos = filename.find_last_of('.');
			if (dot_pos == -1) {
				fixed = filename + wxT("_" + tag + "." + extension);
			} else {
				fixed = filename;
				fixed.insert(dot_pos, "_" + tag);
			}
		}
	}
	return fixed;
}

std::string FileHelper::GetFilenameTag(const std::string& filepath)
{
	const size_t start = filepath.find_last_of('_') + 1,
		end = filepath.find_last_of('.');
	return filepath.substr(start, end - start);
}

std::string FileHelper::GetFilename(const std::string& filepath)
{
	int pos_divide = std::max((int)filepath.find_last_of('/'), (int)filepath.find_last_of('\\'));
	const size_t start = pos_divide + 1,
		end = filepath.find_last_of('.');
	return filepath.substr(start, end - start);
}

std::string FileHelper::GetFilenameWithExtension(const std::string& filepath)
{
	int pos_divide = std::max((int)filepath.find_last_of('/'), (int)filepath.find_last_of('\\'));
	return filepath.substr(pos_divide + 1);
}

std::string FileHelper::GetDirName(const std::string& dir)
{
	return GetFilenameWithExtension(dir);
}

std::string FileHelper::GetRelativePath(const std::string& dir, const std::string& absolute)
{
	wxFileName filename(absolute);
	filename.MakeRelativeTo(dir);
	return filename.GetFullPath().Lower().ToStdString();
}

std::string FileHelper::GetAbsolutePath(const std::string& dir, const std::string& relative)
{
	wxFileName filename(relative);
	filename.MakeAbsolute(dir);
	filename.Normalize();
	return filename.GetFullPath().ToStdString();
}

std::string FileHelper::GetAbsolutePath(const std::string& filepath)
{
	wxFileName filename(filepath);
	filename.Normalize();
	return filename.GetFullPath().ToStdString();
}

std::string FileHelper::GetAbsolutePathFromFile(const std::string& base, const std::string& relative)
{
	std::string dir = FileHelper::GetFileDir(base);
	return FileHelper::GetAbsolutePath(dir, relative);
}

std::string FileHelper::GetFilePathExceptExtension(const std::string& filepath)
{
	return filepath.substr(0, filepath.find_last_of('.'));
}

std::string FileHelper::GetExtension(const std::string& filepath)
{
	return filepath.substr(filepath.find_last_of('.') + 1);
}

std::string FileHelper::GetFileDir(const std::string& filepath)
{
	int pos_divide = std::max((int)filepath.find_last_of('/'), (int)filepath.find_last_of('\\'));
	if (pos_divide == -1) {
		return ".";
	} else {
		return filepath.substr(0, pos_divide);
	}
}

std::string FileHelper::GetExistFilepath(const std::string& filepath, const std::string& dir /*= wxEmptyString*/)
{
	std::string fixed = filepath;
	if (!IsFileExist(fixed))
	{
		std::string filename = fixed = GetFilenameWithExtension(fixed);
		if (!IsFileExist(fixed))
		{
			std::string cwd = wxFileName::GetCwd();

			Config* cfg = Config::Instance();
			std::set<std::string>::const_iterator
				itr = cfg->GetResPathes().begin();
			for ( ; itr != cfg->GetResPathes().end(); ++itr)
			{
				fixed = *itr + filename;
				if (IsFileExist(fixed))
					return fixed;

				fixed = cwd + *itr + filename;
				if (IsFileExist(fixed))
					return fixed;
			}
			if (dir != wxEmptyString)
			{
				fixed = dir + filename;
				if (IsFileExist(fixed))
					return fixed;
			}
// 			throw Exception("File: %s don't exist!", filepath.ToStdString().c_str());
			return "";
		}
		else
		{
			return fixed;
		}
	}
	else
	{
		return fixed;
	}
}

void FileHelper::FormatSeparators(std::string& filepath)
{
	const std::string oldVal = "/", newVal = "\\";
	for(std::string::size_type pos(0); pos != std::string::npos; pos += oldVal.length())
	{
		if((pos = filepath.find(oldVal, pos)) != std::string::npos)
			filepath.replace(pos, oldVal.length(), newVal);
		else
			break;
	}
}

std::string FileHelper::FormatFilepath(const std::string& filepath)
{
	std::string ret = filepath;
	StringHelper::ToLower(ret);
	FormatSeparators(ret);
	return ret;
}

std::string FileHelper::FormatFilepathAbsolute(const std::string& filepath)
{
	wxFileName filename(FormatFilepath(filepath));
	filename.Normalize();
	return filename.GetFullPath().Lower().ToStdString();
}

}<|endoftext|>


<commit_before>#include "json.h"

#include "../lib/rapidjson/prettywriter.h"
#include "../lib/rapidjson/stringbuffer.h"

using namespace Batyr::Json;

std::string
Batyr::Json::stringify(rapidjson::Document & doc)
{
    rapidjson::StringBuffer buffer;
    rapidjson::PrettyWriter< rapidjson::StringBuffer > writer(buffer);
    doc.Accept(writer);

    return std::string(buffer.GetString());
}

std::string
Batyr::Json::stringify(std::chrono::system_clock::time_point tp)
{
    time_t tp_t = std::chrono::system_clock::to_time_t(tp);
    tm utc_tm = *std::gmtime(&tp_t);

    char buffer[100];
    std::strftime(buffer, sizeof(buffer), "%FT%TZ", &utc_tm);
    return std::string(buffer);
}

<commit_msg>only return pretty printed json in debug builds<commit_after>#include "json.h"

#include "../lib/rapidjson/prettywriter.h"
#include "../lib/rapidjson/writer.h"
#include "../lib/rapidjson/stringbuffer.h"

using namespace Batyr::Json;

std::string
Batyr::Json::stringify(rapidjson::Document & doc)
{
    rapidjson::StringBuffer buffer;

#ifdef _DEBUG
    // use pretty printed json when creating a debug build
    rapidjson::PrettyWriter< rapidjson::StringBuffer > writer(buffer);
#else
    rapidjson::Writer< rapidjson::StringBuffer > writer(buffer);
#endif

    doc.Accept(writer);

    return std::string(buffer.GetString());
}

std::string
Batyr::Json::stringify(std::chrono::system_clock::time_point tp)
{
    time_t tp_t = std::chrono::system_clock::to_time_t(tp);
    tm utc_tm = *std::gmtime(&tp_t);

    char buffer[100];
    std::strftime(buffer, sizeof(buffer), "%FT%TZ", &utc_tm);
    return std::string(buffer);
}

<|endoftext|>