code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
package myservlet; public class Credential { private String username; private String password; public Credential(String username, String password){ this.username = username; this.password = password; } public boolean IsCorrect() { if (username.equals("dummy") && password.equals("foobar")) return true; else return false; } public String GetUserName() { return this.username; } }
zyws-cloudcomputing
trunk/Auth/ServletHost/src/myservlet/Credential.java
Java
gpl2
412
package myservlet; import javax.servlet.http.HttpServlet; public class RegisterServlet extends HttpServlet{ }
zyws-cloudcomputing
trunk/Auth/ServletHost/src/myservlet/RegisterServlet.java
Java
gpl2
113
package myservlet; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; /* this is the Login Servlet */ public class LoginServlet extends HttpServlet{ /** * */ private static final long serialVersionUID = 1L; private String s = "/home/ec2-user/AwsCredentials.properties"; public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException{ String username; String password; res.setContentType("text/html"); // PrintWriter out = res.getWriter(); FileInputStream fis = new FileInputStream("/home/ec2-user/AwsCredentials.properties"); OutputStream os = res.getOutputStream(); int r = -1; username = req.getParameter("username"); password = req.getParameter("password"); Credential c = new Credential(username, password); if (c.IsCorrect() == true) { // out.println("1Dude, you are right!1"); while((r=fis.read())!=-1){ os.write(r); } os.flush(); } else { // out.println("0Dude, you are wrong!1"); // os.write(-1); os.flush(); } os.close(); } }
zyws-cloudcomputing
trunk/Auth/ServletHost/src/myservlet/LoginServlet.java
Java
gpl2
1,070
package testclient; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.net.MalformedURLException; import java.net.URL; import java.net.URLConnection; import java.net.URLEncoder; /* OK, let's try pass string A and print string B */ public class TClient { public static void main(String args[]) { // Construct data String Login_Credential; try { Login_Credential = "username=dummy&password=foobar"; // Send data URL url = new URL("http://107.22.164.227:8080/ServletHost/login"); // URL url = new URL("http://localhost:8080/ServletHost/servlet"); URLConnection conn = url.openConnection(); conn.setDoOutput(true); OutputStreamWriter wr = new OutputStreamWriter( conn.getOutputStream()); wr.write(Login_Credential); wr.flush(); // Get the response BufferedReader rd = new BufferedReader(new InputStreamReader( conn.getInputStream())); String line; while ((line = rd.readLine()) != null) { // Process line... System.out.println(line); } rd.close(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (MalformedURLException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
zyws-cloudcomputing
trunk/Auth/ServletClient/src/testclient/TClient.java
Java
gpl2
1,469
package testclient; public class CLogin { String CredentialPath = "/home/AwsCredential.properties"; public CLogin(String username, String password) { } }
zyws-cloudcomputing
trunk/Auth/ServletClient/src/testclient/CLogin.java
Java
gpl2
162
# makefile pro preklad LaTeX verze Bc. prace # (c) 2008 Michal Bidlo # E-mail: bidlom AT fit vutbr cz #=========================================== # asi budete chtit prejmenovat: CO=projekt all: $(CO).pdf pdf: $(CO).pdf $(CO).ps: $(CO).dvi dvips $(CO) $(CO).pdf: clean pdflatex -quiet $(CO) bibtex $(CO) pdflatex -quiet $(CO) pdflatex -quiet $(CO) $(CO).dvi: $(CO).tex $(CO).bib latex -quiet $(CO) bibtex -quiet $(CO) latex -quiet $(CO) latex -quiet $(CO) desky: # latex desky # dvips desky # dvipdf desky pdflatex desky clean: rm -f *.dvi *.log $(CO).blg $(CO).bbl $(CO).toc *.aux $(CO).out $(CO).lof rm -f $(CO).pdf rm -f *~ pack: tar czvf bp-xjmeno.tar.gz *.tex *.bib *.bst ./fig/* ./cls/* Makefile Changelog
zx-simi
trunk/DP/Makefile
Makefile
oos
734
library IEEE; use ieee.std_logic_1164.ALL; use ieee.std_logic_ARITH.ALL; use ieee.std_logic_UNSIGNED.ALL; entity KEYBOARD is port ( CLK : in std_logic; RESET : in std_logic; -- rozhrani pro komunikaci s procesorem ADDR : in std_logic_vector(15 downto 0); DATA_OUT : out std_logic_vector(7 downto 0); -- rozhrani pro komunikaci s PS2 klavesnici pripojenou k FPGA K_CLK : inout std_logic; K_DATA : inout std_logic ); end entity; architecture behav of KEYBOARD is -- PS/2 controller component PS2_controller is port ( -- Reset a synchronizace RST : in std_logic; CLK : in std_logic; -- Rozhrani PS/2 PS2_CLK : inout std_logic; PS2_DATA : inout std_logic; -- Vstup (zapis do zarizeni) DATA_IN : in std_logic_vector(7 downto 0); WRITE_EN : in std_logic; -- Vystup (cteni ze zarizeni) DATA_OUT : out std_logic_vector(7 downto 0); DATA_VLD : out std_logic; DATA_ERR : out std_logic ); end component; for ps2kb: PS2_controller use entity work.PS2_controller(half); signal PS2_DATA_OUT : std_logic_vector(7 downto 0); signal PS2_DATA_OUT_VLD : std_logic; type reg5x8 is array (0 to 7) of std_logic_vector(4 downto 0); signal keys : reg5x8; signal mask0,mask3,mask4,mask6,mask7 : std_logic_vector(4 downto 0); signal data_mx : std_logic_vector(4 downto 0); signal key_release : std_logic; signal key_E0 : std_logic; -- priznak, ktery maji nektere klavesy signal key_backspace : std_logic; signal key_capslock : std_logic; signal key_tecka : std_logic; signal key_carka : std_logic; signal key_plus : std_logic; signal key_minus : std_logic; signal key_krat : std_logic; signal key_deleno : std_logic; signal key_up : std_logic; signal key_down : std_logic; signal key_left : std_logic; signal key_right : std_logic; begin ps2kb: PS2_controller port map ( RST => RESET, CLK => CLK, PS2_CLK => K_CLK, PS2_DATA => K_DATA, DATA_IN => (others=>'0'), WRITE_EN => '0', DATA_OUT => PS2_DATA_OUT, DATA_VLD => PS2_DATA_OUT_VLD, DATA_ERR => open ); -- vystup pro procesor DATA_OUT <= "111" & data_mx; -- maska s ostatnimi klavesami mask0 <= key_deleno & "111" & (key_backspace and key_capslock and key_up and key_down and key_left and key_right); mask3 <= key_left & "11" & key_capslock & '1'; mask4 <= key_down & key_up & key_right & '1' & key_backspace; mask6 <= '1' & key_minus & key_plus & "11"; mask7 <= key_krat & key_carka & key_tecka & (key_tecka and key_carka and key_plus and key_minus and key_krat and key_deleno) & '1'; -- podle horni casti adresy na vystup pripojim patricny datovy radek with ADDR(15 downto 8) select data_mx <= (keys(0) and mask0) when "11111110", keys(1) when "11111101", keys(2) when "11111011", (keys(3) and mask3) when "11110111", (keys(4) and mask4) when "11101111", keys(5) when "11011111", (keys(6) and mask6) when "10111111", (keys(7) and mask7) when others; -- stisknuta klavesa se signalizuje logickou 0, uvolnena klavesa logickou 1 process(RESET,CLK) begin if RESET='1' then keys <= (others=>"11111"); key_backspace <= '1'; key_capslock <= '1'; key_tecka <= '1'; key_carka <= '1'; key_plus <= '1'; key_minus <= '1'; key_krat <= '1'; key_deleno <= '1'; key_up <='1'; key_down <='1'; key_left <='1'; key_right <='1'; key_release <= '0'; elsif CLK'event and CLK='1' then if PS2_DATA_OUT_VLD='1' then key_release <= '0'; -- priznak uvolneni je platny vzdy pro nasledujici znak. Nyni ho smazu, ale smazani se provede az po skonceni tohoto procesu key_E0 <= '0'; case key_E0 & PS2_DATA_OUT is when X"012" => -- Caps Shift (levy shift) keys(0)(0) <= key_release; when X"01A" => -- Z keys(0)(1) <= key_release; when X"022" => -- X keys(0)(2) <= key_release; when X"021" => -- C keys(0)(3) <= key_release; when X"02A" => -- V keys(0)(4) <= key_release; when X"01C" => -- A keys(1)(0) <= key_release; when X"01B" => -- S keys(1)(1) <= key_release; when X"023" => -- D keys(1)(2) <= key_release; when X"02B" => -- F keys(1)(3) <= key_release; when X"034" => -- G keys(1)(4) <= key_release; when X"015" => -- Q keys(2)(0) <= key_release; when X"01D" => -- W keys(2)(1) <= key_release; when X"024" => -- E keys(2)(2) <= key_release; when X"02D" => -- R keys(2)(3) <= key_release; when X"02C" => -- T keys(2)(4) <= key_release; when X"016" | X"069" => -- 1 keys(3)(0) <= key_release; when X"01E" | X"072" => -- 2 keys(3)(1) <= key_release; when X"026" | X"07A" => -- 3 keys(3)(2) <= key_release; when X"025" | X"06B" => -- 4 keys(3)(3) <= key_release; when X"02E" | X"073" => -- 5 keys(3)(4) <= key_release; when X"045" | X"070" => -- 0 keys(4)(0) <= key_release; when X"046" | X"007D" => -- 9 keys(4)(1) <= key_release; when X"03E" | X"075" => -- 8 keys(4)(2) <= key_release; when X"03D" | X"06C" => -- 7 keys(4)(3) <= key_release; when X"036" | X"074" => -- 6 keys(4)(4) <= key_release; when X"04D" => -- P keys(5)(0) <= key_release; when X"044" => -- O keys(5)(1) <= key_release; when X"043" => -- I keys(5)(2) <= key_release; when X"03C" => -- U keys(5)(3) <= key_release; when X"035" => -- Y keys(5)(4) <= key_release; when X"05A" | X"15A" => -- Enter keys(6)(0) <= key_release; when X"04B" => -- L keys(6)(1) <= key_release; when X"042" => -- K keys(6)(2) <= key_release; when X"03B" => -- J keys(6)(3) <= key_release; when X"033" => -- H keys(6)(4) <= key_release; when X"029" => -- Space keys(7)(0) <= key_release; when X"059" => -- Symbol Shift (pravy shift) keys(7)(1) <= key_release; when X"03A" => -- M keys(7)(2) <= key_release; when X"031" => -- N keys(7)(3) <= key_release; when X"032" => -- B keys(7)(4) <= key_release; when X"079" => -- + key_plus <= key_release; when X"07B" => -- - key_minus <= key_release; when X"07C" => -- * key_krat <= key_release; when X"14A" => -- / key_deleno <= key_release; when X"041" => -- , key_carka <= key_release; when X"049" => -- . key_tecka <= key_release; when X"175" => -- Key up key_up <= key_release; when X"172" => -- Key down key_down <= key_release; when X"16B" => -- Key left key_left <= key_release; when X"174" => -- Key right key_right <= key_release; when X"066" => -- Backspace key_backspace <= key_release; when X"058" => -- Caps Lock key_capslock <= key_release; when X"0E0" => -- E0 key_E0 <= '1'; when X"0F0" | X"1F0" => -- uvolneni klavesy key_release <= '1'; key_E0 <= key_E0; -- priznak E0 zopakuji i pro priste when others => null; end case; end if; end if; end process; end architecture behav;
zx-simi
trunk/fpga/keyboard.vhd
VHDL
oos
7,843
-- fpga_config.vhd: user constants use work.clkgen_cfg.all; package fpga_cfg is constant DCM_FREQUENCY : dcm_freq := DCM_50MHz; end fpga_cfg; package body fpga_cfg is end fpga_cfg;
zx-simi
trunk/fpga/config.vhd
VHDL
oos
186
library IEEE; use ieee.std_logic_1164.ALL; use ieee.std_logic_ARITH.ALL; use ieee.std_logic_UNSIGNED.ALL; use work.vga_controller_cfg.all; entity GPU is port ( CLK : in std_logic; RESET : in std_logic; -- okraj (BORDER) BORDER_IN : in std_logic_vector(7 downto 0); BORDER_WR : in std_logic; -- signaly VGA radice VGA_VSYNC : out std_logic; VGA_HSYNC : out std_logic; VGA_RED : out std_logic_vector(2 downto 0); VGA_GREEN : out std_logic_vector(2 downto 0); VGA_BLUE : out std_logic_vector(2 downto 0); -- signaly pro komunikaci s pameti ADDR : out std_logic_vector(13 downto 0); READ_EN : out std_logic; DATA_IN : in std_logic_vector(7 downto 0); DATA_IN_VLD : in std_logic; REFRESH : out std_logic -- povoleni refresh pameti ); end entity; architecture behav of GPU is constant RESOLUTION_WIDTH : integer := 640; constant RESOLUTION_HEIGHT : integer := 480; constant PIXEL_WIDTH : integer := 2; constant PIXEL_HEIGHT : integer := 2; -- rozmer kreslici plochy constant SCREEN_WIDTH : integer := 256*PIXEL_WIDTH; constant SCREEN_HEIGHT : integer := 192*PIXEL_HEIGHT; -- sirka okraju constant BORDER_WIDTH : integer := (RESOLUTION_WIDTH-SCREEN_WIDTH)/2; constant BORDER_HEIGHT : integer := (RESOLUTION_HEIGHT-SCREEN_HEIGHT)/2; component BUFG port ( I: in std_logic; O: out std_logic ); end component; -- adresove vodice signal addr_data : std_logic_vector(13 downto 0); signal addr_atrib : std_logic_vector(13 downto 0); signal data : std_logic_vector(7 downto 0); -- aktualni zobrazovana data signal data1 : std_logic_vector(7 downto 0); -- data registr1 signal data2 : std_logic_vector(7 downto 0); -- data registr2 signal data_fetch_vld : std_logic; -- signal zapis do registru signal data_bit : std_logic; -- aktualni datovy bit, ktery se vykresluje signal read_en_vld : std_logic; -- povoleni vystupu READ_EN signal atrib : std_logic_vector(7 downto 0); -- atributy aktualne zobrazovanych dat signal atrib1 : std_logic_vector(7 downto 0); -- atributy registr1 signal atrib2 : std_logic_vector(7 downto 0); -- atributy registr2 signal atrib_fetch_vld : std_logic; -- signál zápis do registru signal clk_reg : std_logic; signal clk_d2 : std_logic; signal color : std_logic_vector(3 downto 0); -- atribut s barvou, ktera se bude kreslit (signal) signal border : std_logic_vector(2 downto 0); -- okraj signal flash : std_logic_vector(4 downto 0); -- inkrementovany registr pro blikani obrazu (flash) signal col_reg : std_logic_vector(8 downto 0); signal col_rst : std_logic; signal row_reg : std_logic_vector(8 downto 0); signal row_rst : std_logic; signal vsync : std_logic; signal hsync : std_logic; signal vsync_old : std_logic; signal hsync_old : std_logic; type t_state_sdram is (S_WAIT, S_DATA_REQ, S_DATA_WAIT, S_ATRIB_REQ); signal sdram_present, sdram_next : t_state_sdram; type t_state_draw is (D_HBORDER, D_VBORDER, D_MIDDLE, D_MIDDLE_PREFETCH); signal draw_present, draw_next : t_state_draw; signal isettings : std_logic_vector(60 downto 0); --nastaveni rezimu VGA signal ROW : std_logic_vector(11 downto 0); signal COL : std_logic_vector(11 downto 0); signal RED : std_logic_vector(2 downto 0); signal GREEN : std_logic_vector(2 downto 0); signal BLUE : std_logic_vector(2 downto 0); begin -- nastaveni grafickeho rezimu SetMode(r640x480x60, isettings); -- napojeni signalu na VGA rozhrani vga: entity work.vga_controller(arch_vga_controller) generic map (REQ_DELAY => 0) -- data jsou k dispozici ihned pomoci kombinacni logiky port map ( CLK => clk_reg, RST => RESET, ENABLE => '1', MODE => isettings, DATA_RED => RED, DATA_GREEN => GREEN, DATA_BLUE => BLUE, ADDR_COLUMN => COL, ADDR_ROW => ROW, VGA_RED => VGA_RED, VGA_BLUE => VGA_BLUE, VGA_GREEN => VGA_GREEN, VGA_HSYNC => hsync, VGA_VSYNC => vsync, -- H/V Status STATUS_H => open, STATUS_V => open ); VGA_HSYNC <= hsync; VGA_VSYNC <= vsync; -- aktualni adresa dat addr_data <= '0' & row_reg(7+PIXEL_HEIGHT-1 downto 6+PIXEL_HEIGHT-1) & row_reg(2+PIXEL_HEIGHT-1 downto 0+PIXEL_HEIGHT-1) & row_reg(5+PIXEL_HEIGHT-1 downto 3+PIXEL_HEIGHT-1) & col_reg(7+PIXEL_WIDTH-1 downto 3+PIXEL_WIDTH-1); addr_atrib <= "0110" & row_reg(7+PIXEL_HEIGHT-1 downto 6+PIXEL_HEIGHT-1) & row_reg(5+PIXEL_HEIGHT-1 downto 3+PIXEL_HEIGHT-1) & col_reg(7+PIXEL_WIDTH-1 downto 3+PIXEL_WIDTH-1); process(RESET,CLK) begin if RESET = '1' then border <= "000"; -- cerny okraj elsif CLK'event and CLK='1' then if BORDER_WR='1' then border <= BORDER_IN(2 downto 0); end if; end if; end process; -- podle sudeho/licheho znaku zobrazuju data bud z registru data1 nebo data2 data <= data1 when COL(4)='1' else data2; -- obsluha datoveho registru 1 process(CLK) begin if CLK'event and CLK='1' then if data_fetch_vld='1' and COL(4)='0' then data1 <= DATA_IN; end if; end if; end process; -- obsluha datoveho registru 2 process(CLK) begin if CLK'event and CLK='1' then if data_fetch_vld='1' and COL(4)='1' then data2 <= DATA_IN; end if; end if; end process; -- podle sudeho/licheho znaku pouzivam atribut bud z registru atrib1 nebo atrib2 atrib <= atrib1 when COL(4)='1' else atrib2; -- obsluha atributoveho registru 1 process(CLK) begin if CLK'event and CLK='1' then if atrib_fetch_vld='1' and COL(4)='0' then atrib1 <= DATA_IN; end if; end if; end process; -- obsluha atributoveho registru 2 process(CLK) begin if CLK'event and CLK='1' then if atrib_fetch_vld='1' and COL(4)='1' then atrib2 <= DATA_IN; end if; end if; end process; -- vyberu aktualni bit podle adresy sloupce process(COL,data) begin case COL(3 downto 1) is when "000" => data_bit <= data(7); when "001" => data_bit <= data(6); when "010" => data_bit <= data(5); when "011" => data_bit <= data(4); when "100" => data_bit <= data(3); when "101" => data_bit <= data(2); when "110" => data_bit <= data(1); when "111" => data_bit <= data(0); when others => null; end case; end process; -- pri kazde vertikalni synchronizaci inkrementuji registr zajistujici blikani flash_counter : process(CLK) begin if (CLK'event and CLK = '1') then vsync_old <= vsync; if (vsync_old='0' and VSYNC='1') then flash <= flash + 1; end if; end if; end process; -- multiplexor, ktery na vystup vybira aktualni barvu mx_color_output : process (color) begin RED <= "000"; GREEN <= "000"; BLUE <= "000"; case color is when "0001" => -- modra BLUE <= "111"; when "0010" => -- tmave cervena RED <= "110"; when "0011" => -- tmave fialova RED <= "110"; BLUE <= "110"; when "0100" => -- tmave zelena GREEN <= "110"; when "0101" => -- tmave cyan GREEN <= "110"; BLUE <= "110"; when "0110" => -- tmave zluta RED <= "110"; GREEN <= "110"; when "0111" => -- seda RED <= "110"; GREEN <= "110"; BLUE <= "110"; when "1001" => -- modra BLUE <= "111"; when "1010" => -- svetle cervena RED <= "111"; when "1011" => -- svetle fialova RED <= "111"; BLUE <= "111"; when "1100" => -- svetle zelena GREEN <= "111"; when "1101" => -- svetle cyan GREEN <= "111"; BLUE <= "111"; when "1110" => -- svetle zluta RED <= "111"; GREEN <= "111"; when "1111" => -- bila RED <= "111"; GREEN <= "111"; BLUE <= "111"; when others => null; end case; end process; -- prepnuti next state do sdram_present sync_logic : process(RESET, CLK) begin if (RESET = '1') then sdram_present <= S_WAIT; draw_present <= D_HBORDER; elsif (CLK'event AND CLK = '1') then sdram_present <= sdram_next; draw_present <= draw_next; end if; end process sync_logic; -- registr radku process (CLK,row_rst,HSYNC) begin if (row_rst = '1') then row_reg <= (others => '0'); elsif (CLK'event and CLK = '1') then hsync_old <= HSYNC; if (hsync_old='0' and HSYNC='1') then row_reg <= row_reg + 1; end if; end if; end process; process(RESET,CLK) begin if RESET='1' then clk_reg <= '0'; elsif CLK'event and CLK='1' then clk_reg <= not clk_reg; end if; end process; clk_d2_bufg : BUFG port map ( I => clk_reg, O => clk_d2 ); -- registr sloupce process(col_rst,clk_d2) begin if (col_rst = '1') then col_reg <= (others => '0'); elsif (clk_d2'event and clk_d2 = '1') then col_reg <= col_reg + 1; end if; end process; -- automat zajistujici vykreslovani FSM_DRAW : process (draw_present, border, ROW, COL, VSYNC, data_bit, flash, atrib) begin row_rst <= '0'; col_rst <= '0'; read_en_vld <= '0'; color <= '0' & border; -- vychozi rezim kresleni je okraj REFRESH <= '0'; case (draw_present) is when D_HBORDER => -- horizontalni okraj draw_next <= D_HBORDER; row_rst <= '1'; -- drzim pocitadlo radku v resetu if ROW = BORDER_HEIGHT then draw_next <= D_VBORDER; end if; when D_VBORDER => -- vertikalni okraj draw_next <= D_VBORDER; col_rst <= '1'; if ROW(1 downto 0)="00" then REFRESH <= '1'; end if; if VSYNC = '0' then -- pri vertikalni synchronizaci zacnu kreslit horni okraj draw_next <= D_HBORDER; elsif (ROW = SCREEN_HEIGHT+BORDER_HEIGHT) then -- radek je mimo oblast, zacnu kreslit horizontalni kraj draw_next <= D_HBORDER; elsif (COL = BORDER_WIDTH-8*PIXEL_WIDTH) then -- sloupec uz je v kreslitelne oblasti, zacnu ho kreslit draw_next <= D_MIDDLE_PREFETCH; end if; when D_MIDDLE_PREFETCH => -- jeste se kresli levy okraj, ale nacitaji se uz data draw_next <= D_MIDDLE_PREFETCH; read_en_vld <= '1'; -- povolim vystupni signal READ_EN if COL = BORDER_WIDTH then draw_next <= D_MIDDLE; end if; when D_MIDDLE => -- kreslim i nacitam data draw_next <= D_MIDDLE; read_en_vld <= '1'; -- povolim vystupni signal READ_EN if (data_bit xor (flash(4) and atrib(7))) = '0' then -- pozadi color <= atrib(6 downto 3); else -- popredi color <= atrib(6) & atrib(2 downto 0); end if; if (COL = SCREEN_WIDTH+BORDER_WIDTH) then draw_next <= D_VBORDER; end if; when others => draw_next <= D_HBORDER; end case; end process; -- FSM zajistujici komunikaci s SDRAM fsm_sdram : process(sdram_present, COL, read_en_vld, DATA_IN_VLD, addr_data, addr_atrib) begin READ_EN <= '0'; ADDR <= addr_data; data_fetch_vld <= '0'; atrib_fetch_vld <= '0'; case (sdram_present) is when S_WAIT => sdram_next <= S_WAIT; if (COL(3 downto 0) = "0001" and read_en_vld='1') then sdram_next <= S_DATA_REQ; end if; when S_DATA_REQ => ADDR <= addr_data; data_fetch_vld <= '1'; -- zapis nactenych dat do pomocneho registru sdram_next <= S_DATA_REQ; if (DATA_IN_VLD = '0') then READ_EN <= '1'; end if; if (DATA_IN_VLD = '1') then sdram_next <= S_ATRIB_REQ; end if; when S_ATRIB_REQ => ADDR <= addr_atrib; atrib_fetch_vld <= '1'; -- zapis nactenych atributu do pomocneho registru sdram_next <= S_ATRIB_REQ; if (DATA_IN_VLD = '0') then READ_EN <= '1'; end if; if (DATA_IN_VLD = '1') then sdram_next <= S_WAIT; end if; when others => sdram_next <= S_WAIT; end case; end process; end architecture behav;
zx-simi
trunk/fpga/gpu.vhd
VHDL
oos
14,882
library IEEE; Library UNISIM; use UNISIM.vcomponents.all; use ieee.std_logic_1164.ALL; use ieee.std_logic_ARITH.ALL; use ieee.std_logic_UNSIGNED.ALL; entity cpu_wrapper is port ( RESET : in std_logic; CLK : in std_logic; ADDR : out std_logic_vector(15 downto 0); DIN : in std_logic_vector(7 downto 0); DOUT : out std_logic_vector(7 downto 0); MEM_DIN_RD : out std_logic; MEM_DIN_VLD : in std_logic; MEM_DOUT_WR : out std_logic; MEM_DOUT_VLD : in std_logic; IO_DIN_RD : out std_logic; IO_DIN_VLD : in std_logic; IO_DOUT_WR : out std_logic; IO_DOUT_VLD : in std_logic; INT : in std_logic ); end entity; architecture cpu_wrapper_inst of cpu_wrapper is signal reset_n : std_logic; signal clk_n : std_logic; signal wait_n : std_logic; signal int_n : std_logic; signal mreq_n : std_logic; signal iorq_n : std_logic; signal rd_n : std_logic; signal wr_n : std_logic; signal mem_din_rd_sig : std_logic; signal mem_dout_wr_sig : std_logic; signal io_din_rd_sig : std_logic; signal io_dout_wr_sig : std_logic; begin reset_n <= not RESET; clk_n <= CLK; int_n <= not INT; wait_n <= '0' when (io_din_rd_sig='1' and IO_DIN_VLD='0') or (io_dout_wr_sig='1' and IO_DOUT_VLD='0') or (mem_din_rd_sig='1' and MEM_DIN_VLD='0') or (mem_dout_wr_sig='1' and MEM_DOUT_VLD='0') else '1'; MEM_DIN_RD <= mem_din_rd_sig; mem_din_rd_sig <= not (rd_n or mreq_n); MEM_DOUT_WR <= mem_dout_wr_sig; mem_dout_wr_sig <= not (wr_n or mreq_n); IO_DIN_RD <= io_din_rd_sig; io_din_rd_sig <= not (rd_n or iorq_n); IO_DOUT_WR <= io_dout_wr_sig; io_dout_wr_sig <= not (wr_n or iorq_n); T80a_inst : entity work.T80s generic map( Mode => 0, -- 0 => Z80, 1 => Fast Z80, 2 => 8080, 3 => GB T2Write => 1, -- 0 => WR_n active in T3, /=0 => WR_n active in T2 IOWait => 1 -- 0 => Single cycle I/O, 1 => Std I/O cycle ) port map ( RESET_n => reset_n, CLK_n => clk_n, WAIT_n => wait_n, INT_n => int_n, NMI_n => '1', BUSRQ_n => '1', M1_n => open, MREQ_n => mreq_n, IORQ_n => iorq_n, RD_n => rd_n, WR_n => wr_n, RFSH_n => open, HALT_n => open, BUSAK_n => open, A => ADDR, DI => DIN, DO => DOUT ); end architecture;
zx-simi
trunk/fpga/cpu_wrapper.vhd
VHDL
oos
2,822
library IEEE; use ieee.std_logic_1164.ALL; use ieee.std_logic_ARITH.ALL; use ieee.std_logic_UNSIGNED.ALL; entity SMDMA is port( RESET : in std_logic; CLK : in std_logic; --signaly pro komunikaci s procesorem CPU_RD : in std_logic; CPU_WR : in std_logic; CPU_WAIT_n : out std_logic; CPU_ADDR : in std_logic_vector(15 downto 0); CPU_DATA_IN : in std_logic_vector(7 downto 0); -- sdilene signaly ADDR : out std_logic_vector(22 downto 0); DIN : in std_logic_vector(7 downto 0); DOUT : out std_logic_vector(7 downto 0); --signaly pro komunikaci s pameti MEM_DIN_RD : out std_logic; MEM_DIN_VLD : in std_logic; MEM_DOUT_WR : out std_logic; MEM_DOUT_VLD : in std_logic; --signaly pro komunikaci s IO zarizenimi IORQ_DIN_RD : out std_logic; IORQ_DIN_VLD : in std_logic; IORQ_DOUT_WR : out std_logic; IORQ_DOUT_VLD : in std_logic ); end SMDMA; architecture behv of SMDMA is signal ADDRA : std_logic_vector(22 downto 0); signal ADDRA_INC : std_logic; signal ADDRA0_SET : std_logic; signal ADDRA1_SET : std_logic; signal ADDRA2_SET : std_logic; signal ADDRB : std_logic_vector(22 downto 0); signal ADDRB_INC : std_logic; signal ADDRB0_SET : std_logic; signal ADDRB1_SET : std_logic; signal ADDRB2_SET : std_logic; signal DATA : std_logic_vector(7 downto 0); signal DATA_SET : std_logic; signal DATA_MEM_SET : std_logic; signal CONFIG : std_logic_vector(7 downto 0); -- 0 - povolit inkrementaci A -- 1 - povolit inkrementaci B signal CONFIG_SET : std_logic; signal LENGTH : std_logic_vector(15 downto 0); signal LENGTH_DEC : std_logic; signal LENGTH_ZERO : std_logic; signal LENGTH0_SET : std_logic; signal LENGTH1_SET : std_logic; signal READ_REQ : std_logic; type t_state is (S_WAIT, S_WRITE1, S_WRITE2, S_WRITEN1, S_WRITEN2,S_WRITEN3,S_WRITEN4,S_READ1,S_READ2); signal present_state, next_state : t_state; begin -- registr adresa A process(RESET,CLK) begin if RESET='1' then ADDRA <= (others=>'0'); elsif CLK'event and CLK='1' then if ADDRA0_SET='1' then -- nejnizsi bajt ADDRA(7 downto 0) <= CPU_DATA_IN; elsif ADDRA1_SET='1' then -- prostredni bajt ADDRA(15 downto 8) <= CPU_DATA_IN; elsif ADDRA2_SET='1' then -- nejvyssi bajt ADDRA(22 downto 16) <= CPU_DATA_IN(6 downto 0); elsif ADDRA_INC='1' and CONFIG(0)='1' then ADDRA <= ADDRA + 1; end if; end if; end process; -- registr adresa B process(RESET,CLK) begin if RESET='1' then ADDRB <= (others=>'0'); ADDRB <= "00000101000000000000000"; --zacatek TAP oblasti elsif CLK'event and CLK='1' then if ADDRB0_SET='1' then -- nejnizsi bajt ADDRB(7 downto 0) <= CPU_DATA_IN; elsif ADDRB1_SET='1' then -- prostredni bajt ADDRB(15 downto 8) <= CPU_DATA_IN; elsif ADDRB2_SET='1' then -- nejvyssi bajt ADDRB(22 downto 16) <= CPU_DATA_IN(6 downto 0); elsif ADDRB_INC='1' and CONFIG(4)='1' then ADDRB <= ADDRB + 1; end if; end if; end process; DOUT <= DATA; -- datovy registr pro docasne ulozeni bajtu process(RESET,CLK) begin if RESET='1' then DATA <= (others=>'0'); elsif CLK'event and CLK='1' then if DATA_SET='1' then DATA <= CPU_DATA_IN; elsif DATA_MEM_SET='1' then DATA <= DIN; end if; end if; end process; -- konfiguracni registr process(RESET,CLK) begin if RESET='1' then CONFIG <= (others=>'0'); CONFIG <= X"10"; elsif CLK'event and CLK='1' then if CONFIG_SET='1' then CONFIG <= CPU_DATA_IN; end if; end if; end process; -- registr s delkou bloku, ktery se ma prenest process(RESET,CLK) begin if RESET='1' then LENGTH <= (others=>'0'); elsif CLK'event and CLK='1' then if LENGTH0_SET='1' then LENGTH(7 downto 0) <= CPU_DATA_IN; elsif LENGTH1_SET='1' then LENGTH(15 downto 8) <= CPU_DATA_IN; elsif LENGTH_DEC='1' then LENGTH <= LENGTH - 1; end if; end if; end process; -- dekodovani adresy od procesoru a zapis hodnoty do registru process(CPU_ADDR, CPU_WR) begin ADDRA0_SET <= '0'; ADDRA1_SET <= '0'; ADDRA2_SET <= '0'; ADDRB0_SET <= '0'; ADDRB1_SET <= '0'; ADDRB2_SET <= '0'; DATA_SET <= '0'; LENGTH0_SET <= '0'; LENGTH1_SET <= '0'; CONFIG_SET <= '0'; if CPU_ADDR(7 downto 0)=X"F3" and CPU_WR='1' then case CPU_ADDR(15 downto 8) is when X"00" => ADDRA0_SET <= '1'; when X"01" => ADDRA1_SET <= '1'; when X"02" => ADDRA2_SET <= '1'; when X"03" => DATA_SET <= '1'; when X"04" => ADDRB0_SET <= '1'; when X"05" => ADDRB1_SET <= '1'; when X"06" => ADDRB2_SET <= '1'; when X"07" => LENGTH0_SET <= '1'; when X"08" => LENGTH1_SET <= '1'; when X"09" => CONFIG_SET <= '1'; when others => null; end case; end if; end process; LENGTH_ZERO <= '1' when LENGTH=X"0000" else '0'; -- priznak, ze CPU chce cist data z pameti READ_REQ <= '1' when CPU_ADDR(7 downto 0)=X"F3" and CPU_RD='1' else '0'; process(present_state, DATA_SET, LENGTH1_SET, ADDRA, DATA, ADDRB, LENGTH_ZERO, READ_REQ, CONFIG, MEM_DIN_VLD, MEM_DOUT_VLD) begin ADDRA_INC <= '0'; ADDRB_INC <= '0'; LENGTH_DEC <= '0'; ADDR <= ADDRA; DATA_MEM_SET <= '0'; CPU_WAIT_n <= '0'; MEM_DIN_RD <= '0'; MEM_DOUT_WR <= '0'; IORQ_DIN_RD <= '0'; IORQ_DOUT_WR <= '0'; case (present_state) is when S_WAIT => CPU_WAIT_n <= '1'; next_state <= S_WAIT; if DATA_SET='1' then -- ulozim jeden bajt next_state <= S_WRITE1; elsif LENGTH1_SET='1' then -- ulozim cely blok pameti next_state <= S_WRITEN1; elsif READ_REQ='1' then next_state <= S_READ1; -- prectu jeden bajt z pameti a vystavim ho na vystup CPU_WAIT_n <= '0'; end if; when S_READ1 => ADDR <= ADDRB; -- zdrojova adresa DATA_MEM_SET <= '1'; -- zapisu si prijaty bajt z pameti do registru next_state <= S_READ1; MEM_DIN_RD <= '1'; if MEM_DIN_VLD='1' then next_state <= S_READ2; end if; when S_READ2 => ADDRB_INC <= '1'; next_state <= S_WAIT; when S_WRITE1 => ADDR <= ADDRA; next_state <= S_WRITE1; if CONFIG(1)='0' then MEM_DOUT_WR <= '1'; if MEM_DOUT_VLD='1' then next_state <= S_WRITE2; end if; end if; if CONFIG(1)='1' then IORQ_DOUT_WR <= '1'; if IORQ_DOUT_VLD='1' then next_state <= S_WRITE2; end if; end if; when S_WRITE2 => ADDRA_INC <= '1'; next_state <= S_WAIT; when S_WRITEN1 => -- nactu bajt z pameti ADDR <= ADDRB; DATA_MEM_SET <= '1'; next_state <= S_WRITEN1; if CONFIG(5)='0' then MEM_DIN_RD <= '1'; if MEM_DIN_VLD='1' then next_state <= S_WRITEN4; end if; end if; if CONFIG(5)='1' then IORQ_DIN_RD <= '1'; if IORQ_DIN_VLD='1' then next_state <= S_WRITEN4; end if; end if; when S_WRITEN4 => ADDRB_INC <= '1'; LENGTH_DEC <= '1'; next_state <= S_WRITEN2; when S_WRITEN2 => -- ulozim bajt z pameti ADDR <= ADDRA; next_state <= S_WRITEN2; if CONFIG(1)='0' then MEM_DOUT_WR <= '1'; if MEM_DOUT_VLD='1' then next_state <= S_WRITEN3; end if; end if; if CONFIG(1)='1' then IORQ_DOUT_WR <= '1'; if IORQ_DOUT_VLD='1' then next_state <= S_WRITEN3; end if; end if; when S_WRITEN3 => ADDRA_INC <= '1'; next_state <= S_WRITEN1; if LENGTH_ZERO='1' then next_state <= S_WAIT; end if; when others => next_state <= S_WAIT; end case; end process; process(RESET,CLK) begin if RESET='1' then present_state <= S_WAIT; elsif CLK'event and CLK='1' then present_state <= next_state; end if; end process; end architecture;
zx-simi
trunk/fpga/smdma.vhd
VHDL
oos
10,639
// // Xilinx VHDL ROM generator // // Version : 0244 // // Copyright (c) 2001-2002 Daniel Wallner (jesus@opencores.org) // // 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 author nor the names of other 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 AUTHOR 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. // // Please report bugs to the author, but before you do so, please // make sure that this is not a derivative work and that // you have the latest version of this file. // // The latest version of this file can be found at: // http://www.opencores.org/cvsweb.shtml/t51/ // // Limitations : // Not all address/data widths produce working code // Requires stl to compile // // File history : // // 0220 : Initial release // // 0221 : Fixed block ROMs with partial bytes // // 0241 : Updated for WebPack 5.1 // // 0244 : Added -n option and component declaration // #include <stdio.h> #include <string> #include <vector> #include <iostream> using namespace std; #if !(defined(max)) && _MSC_VER // VC fix #define max __max #endif int main (int argc, char *argv[]) { cerr << "Xilinx VHDL ROM generator by Daniel Wallner. Version 0244\n"; try { unsigned long aWidth; unsigned long dWidth; unsigned long select = 0; unsigned long length = 0; char z = 0; if (argc < 4) { cerr << "\nUsage: xrom <entity name> <address bits> <data bits> <options>\n"; cerr << "\nThe options can be:\n"; cerr << " -[decimal number] = SelectRAM usage in 1/16 parts\n"; cerr << " -z = use tri-state buses\n"; cerr << " -n [decimal size] = limit rom size\n"; cerr << "\nExample:\n"; cerr << " xrom Test_ROM 13 8 -6\n\n"; return -1; } int result; result = sscanf(argv[2], "%lu", &aWidth); if (result < 1) { throw "Error in address bits argument!\n"; } result = sscanf(argv[3], "%lu", &dWidth); if (result < 1) { throw "Error in data bits argument!\n"; } int argument = 4; while (argument < argc) { char tmpC = 0; unsigned long tmpL = 0; result = sscanf(argv[argument], "%c%lu", &tmpC, &tmpL); if (result < 1 || tmpC != '-' ) { throw "Error in options!\n"; } if (result < 2) { sscanf(argv[argument], "%c%c", &tmpC, &tmpC); if (tmpC != 'z' && tmpC != 'n') { throw "Unkown option!\n"; } if (tmpC == 'z') { z = tmpC; } else { argument++; if (argument == argc) { throw "No memory size argument!\n"; } result = sscanf(argv[argument], "%lu", &tmpL); if (!result) { throw "Memory size not a number!\n"; } length = tmpL; } } else { select = tmpL; } argument++; } unsigned long selectIter = 0; unsigned long blockIter = 0; unsigned long bytes = (dWidth + 7) / 8; if (!select) { blockIter = ((1UL << aWidth) + 511) / 512; if (length && length < blockIter * 512) { blockIter = (length + 511) / 512; } } else if (select == 16) { selectIter = ((1UL << aWidth) + 15) / 16; if (length && length < selectIter * 16) { selectIter = (length + 15) / 16; } } else { blockIter = ((1UL << aWidth) * (16 - select) / 16 + 511) / 512; selectIter = ((1UL << aWidth) - blockIter * 512 + 15) / 16; } unsigned long blockTotal = ((1UL << aWidth) + 511) / 512; if (length && length < blockTotal * 512) { blockTotal = (length + 511) / 512; } if (length) { if (length > selectIter * 16) { blockIter -= ((1UL << aWidth) + 511) / 512 - blockTotal; } else { blockIter = 0; } } if (length && !blockIter && length < selectIter * 16) { selectIter = (length + 15) / 16; } cerr << "Creating ROM with " << selectIter * bytes; cerr << " RAM16X1S and " << blockIter * bytes << " RAMB4_S8\n"; printf("-- This file was generated with xrom written by Daniel Wallner\n"); printf("\nlibrary IEEE;"); printf("\nuse IEEE.std_logic_1164.all;"); printf("\nuse IEEE.numeric_std.all;"); printf("\n\nentity %s is", argv[1]); printf("\n\tport("); printf("\n\t\tClk\t: in std_logic;"); printf("\n\t\tA\t: in std_logic_vector(%d downto 0);", aWidth - 1); printf("\n\t\tD\t: out std_logic_vector(%d downto 0)", dWidth - 1); printf("\n\t);"); printf("\nend %s;", argv[1]); printf("\n\narchitecture rtl of %s is", argv[1]); if (selectIter) { printf("\n\tcomponent RAM16X1S"); printf("\n\t\tport("); printf("\n\t\t\tO : out std_ulogic;"); printf("\n\t\t\tA0 : in std_ulogic;"); printf("\n\t\t\tA1 : in std_ulogic;"); printf("\n\t\t\tA2 : in std_ulogic;"); printf("\n\t\t\tA3 : in std_ulogic;"); printf("\n\t\t\tD : in std_ulogic;"); printf("\n\t\t\tWCLK : in std_ulogic;"); printf("\n\t\t\tWE : in std_ulogic);"); printf("\n\tend component;\n"); } if (blockIter) { printf("\n\tcomponent RAMB4_S8"); printf("\n\t\tport("); printf("\n\t\t\tDO : out std_logic_vector(7 downto 0);"); printf("\n\t\t\tADDR : in std_logic_vector(8 downto 0);"); printf("\n\t\t\tCLK : in std_ulogic;"); printf("\n\t\t\tDI : in std_logic_vector(7 downto 0);"); printf("\n\t\t\tEN : in std_ulogic;"); printf("\n\t\t\tRST : in std_ulogic;"); printf("\n\t\t\tWE : in std_ulogic);"); printf("\n\tend component;\n"); } if (selectIter > 0) { printf("\n\tsignal A_r: unsigned(A'range);"); } if (selectIter > 1) { printf("\n\ttype sRAMOut_a is array(0 to %d) of std_logic_vector(D'range);", selectIter - 1); printf("\n\tsignal sRAMOut : sRAMOut_a;"); printf("\n\tsignal siA_r : integer;"); } if (selectIter && blockIter) { printf("\n\tsignal sD : std_logic_vector(D'range);"); } if (blockIter == 1) { printf("\n\tsignal bRAMOut : std_logic_vector(%d downto 0);", bytes * 8 - 1); } if (blockIter > 1) { printf("\n\ttype bRAMOut_a is array(%d to %d) of std_logic_vector(%d downto 0);", blockTotal - blockIter, blockTotal - 1, bytes * 8 - 1); printf("\n\tsignal bRAMOut : bRAMOut_a;"); printf("\n\tsignal biA_r : integer;"); if (!selectIter) { printf("\n\tsignal A_r : unsigned(A'left downto 9);"); } } if (selectIter && blockIter) { printf("\n\tsignal bD : std_logic_vector(D'range);"); } printf("\nbegin"); if (selectIter > 0 || blockIter > 1) { printf("\n\tprocess (Clk)"); printf("\n\tbegin"); printf("\n\t\tif Clk'event and Clk = '1' then"); if (!selectIter) { printf("\n\t\t\tA_r <= unsigned(A(A'left downto 9));"); } else { printf("\n\t\t\tA_r <= unsigned(A);"); } printf("\n\t\tend if;"); printf("\n\tend process;"); } if (selectIter == 1) { printf("\n\n\tsG1: for I in 0 to %d generate", dWidth - 1); printf("\n\t\tS%s : RAM16X1S\n\t\t\tport map (", argv[1]); if (blockIter) { printf("s"); } printf("WE => '0', WCLK => '0', D => '0', O => D(I), A0 => A_r(0), A1 => A_r(1), A2 => A_r(2), A3 => A_r(3));"); printf("\n\tend generate;"); } if (selectIter > 1) { printf("\n\n\tsiA_r <= to_integer(A_r(A'left downto 4));"); printf("\n\n\tsG1: for I in 0 to %d generate", selectIter - 1); printf("\n\t\tsG2: for J in 0 to %d generate", dWidth - 1); printf("\n\t\t\tS%s : RAM16X1S\n\t\t\t\tport map (WE => '0', WCLK => '0', D => '0', O => sRAMOut(I)(J), A0 => A_r(0), A1 => A_r(1), A2 => A_r(2), A3 => A_r(3));", argv[1]); printf("\n\t\tend generate;"); if (z == 'z') { printf("\n\t\t"); if (blockIter) { printf("s"); } printf("D <= sRAMOut(I) when siA_r = I else (others => 'Z');"); } printf("\n\tend generate;"); if (z != 'z') { printf("\n\n\tprocess (siA_r, sRAMOut)\n\tbegin\n\t\t"); if (blockIter) { printf("s"); } printf("D <= sRAMOut(0);"); printf("\n\t\tfor I in 1 to %d loop", selectIter - 1); printf("\n\t\t\tif siA_r = I then\n\t\t\t\t"); if (blockIter) { printf("s"); } printf("D <= sRAMOut(I);\n\t\t\tend if;"); printf("\n\t\tend loop;\n\tend process;"); } } if (blockIter == 1) { printf("\n\n\tbG1: for J in 0 to %d generate", bytes - 1); printf("\n\t\tB%s : RAMB4_S8", argv[1]); printf("\n\t\t\tport map (DI => \"00000000\", EN => '1', RST => '0', WE => '0', CLK => Clk, ADDR => A(8 downto 0), DO => bRAMOut(7 + 8 * J downto 8 * J));", argv[1]); printf("\n\tend generate;"); printf("\n\n\t"); if (selectIter) { printf("b"); } printf("D <= bRAMOut(D'range);"); } if (blockIter > 1) { printf("\n\n\tbiA_r <= to_integer(A_r(A'left downto 9));"); printf("\n\n\tbG1: for I in %d to %d generate", blockTotal - blockIter, blockTotal - 1); printf("\n\t\tbG2: for J in 0 to %d generate", bytes - 1); printf("\n\t\t\tB%s : RAMB4_S8\n\t\t\t\tport map (DI => \"00000000\", EN => '1', RST => '0', WE => '0', CLK => Clk, ADDR => A(8 downto 0), DO => bRAMOut(I)(7 + 8 * J downto 8 * J));", argv[1]); printf("\n\t\tend generate;"); if (z == 'z') { printf("\n\t\t"); if (selectIter) { printf("b"); } printf("D <= bRAMOut(I) when biA_r = I else (others => 'Z');"); } printf("\n\tend generate;"); if (z != 'z') { printf("\n\n\tprocess (biA_r, bRAMOut)\n\tbegin\n\t\t"); if (selectIter) { printf("b"); } printf("D <= bRAMOut(%d)(D'range);", blockTotal - blockIter); printf("\n\t\tfor I in %d to %d loop", blockTotal - blockIter + 1, blockTotal - 1); printf("\n\t\t\tif biA_r = I then\n\t\t\t\t"); if (selectIter) { printf("b"); } printf("D <= bRAMOut(I)(D'range);\n\t\t\tend if;"); printf("\n\t\tend loop;\n\tend process;"); } } if (selectIter && blockIter) { printf("\n\n\tD <= bD when A_r(A'left downto 9) >= %d else sD;", blockTotal - blockIter); } printf("\nend;\n"); return 0; } catch (string error) { cerr << "Fatal: " << error; } catch (const char *error) { cerr << "Fatal: " << error; } return -1; }
zx-simi
trunk/fpga/t80/trunk/sw/xrom.cpp
C++
oos
11,288
// // Binary and intel/motorola hex to VHDL ROM converter // // Version : 0244 // // Copyright (c) 2001-2002 Daniel Wallner (jesus@opencores.org) // // 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 author nor the names of other 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 AUTHOR 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. // // Please report bugs to the author, but before you do so, please // make sure that this is not a derivative work and that // you have the latest version of this file. // // The latest version of this file can be found at: // http://www.opencores.org/cvsweb.shtml/t51/ // // Limitations : // No support for wrapped intel segments // Requires stl to compile // // File history : // // 0146 : Initial release // // 0150 : Added binary read // // 0208 : Changed some errors to warnings // // 0215 : Added support for synchronous ROM // // 0220 : Changed array ROM format, added support for Xilinx .UCF generation // // 0221 : Fixed small .UCF generation for small ROMs // // 0244 : Added Leonardo .UCF option // #include <stdio.h> #include <string> #include <vector> #include <iostream> using namespace std; #if !(defined(max)) && _MSC_VER // VC fix #define max __max #endif class MemBlock { public: unsigned long m_startAddress; vector<unsigned char> m_bytes; }; class File { public: explicit File(const char *fileName, const char *mode) { m_file = fopen(fileName, mode); if (m_file != NULL) { return; } string errorStr = "Error opening "; errorStr += fileName; errorStr += "\n"; throw errorStr; } ~File() { fclose(m_file); } // Read binary file void ReadBin(unsigned long limit) { m_top = 0; m_chunks.push_back(MemBlock()); m_chunks.back().m_startAddress = 0; cerr << "Reading binary file\n"; int tmp = fgetc(m_file); while (!feof(m_file)) { m_chunks.back().m_bytes.push_back(tmp); if (m_chunks.back().m_bytes.size() > limit + 1) { m_chunks.back().m_bytes.pop_back(); m_top = m_chunks.back().m_bytes.size() - 1; cerr << "Ignoring data above address space!\n"; cerr << " Limit: " << limit << "\n"; return; } tmp = fgetc(m_file); } m_top = m_chunks.back().m_bytes.size() - 1; if (!m_chunks.back().m_bytes.size()) { cerr << "No data!\n"; m_chunks.pop_back(); } } // Read hex file void ReadHex(unsigned long limit) { char szLine[1024]; bool formatDetected = false; bool intel; bool endSeen = false; bool linear = true; // Only used for intel hex unsigned long addressBase = 0; // Only used for intel hex unsigned long dataRecords = 0; // Only used for s-record while (!feof(m_file)) { if (fgets(szLine, 1024, m_file) == 0) { if (ferror(m_file)) { throw "Error reading input!\n"; } continue; } if (szLine[strlen(szLine) - 1] == 0xA || szLine[strlen(szLine) - 1] == 0xD) { szLine[strlen(szLine) - 1] = 0; } if (szLine[strlen(szLine) - 1] == 0xA || szLine[strlen(szLine) - 1] == 0xD) { szLine[strlen(szLine) - 1] = 0; } if (strlen(szLine) == 1023) { throw "Hex file lines to long!\n"; } // Ignore blank lines if (szLine[0] == '\n') { continue; } // Detect format and warn if garbage lines are found if (!formatDetected) { if (szLine[0] != ':' && szLine[0] != 'S') { cerr << "Ignoring garbage line!\n"; continue; } if (szLine[0] == 'S') { intel = false; cerr << "Detected S-Record\n"; } else { intel = true; cerr << "Detected intel hex file\n"; } formatDetected = true; } else if ((intel && szLine[0] != ':') || (!intel && szLine[0] != 'S')) { cerr << "Ignoring garbage line!\n"; continue; } if (endSeen) { throw "Hex line after end of file record!\n"; } if (intel) { unsigned long dataBytes; unsigned long startAddress; unsigned long type; if (sscanf(&szLine[1], "%2lx%4lx%2lx", &dataBytes, &startAddress, &type) != 3) { throw "Hex line beginning corrupt!\n"; } // Check line length if (szLine[11 + dataBytes * 2] != '\n' && szLine[11 + dataBytes * 2] != 0) { throw "Hex line length incorrect!\n"; } // Check line checksum unsigned char checkSum = 0; unsigned long tmp; for (unsigned int i = 0; i <= dataBytes + 4; ++i) { if (sscanf(&szLine[1 + i * 2], "%2lx", &tmp) != 1) { throw "Hex line data corrupt!\n"; } checkSum += tmp; } if (checkSum != 0) { throw "Hex line checksum error!\n"; } switch (type) { case 0: // Data record if (!linear) { // Segmented unsigned long test = startAddress; test += dataBytes; if (test > 0xffff) { throw "Can't handle wrapped segments!\n"; } } if (!m_chunks.size() || m_chunks.back().m_startAddress + m_chunks.back().m_bytes.size() != addressBase + startAddress) { m_chunks.push_back(MemBlock()); m_chunks.back().m_startAddress = addressBase + startAddress; } { unsigned char i = 0; for (i = 0; i < dataBytes; ++i) { sscanf(&szLine[9 + i * 2], "%2lx", &tmp); if (addressBase + startAddress + i > limit) { cerr << "Ignoring data above address space!\n"; cerr << "Data address: " << addressBase + startAddress + i; cerr << " Limit: " << limit << "\n"; if (!m_chunks.back().m_bytes.size()) { m_chunks.pop_back(); } continue; } m_chunks.back().m_bytes.push_back(tmp); } } break; case 1: // End-of-file record if (dataBytes != 0) { cerr << "Warning: End of file record not zero length!\n"; } if (startAddress != 0) { cerr << "Warning: End of file record address not zero!\n"; } endSeen = true; break; case 2: // Extended segment address record if (dataBytes != 2) { throw "Length field must be 2 in extended segment address record!\n"; } if (startAddress != 0) { throw "Address field must be zero in extended segment address record!\n"; } sscanf(&szLine[9], "%4lx", &startAddress); addressBase = startAddress << 4; linear = false; break; case 3: // Start segment address record if (dataBytes != 4) { cerr << "Warning: Length field must be 4 in start segment address record!\n"; } if (startAddress != 0) { cerr << "Warning: Address field must be zero in start segment address record!\n"; } if (dataBytes == 4) { unsigned long ssa; char ssaStr[16]; sscanf(&szLine[9], "%8lx", &ssa); sprintf(ssaStr, "%08X\n", ssa); cerr << "Segment start address (CS/IP): "; cerr << ssaStr; } break; case 4: // Extended linear address record if (dataBytes != 2) { throw "Length field must be 2 in extended linear address record!\n"; } if (startAddress != 0) { throw "Address field must be zero in extended linear address record!\n"; } sscanf(&szLine[9], "%4lx", &startAddress); addressBase = ((unsigned long)startAddress) << 16; linear = true; break; case 5: // Start linear address record if (dataBytes != 4) { cerr << "Warning: Length field must be 4 in start linear address record!\n"; } if (startAddress != 0) { cerr << "Warning: Address field must be zero in start linear address record!\n"; } if (dataBytes == 4) { unsigned long lsa; char lsaStr[16]; sscanf(&szLine[9], "%8lx", &lsa); sprintf(lsaStr, "%08X\n", lsa); cerr << "Linear start address: "; cerr << lsaStr; } break; default: cerr << "Waring: Unknown record found!\n"; } } else { // S-record unsigned long count; char type; if (sscanf(&szLine[1], "%c%2lx", &type, &count) != 2) { throw "Hex line beginning corrupt!\n"; } // Check line length if (szLine[4 + count * 2] != '\n' && szLine[4 + count * 2] != 0) { throw "Hex line length incorrect!\n"; } // Check line checksum unsigned char checkSum = 0; unsigned long tmp; for (unsigned int i = 0; i < count + 1; ++i) { if (sscanf(&szLine[2 + i * 2], "%2lx", &tmp) != 1) { throw "Hex line data corrupt!\n"; } checkSum += tmp; } if (checkSum != 255) { throw "Hex line checksum error!\n"; } switch (type) { case '0': // Header record { char header[256]; unsigned char i = 0; for (i = 0; i + 3 < count; ++i) { sscanf(&szLine[8 + i * 2], "%2lx", &tmp); header[i] = tmp; } header[i] = 0; if (i > 0) { cerr << "Module name: " << header << "\n"; } } break; case '1': case '2': case '3': // Data record { dataRecords++; unsigned long startAddress; if (type == '1') { sscanf(&szLine[4], "%4lx", &startAddress); } else if (type == '2') { sscanf(&szLine[4], "%6lx", &startAddress); } else { sscanf(&szLine[4], "%8lx", &startAddress); } if (!m_chunks.size() || m_chunks.back().m_startAddress + m_chunks.back().m_bytes.size() != startAddress) { m_chunks.push_back(MemBlock()); m_chunks.back().m_startAddress = startAddress; } unsigned char i = 0; for (i = (type - '1'); i + 3 < count; ++i) { sscanf(&szLine[8 + i * 2], "%2lx", &tmp); if (startAddress + i > limit) { cerr << "Ignoring data above address space!\n"; cerr << "Data address: " << startAddress + i; cerr << " Limit: " << limit << "\n"; if (!m_chunks.back().m_bytes.size()) { m_chunks.pop_back(); } continue; } m_chunks.back().m_bytes.push_back(tmp); } } break; case '5': // Count record { unsigned long address; sscanf(&szLine[4], "%4lx", &address); if (address != dataRecords) { throw "Wrong number of data records!\n"; } } break; case '7': case '8': case '9': // Start address record cerr << "Ignoring start address record!\n"; break; default: cerr << "Unknown record found!\n"; } } } if (intel && !endSeen) { cerr << "No end of file record!\n"; } if (!m_chunks.size()) { throw "No data in file!\n"; } vector<MemBlock>::iterator vi; m_top = 0; for (vi = m_chunks.begin(); vi < m_chunks.end(); vi++) { m_top = max(m_top, vi->m_startAddress + vi->m_bytes.size() - 1); } } // Rather inefficient this one, fix sometime bool GetByte(const unsigned long address, unsigned char &chr) { vector<MemBlock>::iterator vi; for (vi = m_chunks.begin(); vi < m_chunks.end(); vi++) { if (vi->m_startAddress + vi->m_bytes.size() > address && vi->m_startAddress <= address) { break; } } if (vi == m_chunks.end()) { return false; } chr = vi->m_bytes[address - vi->m_startAddress]; return true; } bool BitString(const unsigned long address, const unsigned char bits, const bool lEndian, string &str) { bool ok = false; long i; unsigned char chr; unsigned long data = 0; unsigned long tmp; if (lEndian) { for (i = 0; i < (bits + 7) / 8; ++i) { ok |= GetByte(address + i, chr); tmp = chr; data |= tmp << (8 * i); } } else { for (i = 0; i < (bits + 7) / 8; ++i) { ok |= GetByte(address + i, chr); tmp = chr; data |= tmp << (8 * ((bits + 7) / 8 - i - 1)); } } if (!ok) { return false; } unsigned long mask = 1; str = ""; for (i = 0; i < bits; i++) { if (data & mask) { str.insert(0,"1"); } else { str.insert(0,"0"); } mask <<= 1; } return true; } FILE *Handle() { return m_file; }; vector<MemBlock> m_chunks; unsigned long m_top; private: FILE *m_file; }; int main (int argc, char *argv[]) { cerr << "Hex to VHDL ROM converter by Daniel Wallner. Version 0244\n"; try { unsigned long aWidth; unsigned long dWidth; char endian; char O = 0; if (!(argc == 4 || argc == 5)) { cerr << "\nUsage: hex2rom [-b] <input file> <entity name> <format>\n"; cerr << "\nIf the -b option is specified the file is read as a binary file\n"; cerr << "Hex input files must be intel hex or motorola s-record\n"; cerr << "\nThe format string has the format AEDOS where:\n"; cerr << " A = Address bits\n"; cerr << " E = Endianness, l or b\n"; cerr << " D = Data bits\n"; cerr << " O = ROM type: (one optional character)\n"; cerr << " z for tri-state output\n"; cerr << " a for array ROM\n"; cerr << " s for synchronous ROM\n"; cerr << " u for XST ucf\n"; cerr << " l for Leonardo ucf\n"; cerr << " S = SelectRAM usage in 1/16 parts (only used when O = u)\n"; cerr << "\nExample:\n"; cerr << " hex2rom test.hex Test_ROM 18b16z\n\n"; return -1; } string inFileName; string outFileName; unsigned long bytes; unsigned long select = 0; if (argc == 5) { if (strcmp(argv[1], "-b")) { throw "Error in arguments!\n"; } } int result; result = sscanf(argv[argc - 1], "%lu%c%lu%c%lu", &aWidth, &endian, &dWidth, &O, &select); if (result < 3) { throw "Error in output format argument!\n"; } if (aWidth > 32 || (endian != 'l' && endian != 'b') || dWidth > 32 || (result > 3 && O != 'z' && O != 'a' && O != 's' && O != 'u' && O != 'l')) { throw "Error in output format argument!\n"; } inFileName = argv[argc - 3]; outFileName = argv[argc - 2]; bytes = (dWidth + 7) / 8; File inFile(inFileName.c_str(), "rb"); if (argc == 4) { inFile.ReadHex((1UL << aWidth) * bytes - 1); } else { inFile.ReadBin((1UL << aWidth) * bytes - 1); } string line; unsigned long words = 1; unsigned long i = inFile.m_top; i /= bytes; while (i != 0) { i >>= 1; words <<= 1; } if (O != 'u' && O != 'l') { printf("-- This file was generated with hex2rom written by Daniel Wallner\n"); printf("\nlibrary IEEE;"); printf("\nuse IEEE.std_logic_1164.all;"); printf("\nuse IEEE.numeric_std.all;"); printf("\n\nentity %s is", outFileName.c_str()); printf("\n\tport("); if (O == 'z') { printf("\n\t\tCE_n\t: in std_logic;", dWidth - 1); printf("\n\t\tOE_n\t: in std_logic;", dWidth - 1); } if (O == 's') { printf("\n\t\tClk\t: in std_logic;", dWidth - 1); } printf("\n\t\tA\t: in std_logic_vector(%d downto 0);", aWidth - 1); printf("\n\t\tD\t: out std_logic_vector(%d downto 0)", dWidth - 1); printf("\n\t);"); printf("\nend %s;", outFileName.c_str()); printf("\n\narchitecture rtl of %s is", outFileName.c_str()); if (!O) { printf("\nbegin"); printf("\n\tprocess (A)"); printf("\n\tbegin"); printf("\n\t\tcase to_integer(unsigned(A)) is"); } else if (O == 's') { printf("\n\tsignal A_r : std_logic_vector(%d downto 0);", aWidth - 1); printf("\nbegin"); printf("\n\tprocess (Clk)"); printf("\n\tbegin"); printf("\n\t\tif Clk'event and Clk = '1' then"); printf("\n\t\t\tA_r <= A;"); printf("\n\t\tend if;"); printf("\n\tend process;"); printf("\n\tprocess (A_r)"); printf("\n\tbegin"); printf("\n\t\tcase to_integer(unsigned(A_r)) is"); } else { printf("\n\tsubtype ROM_WORD is std_logic_vector(%d downto 0);", dWidth - 1); printf("\n\ttype ROM_TABLE is array(0 to %d) of ROM_WORD;", words - 1); printf("\n\tconstant ROM: ROM_TABLE := ROM_TABLE'("); } string str; string strDC; for (i = 0; i < dWidth; i++) { strDC.insert(0, "-"); } for (i = 0; i < words; i++) { if (!inFile.BitString(i * bytes, dWidth, endian == 'l', str)) { str = strDC; } if (!O || O == 's') { if (inFile.m_top / bytes >= i) { printf("\n\t\twhen %06d => D <= \"%s\";",i, str.c_str()); printf("\t-- 0x%04X", i * bytes); } } else { printf("\n\t\t\"%s", str.c_str()); if (i != words - 1) { printf("\","); } else { printf("\");"); } printf("\t-- 0x%04X", i * bytes); } } if (!O || O == 's') { printf("\n\t\twhen others => D <= \"%s\";", strDC.c_str()); printf("\n\t\tend case;"); printf("\n\tend process;"); } else { printf("\nbegin"); if (O == 'z') { printf("\n\tD <= ROM(to_integer(unsigned(A))) when CE_n = '0' and OE_n = '0' else (others => 'Z');"); } else { printf("\n\tD <= ROM(to_integer(unsigned(A)));"); } } printf("\nend;\n"); } else { unsigned long selectIter = 0; unsigned long blockIter = 0; if (!select) { blockIter = ((1UL << aWidth) + 511) / 512; } else if (select == 16) { selectIter = ((1UL << aWidth) + 15) / 16; } else { blockIter = ((1UL << aWidth) * (16 - select) / 16 + 511) / 512; selectIter = ((1UL << aWidth) - blockIter * 512 + 15) / 16; } cerr << "Creating .ucf file with " << selectIter * bytes; cerr << " LUTs and " << blockIter * bytes << " block RAMs\n"; unsigned long blockTotal = ((1UL << aWidth) + 511) / 512; printf("# This file was generated with hex2rom written by Daniel Wallner\n"); for (i = 0; i < selectIter; i++) { unsigned long base = i * 16 * bytes; unsigned long j; unsigned char c; unsigned long pos; // Check that there is any actual data in segment bool init = false; for (pos = 0; pos < bytes * 16; pos++) { init = inFile.GetByte(base + pos, c); if (init) { break; } } if (init) { for (j = 0; j < dWidth; j++) { unsigned long bitMask = 1; unsigned long bits = 0; for (pos = 0; pos < 16; pos++) { unsigned long addr; if (endian = 'l') { addr = base + bytes * pos + j / 8; } else { addr = base + bytes * pos + bytes - j / 8 - 1; } c = 0; inFile.GetByte(addr, c); if (c & (1 << (j % 8))) { bits |= bitMask; } bitMask <<= 1; } if (O == 'u') { if (selectIter == 1) { printf("\nINST *s%s%d INIT = %04X;", outFileName.c_str(), j, bits); } else { printf("\nINST *s%s%d%d INIT = %04X;", outFileName.c_str(), i, j, bits); } } else { if (selectIter == 1) { printf("\nINST *sG1_%d_S%s INIT = %04X;", j, outFileName.c_str(), bits); } else { printf("\nINST *sG1_%d_sG2_%d_S%s INIT = %04X;", i, j, outFileName.c_str(), bits); } } } } } for (i = blockTotal - blockIter; i < blockTotal; i++) { unsigned long j; for (j = 0; j < bytes; j++) { unsigned long k; for (k = 0; k < 16; k++) { unsigned long base = i * 512 * bytes + k * 32 * bytes; unsigned char c; unsigned long pos; // Check that there is any actual data in segment bool init = false; for (pos = 0; pos < 32; pos++) { init = inFile.GetByte(base + bytes * pos + j, c); if (init) { break; } } if (init) { if (O == 'u') { if (blockIter == 1) { printf("\nINST *b%s%d INIT_%02X = ", outFileName.c_str(), j, k); } else { printf("\nINST *b%s%d%d INIT_%02X = ", outFileName.c_str(), i, j, k); } } else { if (blockIter == 1) { printf("\nINST *bG1_%d_B%s INIT_%02X = ", j, outFileName.c_str(), k); } else { printf("\nINST *bG1_%d_bG2_%d_B%s INIT_%02X = ", i, j, outFileName.c_str(), k); } } for (pos = 0; pos < 32; pos++) { unsigned long addr; if (endian = 'l') { addr = base + bytes * (31 - pos) + j; } else { addr = base + bytes * (31 - pos) + bytes - j - 1; } c = 0; inFile.GetByte(addr, c); printf("%02X", c); } printf(";"); } } } } printf("\n"); } return 0; } catch (string error) { cerr << "Fatal: " << error; } catch (const char *error) { cerr << "Fatal: " << error; } return -1; }
zx-simi
trunk/fpga/t80/trunk/sw/hex2rom.cpp
C++
oos
22,100
set name=t80 rem set target=xc2v250-cs144-6 rem set target=xcv300e-pq240-8 set target=xc2s200-pq208-5 if "%2" == "" goto default set target=%2 :default cd ..\out if "%1" == "" goto xst set name=t80_leo copy ..\bin\t80_leo.pin %name%.ucf ngdbuild -p %target% %1 %name%.ngd goto builddone :xst copy ..\bin\%name%.pin %name%.ucf xst -ifn ../bin/%name%.scr -ofn ../log/%name%.srp ngdbuild -p %target% %name%.ngc :builddone move %name%.bld ..\log map -p %target% -cm speed -c 100 -tx on -o %name%_map %name% move %name%_map.mrp ..\log\%name%.mrp par -ol 3 -t 1 %name%_map -w %name% move %name%.par ..\log trce %name%.ncd -o ../log/%name%.twr %name%_map.pcf bitgen -w %name% move %name%.bgn ..\log cd ..\run
zx-simi
trunk/fpga/t80/trunk/syn/xilinx/run/t80.bat
Batchfile
oos
719
cd ..\out hex2rom ..\..\..\sw\monitor.hex MonZ80 11b8s > ..\src\MonZ80_leo.vhd spectrum -file ..\bin\t80debug.tcl move exemplar.log ..\log\t80debug_leo.srp cd ..\run t80debug t80debug_leo.edf xc2s200-pq208-5
zx-simi
trunk/fpga/t80/trunk/syn/xilinx/run/t80debug_leo.bat
Batchfile
oos
212
cd ..\out hex2rom ..\..\..\sw\monitorxr.hex MonZ80 11b8s > ..\src\MonZ80_leo.vhd spectrum -file ..\bin\t80debugxr.tcl move exemplar.log ..\log\t80debugxr_leo.srp cd ..\run t80debugxr t80debugxr_leo.edf xc2s200-pq208-5
zx-simi
trunk/fpga/t80/trunk/syn/xilinx/run/t80debugxr_leo.bat
Batchfile
oos
222
set name=t80debug rem set target=xc2v250-cs144-6 rem set target=xcv300e-pq240-8 set target=xc2s200-pq208-5 if "%2" == "" goto default set target=%2 :default cd ..\out if "%1" == "" goto xst set name=t80debug_leo copy ..\bin\t80debug.pin %name%.ucf ngdbuild -p %target% %1 %name%.ngd goto builddone :xst xrom MonZ80 11 8 > ..\src\MonZ80.vhd hex2rom ..\..\..\sw\monitor.hex MonZ80 11b8u > MonZ80.ini copy ..\out\MonZ80.ini + ..\bin\%name%.pin %name%.ucf xst -ifn ../bin/%name%.scr -ofn ../log/%name%.srp ngdbuild -p %target% %name%.ngc :builddone move %name%.bld ..\log map -p %target% -cm speed -c 100 -pr b -timing -tx on -o %name%_map %name% move %name%_map.mrp ..\log\%name%.mrp par -ol 3 -t 1 %name%_map -w %name% move %name%.par ..\log trce %name%.ncd -o ../log/%name%.twr %name%_map.pcf bitgen -w %name% move %name%.bgn ..\log cd ..\run
zx-simi
trunk/fpga/t80/trunk/syn/xilinx/run/t80debug.bat
Batchfile
oos
859
set name=t80debugxr rem set target=xc2v250-cs144-6 rem set target=xcv300e-pq240-8 set target=xc2s200-pq208-5 if "%2" == "" goto default set target=%2 :default cd ..\out if "%1" == "" goto xst set name=t80debugxr_leo copy ..\bin\t80debugxr_leo.pin %name%.ucf ngdbuild -p %target% %1 %name%.ngd goto builddone :xst xrom MonZ80 11 8 > ..\src\MonZ80.vhd hex2rom ..\..\..\sw\monitorxr.hex MonZ80 11b8u > MonZ80.ini copy ..\out\MonZ80.ini + ..\bin\%name%.pin %name%.ucf xst -ifn ../bin/%name%.scr -ofn ../log/%name%.srp ngdbuild -p %target% %name%.ngc :builddone move %name%.bld ..\log map -p %target% -cm speed -c 100 -pr b -timing -tx on -o %name%_map %name% move %name%_map.mrp ..\log\%name%.mrp par -ol 3 -t 1 %name%_map -w %name% move %name%.par ..\log trce %name%.ncd -o ../log/%name%.twr %name%_map.pcf bitgen -w %name% move %name%.bgn ..\log cd ..\run
zx-simi
trunk/fpga/t80/trunk/syn/xilinx/run/t80debugxr.bat
Batchfile
oos
871
cd ..\out spectrum -file ..\bin\t80.tcl move exemplar.log ..\log\t80_leo.srp cd ..\run t80 t80_leo.edf xc2s200-pq208-5
zx-simi
trunk/fpga/t80/trunk/syn/xilinx/run/t80_leo.bat
Batchfile
oos
122
-- -- File I/O test-bench utilities -- -- Version : 0146 -- -- Copyright (c) 2001 Daniel Wallner (jesus@opencores.org) -- -- All rights reserved -- -- Redistribution and use in source and synthezised 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 synthesized 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 author nor the names of other 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 AUTHOR 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. -- -- Please report bugs to the author, but before you do so, please -- make sure that this is not a derivative work and that -- you have the latest version of this file. -- -- The latest version of this file can be found at: -- http://www.opencores.org/cvsweb.shtml/t51/ -- -- Limitations : -- -- File history : -- library IEEE; use IEEE.std_logic_1164.all; package StimLog is component AsyncStim generic( FileName : string; Baud : integer; InterCharDelay : time := 0 ns; Bits : integer := 8; -- Data bits Parity : boolean := false; -- Enable Parity P_Odd_Even_n : boolean := false -- false => Even Parity, true => Odd Parity ); port( TXD : out std_logic ); end component; component AsyncLog generic( FileName : string; Baud : integer; Bits : integer := 8; -- Data bits Parity : boolean := false; -- Enable Parity P_Odd_Even_n : boolean := false -- false => Even Parity, true => Odd Parity ); port( RXD : in std_logic ); end component; component BinaryStim generic( FileName : string; Bytes : integer := 1; -- Number of bytes per word LittleEndian : boolean := true -- Byte order ); port( Rd : in std_logic; Data : out std_logic_vector(Bytes * 8 - 1 downto 0) ); end component; component BinaryLog generic( FileName : string; Bytes : integer := 1; -- Number of bytes per word LittleEndian : boolean := true -- Byte order ); port( Clk : in std_logic; En : in std_logic; Data : in std_logic_vector(Bytes * 8 - 1 downto 0) ); end component; component I2SStim is generic( FileName : string; Bytes : integer := 2; -- Number of bytes per word (1 to 4) LittleEndian : boolean := true -- Byte order ); port( BClk : in std_logic; FSync : in std_logic; SData : out std_logic ); end component; component I2SLog is generic( FileName : string; Bytes : integer := 2; -- Number of bytes per word LittleEndian : boolean := true -- Byte order ); port( BClk : in std_logic; FSync : in std_logic; SData : in std_logic ); end component; component IntegerLog is generic( FileName : string ); port( Clk : in std_logic; En : in std_logic; Data : in integer ); end component; end;
zx-simi
trunk/fpga/t80/trunk/bench/vhdl/StimLog.vhd
VHDL
oos
4,034
-- -- Simple SRAM model without timing -- -- Version : 0247 -- -- Copyright (c) 2001 Daniel Wallner (jesus@opencores.org) -- -- All rights reserved -- -- Redistribution and use in source and synthezised 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 synthesized 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 author nor the names of other 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 AUTHOR 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. -- -- Please report bugs to the author, but before you do so, please -- make sure that this is not a derivative work and that -- you have the latest version of this file. -- -- The latest version of this file can be found at: -- http://www.opencores.org/cvsweb.shtml/t80/ -- -- Limitations : -- -- File history : -- library IEEE; use IEEE.std_logic_1164.all; use IEEE.numeric_std.all; entity SRAM is generic( AddrWidth : integer := 16; DataWidth : integer := 8 ); port( CE_n : in std_logic; OE_n : in std_logic; WE_n : in std_logic; A : in std_logic_vector(AddrWidth - 1 downto 0); D : inout std_logic_vector(DataWidth - 1 downto 0) ); end SRAM; architecture behaviour of SRAM is type Memory_Image is array (natural range <>) of std_logic_vector(DataWidth - 1 downto 0); signal RAM : Memory_Image(0 to 2 ** AddrWidth - 1); signal Write : std_logic; signal D_del : std_logic_vector(7 downto 0); begin Write <= '1' when CE_n = '0' and WE_n = '0' else '0'; D_del <= D after 1 ns; process (Write) begin if Write'event and Write = '0' then RAM(to_integer(unsigned(A))) <= D_del; end if; end process; D <= RAM(to_integer(unsigned(A))) -- pragma translate_off when OE_n = '0' and CE_n = '0' and WE_n = '1' and not is_x(A) else (others => 'Z') -- pragma translate_on ; end;
zx-simi
trunk/fpga/t80/trunk/bench/vhdl/SRAM.vhd
VHDL
oos
2,957
library IEEE; use IEEE.std_logic_1164.all; use work.StimLog.all; entity TestBench is end entity TestBench; architecture behaviour of TestBench is signal M1_n : std_logic; signal MREQ_n : std_logic; signal IORQ_n : std_logic; signal RD_n : std_logic; signal WR_n : std_logic; signal RFSH_n : std_logic; signal HALT_n : std_logic; signal WAIT_n : std_logic := '1'; signal INT_n : std_logic := '1'; signal NMI_n : std_logic := '1'; signal RESET_n : std_logic; signal BUSRQ_n : std_logic := '1'; signal BUSAK_n : std_logic; signal CLK_n : std_logic := '0'; signal A : std_logic_vector(15 downto 0); signal D : std_logic_vector(7 downto 0); signal UART_D : std_logic_vector(7 downto 0); signal BaudOut : std_logic; signal TXD : std_logic; signal RXD : std_logic; signal CTS : std_logic := '0'; signal DSR : std_logic := '0'; signal RI : std_logic := '1'; signal DCD : std_logic := '0'; signal IOWR_n : std_logic; signal ROMCS_n : std_logic; signal RAMCS_n : std_logic; signal UARTCS_n : std_logic; begin Reset_n <= '0', '1' after 1 us; -- 16 MHz clock CLK_n <= not CLK_n after 31.25 ns; IOWR_n <= WR_n or IORQ_n; ROMCS_n <= A(15) or MREQ_n; RAMCS_n <= not A(15) or MREQ_n; UARTCS_n <= '0' when IORQ_n = '0' and A(7 downto 3) = "00000" else '1'; -- NMI NMI_n <= not D(0) when IOWR_n'event and IOWR_n = '1' and A(7 downto 0) = "00001000"; -- INT INT_n <= not D(1) when IOWR_n'event and IOWR_n = '1' and A(7 downto 0) = "00001000"; as : AsyncStim generic map(FileName => "../../../bench/vhdl/ROM80.vhd", InterCharDelay => 100 us, Baud => 1000000, Bits => 8) port map(RXD); al : AsyncLog generic map(FileName => "RX_Log.txt", Baud => 1000000, Bits => 8) port map(TXD); u0 : entity work.T80a port map( RESET_n, CLK_n, WAIT_n, INT_n, NMI_n, BUSRQ_n, M1_n, MREQ_n, IORQ_n, RD_n, WR_n, RFSH_n, HALT_n, BUSAK_n, A, D); u1 : entity work.ROM80 port map( CE_n => ROMCS_n, OE_n => RD_n, A => A(14 downto 0), D => D); u2 : entity work.SRAM generic map( AddrWidth => 15) port map( CE_n => RAMCS_n, OE_n => RD_n, WE_n => WR_n, A => A(14 downto 0), D => D); D <= UART_D when UARTCS_n = '0' and RD_n = '0' else "ZZZZZZZZ"; u3 : entity work.T16450 port map( MR_n => Reset_n, XIn => CLK_n, RClk => BaudOut, CS_n => UARTCS_n, Rd_n => RD_n, Wr_n => IOWR_n, A => A(2 downto 0), D_In => D, D_Out => UART_D, SIn => RXD, CTS_n => CTS, DSR_n => DSR, RI_n => RI, DCD_n => DCD, SOut => TXD, RTS_n => open, DTR_n => open, OUT1_n => open, OUT2_n => open, BaudOut => BaudOut, Intr => open); end;
zx-simi
trunk/fpga/t80/trunk/bench/vhdl/TestBench.vhd
VHDL
oos
2,772
library IEEE; use IEEE.std_logic_1164.all; use work.StimLog.all; entity DebugSystem_TB is end entity DebugSystem_TB; architecture behaviour of DebugSystem_TB is signal Reset_n : std_logic; signal Clk : std_logic := '0'; signal NMI_n : std_logic := '1'; signal TXD0 : std_logic; signal RTS0 : std_logic; signal DTR0 : std_logic; signal RXD0 : std_logic; signal CTS0 : std_logic := '0'; signal DSR0 : std_logic := '0'; signal RI0 : std_logic := '1'; signal DCD0 : std_logic := '0'; signal TXD1 : std_logic; signal RTS1 : std_logic; signal DTR1 : std_logic; signal RXD1 : std_logic; signal CTS1 : std_logic := '0'; signal DSR1 : std_logic := '0'; signal RI1 : std_logic := '1'; signal DCD1 : std_logic := '0'; begin ni : entity work.DebugSystem port map( Reset_n => Reset_n, Clk => Clk, NMI_n => NMI_n, RXD0 => RXD0, CTS0 => CTS0, DSR0 => DSR0, RI0 => RI0, DCD0 => DCD0, RXD1 => RXD1, CTS1 => CTS1, DSR1 => DSR1, RI1 => RI1, DCD1 => DCD1, TXD0 => TXD0, RTS0 => RTS0, DTR0 => DTR0, TXD1 => TXD1, RTS1 => RTS1, DTR1 => DTR1); as0 : AsyncStim generic map(FileName => "../../../bench/vhdl/ROM80.vhd", InterCharDelay => 0 us, Baud => 115200, Bits => 8) port map(RXD0); al0 : AsyncLog generic map(FileName => "RX_Log0.txt", Baud => 115200, Bits => 8) port map(TXD0); as1 : AsyncStim generic map(FileName => "RX_Cmd1.txt", InterCharDelay => 0 us, Baud => 115200, Bits => 8) port map(RXD1); al1 : AsyncLog generic map(FileName => "RX_Log1.txt", Baud => 115200, Bits => 8) port map(TXD1); Reset_n <= '0', '1' after 1 us; -- 18 MHz clock Clk <= not Clk after 27 ns; end;
zx-simi
trunk/fpga/t80/trunk/bench/vhdl/DebugSystem_TB.vhd
VHDL
oos
1,710
-- -- Asynchronous serial generator with input from binary file -- -- Version : 0146 -- -- Copyright (c) 2001 Daniel Wallner (jesus@opencores.org) -- -- All rights reserved -- -- Redistribution and use in source and synthezised 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 synthesized 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 author nor the names of other 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 AUTHOR 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. -- -- Please report bugs to the author, but before you do so, please -- make sure that this is not a derivative work and that -- you have the latest version of this file. -- -- The latest version of this file can be found at: -- http://www.opencores.org/cvsweb.shtml/t51/ -- -- Limitations : -- -- File history : -- library IEEE; use IEEE.std_logic_1164.all; use IEEE.numeric_std.all; entity AsyncStim is generic( FileName : string; Baud : integer; InterCharDelay : time := 0 ns; Bits : integer := 8; -- Data bits Parity : boolean := false; -- Enable Parity P_Odd_Even_n : boolean := false -- false => Even Parity, true => Odd Parity ); port( TXD : out std_logic ); end AsyncStim; architecture behaviour of AsyncStim is signal TX_ShiftReg : std_logic_vector(Bits - 1 downto 0); signal TX_Bit_Cnt : integer range 0 to 15 := 0; signal ParTmp : boolean; begin process type ChFile is file of character; file InFile : ChFile open read_mode is FileName; variable Inited : boolean := false; variable CharTmp : character; variable IntTmp : integer; begin if not Inited then Inited := true; TXD <= '1'; end if; wait for 1000000000 ns / Baud; TX_Bit_Cnt <= TX_Bit_Cnt + 1; case TX_Bit_Cnt is when 0 => TXD <= '1'; wait for InterCharDelay; when 1 => -- Start bit read(InFile, CharTmp); IntTmp := character'pos(CharTmp); TX_ShiftReg(Bits - 1 downto 0) <= std_logic_vector(to_unsigned(IntTmp, Bits)); TXD <= '0'; ParTmp <= P_Odd_Even_n; when others => TXD <= TX_ShiftReg(0); ParTmp <= ParTmp xor (TX_ShiftReg(0) = '1'); TX_ShiftReg(Bits - 2 downto 0) <= TX_ShiftReg(Bits - 1 downto 1); if (TX_Bit_Cnt = Bits + 1 and not Parity) or (TX_Bit_Cnt = Bits + 2 and Parity) then -- Stop bit TX_Bit_Cnt <= 0; end if; if Parity and TX_Bit_Cnt = Bits + 2 then if ParTmp then TXD <= '1'; else TXD <= '0'; end if; end if; end case; end process; end;
zx-simi
trunk/fpga/t80/trunk/bench/vhdl/AsyncStim.vhd
VHDL
oos
3,757
-- -- Asynchronous serial input with binary file log -- -- Version : 0146 -- -- Copyright (c) 2001 Daniel Wallner (jesus@opencores.org) -- -- All rights reserved -- -- Redistribution and use in source and synthezised 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 synthesized 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 author nor the names of other 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 AUTHOR 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. -- -- Please report bugs to the author, but before you do so, please -- make sure that this is not a derivative work and that -- you have the latest version of this file. -- -- The latest version of this file can be found at: -- http://www.opencores.org/cvsweb.shtml/t51/ -- -- Limitations : -- -- File history : -- library IEEE; use IEEE.std_logic_1164.all; use IEEE.numeric_std.all; entity AsyncLog is generic( FileName : string; Baud : integer; Bits : integer := 8; -- Data bits Parity : boolean := false; -- Enable Parity P_Odd_Even_n : boolean := false -- false => Even Parity, true => Odd Parity ); port( RXD : in std_logic ); end AsyncLog; architecture behaviour of AsyncLog is function to_char( constant Byte : std_logic_vector(7 downto 0) ) return character is begin return character'val(to_integer(unsigned(Byte))); end function; signal Baud16 : std_logic := '0'; -- Receive signals signal Bit_Phase : unsigned(3 downto 0) := "0000"; signal RX_ShiftReg : std_logic_vector(Bits - 1 downto 0) := (others => '0'); signal RX_Bit_Cnt : integer := 0; signal ParTmp : boolean; begin Baud16 <= not Baud16 after 1000000000 ns / 32 / Baud; process (Baud16) type ChFile is file of character; file OutFile : ChFile open write_mode is FileName; begin if Baud16'event and Baud16 = '1' then if RX_Bit_Cnt = 0 and (RXD = '1' or Bit_Phase = "0111") then Bit_Phase <= "0000"; else Bit_Phase <= Bit_Phase + 1; end if; if RX_Bit_Cnt = 0 then if Bit_Phase = "0111" then RX_Bit_Cnt <= RX_Bit_Cnt + 1; end if; ParTmp <= false; elsif Bit_Phase = "1111" then RX_Bit_Cnt <= RX_Bit_Cnt + 1; if (RX_Bit_Cnt = Bits + 1 and not Parity) or (RX_Bit_Cnt = Bits + 2 and Parity) then -- Stop bit RX_Bit_Cnt <= 0; assert RXD = '1' report "Framing error" severity error; write(OutFile, to_char(RX_ShiftReg(7 downto 0))); elsif RX_Bit_Cnt = Bits + 1 and Parity then -- Parity bit assert ParTmp xor (RXD = '1') = P_Odd_Even_n report "Parity error" severity error; else ParTmp <= ParTmp xor (RXD = '1'); RX_ShiftReg(Bits - 2 downto 0) <= RX_ShiftReg(Bits - 1 downto 1); RX_ShiftReg(Bits - 1) <= RXD; end if; end if; end if; end process; end;
zx-simi
trunk/fpga/t80/trunk/bench/vhdl/AsyncLog.vhd
VHDL
oos
4,081
-- -- 16450 compatible UART with synchronous bus interface -- RClk/BaudOut is XIn enable instead of actual clock -- -- Version : 0249b -- -- Copyright (c) 2002 Daniel Wallner (jesus@opencores.org) -- -- All rights reserved -- -- Redistribution and use in source and synthezised 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 synthesized 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 author nor the names of other 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 AUTHOR 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. -- -- Please report bugs to the author, but before you do so, please -- make sure that this is not a derivative work and that -- you have the latest version of this file. -- -- The latest version of this file can be found at: -- http://www.opencores.org/cvsweb.shtml/t80/ -- -- Limitations : -- -- File history : -- -- 0208 : First release -- -- 0249 : Fixed interrupt and baud rate bugs found by Andy Dyer -- Added modem status and break detection -- Added support for 1.5 and 2 stop bits -- -- 0249b : Fixed loopback break generation bugs found by Andy Dyer -- library IEEE; use IEEE.std_logic_1164.all; use IEEE.numeric_std.all; entity T16450 is port( MR_n : in std_logic; XIn : in std_logic; RClk : in std_logic; CS_n : in std_logic; Rd_n : in std_logic; Wr_n : in std_logic; A : in std_logic_vector(2 downto 0); D_In : in std_logic_vector(7 downto 0); D_Out : out std_logic_vector(7 downto 0); SIn : in std_logic; CTS_n : in std_logic; DSR_n : in std_logic; RI_n : in std_logic; DCD_n : in std_logic; SOut : out std_logic; RTS_n : out std_logic; DTR_n : out std_logic; OUT1_n : out std_logic; OUT2_n : out std_logic; BaudOut : out std_logic; Intr : out std_logic ); end T16450; architecture rtl of T16450 is signal RBR : std_logic_vector(7 downto 0); -- Reciever Buffer Register signal THR : std_logic_vector(7 downto 0); -- Transmitter Holding Register signal IER : std_logic_vector(7 downto 0); -- Interrupt Enable Register signal IIR : std_logic_vector(7 downto 0); -- Interrupt Ident. Register signal LCR : std_logic_vector(7 downto 0); -- Line Control Register signal MCR : std_logic_vector(7 downto 0); -- MODEM Control Register signal LSR : std_logic_vector(7 downto 0); -- Line Status Register signal MSR : std_logic_vector(7 downto 0); -- MODEM Status Register signal SCR : std_logic_vector(7 downto 0); -- Scratch Register signal DLL : std_logic_vector(7 downto 0); -- Divisor Latch (LS) signal DLM : std_logic_vector(7 downto 0); -- Divisor Latch (MS) signal DM0 : std_logic_vector(7 downto 0); signal DM1 : std_logic_vector(7 downto 0); signal MSR_In : std_logic_vector(3 downto 0); signal Bit_Phase : unsigned(3 downto 0); signal Brk_Cnt : unsigned(3 downto 0); signal RX_Filtered : std_logic; signal RX_ShiftReg : std_logic_vector(7 downto 0); signal RX_Bit_Cnt : integer range 0 to 11; signal RX_Parity : std_logic; signal RXD : std_logic; signal TX_Tick : std_logic; signal TX_ShiftReg : std_logic_vector(7 downto 0); signal TX_Bit_Cnt : integer range 0 to 11; signal TX_Parity : std_logic; signal TX_Next_Is_Stop : std_logic; signal TX_Stop_Bit : std_logic; signal TXD : std_logic; begin DTR_n <= MCR(4) or not MCR(0); RTS_n <= MCR(4) or not MCR(1); OUT1_n <= MCR(4) or not MCR(2); OUT2_n <= MCR(4) or not MCR(3); SOut <= MCR(4) or (TXD and not LCR(6)); RXD <= SIn when MCR(4) = '0' else (TXD and not LCR(6)); Intr <= not IIR(0); -- Registers DM0 <= DLL when LCR(7) = '1' else RBR; DM1 <= DLM when LCR(7) = '1' else IER; with A select D_Out <= DM0 when "000", DM1 when "001", IIR when "010", LCR when "011", MCR when "100", LSR when "101", MSR when "110", SCR when others; process (MR_n, XIn) begin if MR_n = '0' then THR <= "00000000"; IER <= "00000000"; LCR <= "00000000"; MCR <= "00000000"; MSR(3 downto 0) <= "0000"; SCR <= "00000000"; -- ?? DLL <= "00000000"; -- ?? DLM <= "00000000"; -- ?? elsif XIn'event and XIn = '1' then if Wr_n = '0' and CS_n = '0' then case A is when "000" => if LCR(7) = '1' then DLL <= D_In; else THR <= D_In; end if; when "001" => if LCR(7) = '1' then DLM <= D_In; else IER(3 downto 0) <= D_In(3 downto 0); end if; when "011" => LCR <= D_In; when "100" => MCR <= D_In; when "111" => SCR <= D_In; when others => end case; end if; if Rd_n = '0' and CS_n = '0' and A = "110" then MSR(3 downto 0) <= "0000"; end if; if MSR(4) /= MSR_In(0) then MSR(0) <= '1'; end if; if MSR(5) /= MSR_In(1) then MSR(1) <= '1'; end if; if MSR(6) = '0' and MSR_In(2) = '1' then MSR(2) <= '1'; end if; if MSR(7) /= MSR_In(3) then MSR(3) <= '1'; end if; end if; end process; process (XIn) begin if XIn'event and XIn = '1' then if MCR(4) = '0' then MSR(4) <= MSR_In(0); MSR(5) <= MSR_In(1); MSR(6) <= MSR_In(2); MSR(7) <= MSR_In(3); else MSR(4) <= MCR(1); MSR(5) <= MCR(0); MSR(6) <= MCR(2); MSR(7) <= MCR(3); end if; MSR_In(0) <= CTS_n; MSR_In(1) <= DSR_n; MSR_In(2) <= RI_n; MSR_In(3) <= DCD_n; end if; end process; IIR(7 downto 3) <= "00000"; IIR(2 downto 0) <= "110" when IER(2) = '1' and LSR(4 downto 1) /= "0000" else "100" when (IER(0) and LSR(0)) = '1' else "010" when (IER(1) and LSR(5)) = '1' else "000" when IER(3) = '1' and ((MCR(4) = '0' and MSR(3 downto 0) /= "0000") or (MCR(4) = '1' and MCR(3 downto 0) /= "0000")) else "001"; -- Baud x 16 clock generator process (MR_n, XIn) variable Baud_Cnt : unsigned(15 downto 0); begin if MR_n = '0' then Baud_Cnt := "0000000000000000"; BaudOut <= '0'; elsif XIn'event and XIn = '1' then if Baud_Cnt(15 downto 1) = "000000000000000" or (Wr_n = '0' and CS_n = '0' and A(2 downto 1) = "00" and LCR(7) = '1') then Baud_Cnt(15 downto 8) := unsigned(DLM); Baud_Cnt(7 downto 0) := unsigned(DLL); BaudOut <= '1'; else Baud_Cnt := Baud_Cnt - 1; BaudOut <= '0'; end if; end if; end process; -- Input filter process (MR_n, XIn) variable Samples : std_logic_vector(1 downto 0); begin if MR_n = '0' then Samples := "11"; RX_Filtered <= '1'; elsif XIn'event and XIn = '1' then if RClk = '1' then Samples(1) := Samples(0); Samples(0) := RXD; end if; if Samples = "00" then RX_Filtered <= '0'; end if; if Samples = "11" then RX_Filtered <= '1'; end if; end if; end process; -- Receive state machine process (MR_n, XIn) begin if MR_n = '0' then RBR <= "00000000"; LSR(4 downto 0) <= "00000"; Bit_Phase <= "0000"; Brk_Cnt <= "0000"; RX_ShiftReg(7 downto 0) <= "00000000"; RX_Bit_Cnt <= 0; RX_Parity <= '0'; elsif XIn'event and XIn = '1' then if A = "000" and LCR(7) = '0' and Rd_n = '0' and CS_n = '0' then LSR(0) <= '0'; -- DR end if; if A = "101" and Rd_n = '0' and CS_n = '0' then LSR(4) <= '0'; -- BI LSR(3) <= '0'; -- FE LSR(2) <= '0'; -- PE LSR(1) <= '0'; -- OE end if; if RClk = '1' then if RX_Bit_Cnt = 0 and (RX_Filtered = '1' or Bit_Phase = "0111") then Bit_Phase <= "0000"; else Bit_Phase <= Bit_Phase + 1; end if; if Bit_Phase = "1111" then if RX_Filtered = '1' then Brk_Cnt <= "0000"; else Brk_Cnt <= Brk_Cnt + 1; end if; if Brk_Cnt = "1100" then LSR(4) <= '1'; -- BI end if; end if; if RX_Bit_Cnt = 0 then if Bit_Phase = "0111" then RX_Bit_Cnt <= RX_Bit_Cnt + 1; RX_Parity <= not LCR(4); -- EPS end if; elsif Bit_Phase = "1111" then RX_Bit_Cnt <= RX_Bit_Cnt + 1; if RX_Bit_Cnt = 10 then -- Parity stop bit RX_Bit_Cnt <= 0; LSR(0) <= '1'; -- UART Receive complete LSR(3) <= not RX_Filtered; -- Framing error elsif (RX_Bit_Cnt = 9 and LCR(1 downto 0) = "11") or (RX_Bit_Cnt = 8 and LCR(1 downto 0) = "10") or (RX_Bit_Cnt = 7 and LCR(1 downto 0) = "01") or (RX_Bit_Cnt = 6 and LCR(1 downto 0) = "00") then -- Stop bit/Parity RX_Bit_Cnt <= 0; if LCR(3) = '1' then -- PEN RX_Bit_Cnt <= 10; if LCR(5) = '1' then -- Stick parity if RX_Filtered = LCR(4) then LSR(2) <= '1'; end if; else if RX_Filtered /= RX_Parity then LSR(2) <= '1'; end if; end if; else LSR(0) <= '1'; -- UART Receive complete LSR(3) <= not RX_Filtered; -- Framing error end if; RBR <= RX_ShiftReg(7 downto 0); LSR(1) <= LSR(0); if A = "101" and Rd_n = '0' and CS_n = '0' then LSR(1) <= '0'; end if; else RX_ShiftReg(6 downto 0) <= RX_ShiftReg(7 downto 1); RX_ShiftReg(7) <= RX_Filtered; if LCR(1 downto 0) = "10" then RX_ShiftReg(7) <= '0'; RX_ShiftReg(6) <= RX_Filtered; end if; if LCR(1 downto 0) = "01" then RX_ShiftReg(7) <= '0'; RX_ShiftReg(6) <= '0'; RX_ShiftReg(5) <= RX_Filtered; end if; if LCR(1 downto 0) = "00" then RX_ShiftReg(7) <= '0'; RX_ShiftReg(6) <= '0'; RX_ShiftReg(5) <= '0'; RX_ShiftReg(4) <= RX_Filtered; end if; RX_Parity <= RX_Filtered xor RX_Parity; end if; end if; end if; end if; end process; -- Transmit bit tick process (MR_n, XIn) variable TX_Cnt : unsigned(4 downto 0); begin if MR_n = '0' then TX_Cnt := "00000"; TX_Tick <= '0'; elsif XIn'event and XIn = '1' then TX_Tick <= '0'; if RClk = '1' then TX_Cnt := TX_Cnt + 1; if LCR(2) = '1' and TX_Stop_Bit = '1' then if LCR(1 downto 0) = "00" then if TX_Cnt = "10111" then TX_Tick <= '1'; TX_Cnt(3 downto 0) := "0000"; end if; else if TX_Cnt = "11111" then TX_Tick <= '1'; TX_Cnt(3 downto 0) := "0000"; end if; end if; else TX_Cnt(4) := '1'; if TX_Cnt(3 downto 0) = "1111" then TX_Tick <= '1'; end if; end if; end if; end if; end process; -- Transmit state machine process (MR_n, XIn) begin if MR_n = '0' then LSR(7 downto 5) <= "011"; TX_Bit_Cnt <= 0; TX_ShiftReg <= (others => '0'); TXD <= '1'; TX_Parity <= '0'; TX_Next_Is_Stop <= '0'; TX_Stop_Bit <= '0'; elsif XIn'event and XIn = '1' then if TX_Tick = '1' then TX_Next_Is_Stop <= '0'; TX_Stop_Bit <= TX_Next_Is_Stop; case TX_Bit_Cnt is when 0 => if LSR(5) <= '0' then -- THRE TX_Bit_Cnt <= 1; end if; TXD <= '1'; when 1 => -- Start bit TX_ShiftReg(7 downto 0) <= THR; LSR(5) <= '1'; -- THRE TXD <= '0'; TX_Parity <= not LCR(4); -- EPS TX_Bit_Cnt <= TX_Bit_Cnt + 1; when 10 => -- Parity bit TXD <= TX_Parity; if LCR(5) = '1' then -- Stick parity TXD <= not LCR(4); end if; TX_Bit_Cnt <= 0; TX_Next_Is_Stop <= '1'; when others => TX_Bit_Cnt <= TX_Bit_Cnt + 1; if (TX_Bit_Cnt = 9 and LCR(1 downto 0) = "11") or (TX_Bit_Cnt = 8 and LCR(1 downto 0) = "10") or (TX_Bit_Cnt = 7 and LCR(1 downto 0) = "01") or (TX_Bit_Cnt = 6 and LCR(1 downto 0) = "00") then TX_Bit_Cnt <= 0; if LCR(3) = '1' then -- PEN TX_Bit_Cnt <= 10; else TX_Next_Is_Stop <= '1'; end if; LSR(6) <= '1'; -- TEMT end if; TXD <= TX_ShiftReg(0); TX_ShiftReg(6 downto 0) <= TX_ShiftReg(7 downto 1); TX_Parity <= TX_ShiftReg(0) xor TX_Parity; end case; end if; if Wr_n = '0' and CS_n = '0' and A = "000" and LCR(7) = '0' then LSR(5) <= '0'; -- THRE LSR(6) <= '0'; -- TEMT end if; end if; end process; end;
zx-simi
trunk/fpga/t80/trunk/rtl/vhdl/T16450.vhd
VHDL
oos
13,027
-- -- Z80 compatible microprocessor core -- -- Version : 0242 -- -- Copyright (c) 2001-2002 Daniel Wallner (jesus@opencores.org) -- -- All rights reserved -- -- Redistribution and use in source and synthezised 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 synthesized 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 author nor the names of other 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 AUTHOR 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. -- -- Please report bugs to the author, but before you do so, please -- make sure that this is not a derivative work and that -- you have the latest version of this file. -- -- The latest version of this file can be found at: -- http://www.opencores.org/cvsweb.shtml/t80/ -- -- Limitations : -- -- File history : -- -- 0208 : First complete release -- -- 0211 : Fixed IM 1 -- -- 0214 : Fixed mostly flags, only the block instructions now fail the zex regression test -- -- 0235 : Added IM 2 fix by Mike Johnson -- -- 0238 : Added NoRead signal -- -- 0238b: Fixed instruction timing for POP and DJNZ -- -- 0240 : Added (IX/IY+d) states, removed op-codes from mode 2 and added all remaining mode 3 op-codes -- -- 0242 : Fixed I/O instruction timing, cleanup -- library IEEE; use IEEE.std_logic_1164.all; use IEEE.numeric_std.all; entity T80_MCode is generic( Mode : integer := 0; Flag_C : integer := 0; Flag_N : integer := 1; Flag_P : integer := 2; Flag_X : integer := 3; Flag_H : integer := 4; Flag_Y : integer := 5; Flag_Z : integer := 6; Flag_S : integer := 7 ); port( IR : in std_logic_vector(7 downto 0); ISet : in std_logic_vector(1 downto 0); MCycle : in std_logic_vector(2 downto 0); F : in std_logic_vector(7 downto 0); NMICycle : in std_logic; IntCycle : in std_logic; MCycles : out std_logic_vector(2 downto 0); TStates : out std_logic_vector(2 downto 0); Prefix : out std_logic_vector(1 downto 0); -- None,BC,ED,DD/FD Inc_PC : out std_logic; Inc_WZ : out std_logic; IncDec_16 : out std_logic_vector(3 downto 0); -- BC,DE,HL,SP 0 is inc Read_To_Reg : out std_logic; Read_To_Acc : out std_logic; Set_BusA_To : out std_logic_vector(3 downto 0); -- B,C,D,E,H,L,DI/DB,A,SP(L),SP(M),0,F Set_BusB_To : out std_logic_vector(3 downto 0); -- B,C,D,E,H,L,DI,A,SP(L),SP(M),1,F,PC(L),PC(M),0 ALU_Op : out std_logic_vector(3 downto 0); -- ADD, ADC, SUB, SBC, AND, XOR, OR, CP, ROT, BIT, SET, RES, DAA, RLD, RRD, None Save_ALU : out std_logic; PreserveC : out std_logic; Arith16 : out std_logic; Set_Addr_To : out std_logic_vector(2 downto 0); -- aNone,aXY,aIOA,aSP,aBC,aDE,aZI IORQ : out std_logic; Jump : out std_logic; JumpE : out std_logic; JumpXY : out std_logic; Call : out std_logic; RstP : out std_logic; LDZ : out std_logic; LDW : out std_logic; LDSPHL : out std_logic; Special_LD : out std_logic_vector(2 downto 0); -- A,I;A,R;I,A;R,A;None ExchangeDH : out std_logic; ExchangeRp : out std_logic; ExchangeAF : out std_logic; ExchangeRS : out std_logic; I_DJNZ : out std_logic; I_CPL : out std_logic; I_CCF : out std_logic; I_SCF : out std_logic; I_RETN : out std_logic; I_BT : out std_logic; I_BC : out std_logic; I_BTR : out std_logic; I_RLD : out std_logic; I_RRD : out std_logic; I_INRC : out std_logic; SetDI : out std_logic; SetEI : out std_logic; IMode : out std_logic_vector(1 downto 0); Halt : out std_logic; NoRead : out std_logic; Write : out std_logic ); end T80_MCode; architecture rtl of T80_MCode is constant aNone : std_logic_vector(2 downto 0) := "111"; constant aBC : std_logic_vector(2 downto 0) := "000"; constant aDE : std_logic_vector(2 downto 0) := "001"; constant aXY : std_logic_vector(2 downto 0) := "010"; constant aIOA : std_logic_vector(2 downto 0) := "100"; constant aSP : std_logic_vector(2 downto 0) := "101"; constant aZI : std_logic_vector(2 downto 0) := "110"; -- constant aNone : std_logic_vector(2 downto 0) := "000"; -- constant aXY : std_logic_vector(2 downto 0) := "001"; -- constant aIOA : std_logic_vector(2 downto 0) := "010"; -- constant aSP : std_logic_vector(2 downto 0) := "011"; -- constant aBC : std_logic_vector(2 downto 0) := "100"; -- constant aDE : std_logic_vector(2 downto 0) := "101"; -- constant aZI : std_logic_vector(2 downto 0) := "110"; function is_cc_true( F : std_logic_vector(7 downto 0); cc : bit_vector(2 downto 0) ) return boolean is begin if Mode = 3 then case cc is when "000" => return F(7) = '0'; -- NZ when "001" => return F(7) = '1'; -- Z when "010" => return F(4) = '0'; -- NC when "011" => return F(4) = '1'; -- C when "100" => return false; when "101" => return false; when "110" => return false; when "111" => return false; end case; else case cc is when "000" => return F(6) = '0'; -- NZ when "001" => return F(6) = '1'; -- Z when "010" => return F(0) = '0'; -- NC when "011" => return F(0) = '1'; -- C when "100" => return F(2) = '0'; -- PO when "101" => return F(2) = '1'; -- PE when "110" => return F(7) = '0'; -- P when "111" => return F(7) = '1'; -- M end case; end if; end; begin process (IR, ISet, MCycle, F, NMICycle, IntCycle) variable DDD : std_logic_vector(2 downto 0); variable SSS : std_logic_vector(2 downto 0); variable DPair : std_logic_vector(1 downto 0); variable IRB : bit_vector(7 downto 0); begin DDD := IR(5 downto 3); SSS := IR(2 downto 0); DPair := IR(5 downto 4); IRB := to_bitvector(IR); MCycles <= "001"; if MCycle = "001" then TStates <= "100"; else TStates <= "011"; end if; Prefix <= "00"; Inc_PC <= '0'; Inc_WZ <= '0'; IncDec_16 <= "0000"; Read_To_Acc <= '0'; Read_To_Reg <= '0'; Set_BusB_To <= "0000"; Set_BusA_To <= "0000"; ALU_Op <= "0" & IR(5 downto 3); Save_ALU <= '0'; PreserveC <= '0'; Arith16 <= '0'; IORQ <= '0'; Set_Addr_To <= aNone; Jump <= '0'; JumpE <= '0'; JumpXY <= '0'; Call <= '0'; RstP <= '0'; LDZ <= '0'; LDW <= '0'; LDSPHL <= '0'; Special_LD <= "000"; ExchangeDH <= '0'; ExchangeRp <= '0'; ExchangeAF <= '0'; ExchangeRS <= '0'; I_DJNZ <= '0'; I_CPL <= '0'; I_CCF <= '0'; I_SCF <= '0'; I_RETN <= '0'; I_BT <= '0'; I_BC <= '0'; I_BTR <= '0'; I_RLD <= '0'; I_RRD <= '0'; I_INRC <= '0'; SetDI <= '0'; SetEI <= '0'; IMode <= "11"; Halt <= '0'; NoRead <= '0'; Write <= '0'; case ISet is when "00" => ------------------------------------------------------------------------------ -- -- Unprefixed instructions -- ------------------------------------------------------------------------------ case IRB is -- 8 BIT LOAD GROUP when "01000000"|"01000001"|"01000010"|"01000011"|"01000100"|"01000101"|"01000111" |"01001000"|"01001001"|"01001010"|"01001011"|"01001100"|"01001101"|"01001111" |"01010000"|"01010001"|"01010010"|"01010011"|"01010100"|"01010101"|"01010111" |"01011000"|"01011001"|"01011010"|"01011011"|"01011100"|"01011101"|"01011111" |"01100000"|"01100001"|"01100010"|"01100011"|"01100100"|"01100101"|"01100111" |"01101000"|"01101001"|"01101010"|"01101011"|"01101100"|"01101101"|"01101111" |"01111000"|"01111001"|"01111010"|"01111011"|"01111100"|"01111101"|"01111111" => -- LD r,r' Set_BusB_To(2 downto 0) <= SSS; ExchangeRp <= '1'; Set_BusA_To(2 downto 0) <= DDD; Read_To_Reg <= '1'; when "00000110"|"00001110"|"00010110"|"00011110"|"00100110"|"00101110"|"00111110" => -- LD r,n MCycles <= "010"; case to_integer(unsigned(MCycle)) is when 2 => Inc_PC <= '1'; Set_BusA_To(2 downto 0) <= DDD; Read_To_Reg <= '1'; when others => null; end case; when "01000110"|"01001110"|"01010110"|"01011110"|"01100110"|"01101110"|"01111110" => -- LD r,(HL) MCycles <= "010"; case to_integer(unsigned(MCycle)) is when 1 => Set_Addr_To <= aXY; when 2 => Set_BusA_To(2 downto 0) <= DDD; Read_To_Reg <= '1'; when others => null; end case; when "01110000"|"01110001"|"01110010"|"01110011"|"01110100"|"01110101"|"01110111" => -- LD (HL),r MCycles <= "010"; case to_integer(unsigned(MCycle)) is when 1 => Set_Addr_To <= aXY; Set_BusB_To(2 downto 0) <= SSS; Set_BusB_To(3) <= '0'; when 2 => Write <= '1'; when others => null; end case; when "00110110" => -- LD (HL),n MCycles <= "011"; case to_integer(unsigned(MCycle)) is when 2 => Inc_PC <= '1'; Set_Addr_To <= aXY; Set_BusB_To(2 downto 0) <= SSS; Set_BusB_To(3) <= '0'; when 3 => Write <= '1'; when others => null; end case; when "00001010" => -- LD A,(BC) MCycles <= "010"; case to_integer(unsigned(MCycle)) is when 1 => Set_Addr_To <= aBC; when 2 => Read_To_Acc <= '1'; when others => null; end case; when "00011010" => -- LD A,(DE) MCycles <= "010"; case to_integer(unsigned(MCycle)) is when 1 => Set_Addr_To <= aDE; when 2 => Read_To_Acc <= '1'; when others => null; end case; when "00111010" => if Mode = 3 then -- LDD A,(HL) MCycles <= "010"; case to_integer(unsigned(MCycle)) is when 1 => Set_Addr_To <= aXY; when 2 => Read_To_Acc <= '1'; IncDec_16 <= "1110"; when others => null; end case; else -- LD A,(nn) MCycles <= "100"; case to_integer(unsigned(MCycle)) is when 2 => Inc_PC <= '1'; LDZ <= '1'; when 3 => Set_Addr_To <= aZI; Inc_PC <= '1'; when 4 => Read_To_Acc <= '1'; when others => null; end case; end if; when "00000010" => -- LD (BC),A MCycles <= "010"; case to_integer(unsigned(MCycle)) is when 1 => Set_Addr_To <= aBC; Set_BusB_To <= "0111"; when 2 => Write <= '1'; when others => null; end case; when "00010010" => -- LD (DE),A MCycles <= "010"; case to_integer(unsigned(MCycle)) is when 1 => Set_Addr_To <= aDE; Set_BusB_To <= "0111"; when 2 => Write <= '1'; when others => null; end case; when "00110010" => if Mode = 3 then -- LDD (HL),A MCycles <= "010"; case to_integer(unsigned(MCycle)) is when 1 => Set_Addr_To <= aXY; Set_BusB_To <= "0111"; when 2 => Write <= '1'; IncDec_16 <= "1110"; when others => null; end case; else -- LD (nn),A MCycles <= "100"; case to_integer(unsigned(MCycle)) is when 2 => Inc_PC <= '1'; LDZ <= '1'; when 3 => Set_Addr_To <= aZI; Inc_PC <= '1'; Set_BusB_To <= "0111"; when 4 => Write <= '1'; when others => null; end case; end if; -- 16 BIT LOAD GROUP when "00000001"|"00010001"|"00100001"|"00110001" => -- LD dd,nn MCycles <= "011"; case to_integer(unsigned(MCycle)) is when 2 => Inc_PC <= '1'; Read_To_Reg <= '1'; if DPAIR = "11" then Set_BusA_To(3 downto 0) <= "1000"; else Set_BusA_To(2 downto 1) <= DPAIR; Set_BusA_To(0) <= '1'; end if; when 3 => Inc_PC <= '1'; Read_To_Reg <= '1'; if DPAIR = "11" then Set_BusA_To(3 downto 0) <= "1001"; else Set_BusA_To(2 downto 1) <= DPAIR; Set_BusA_To(0) <= '0'; end if; when others => null; end case; when "00101010" => if Mode = 3 then -- LDI A,(HL) MCycles <= "010"; case to_integer(unsigned(MCycle)) is when 1 => Set_Addr_To <= aXY; when 2 => Read_To_Acc <= '1'; IncDec_16 <= "0110"; when others => null; end case; else -- LD HL,(nn) MCycles <= "101"; case to_integer(unsigned(MCycle)) is when 2 => Inc_PC <= '1'; LDZ <= '1'; when 3 => Set_Addr_To <= aZI; Inc_PC <= '1'; LDW <= '1'; when 4 => Set_BusA_To(2 downto 0) <= "101"; -- L Read_To_Reg <= '1'; Inc_WZ <= '1'; Set_Addr_To <= aZI; when 5 => Set_BusA_To(2 downto 0) <= "100"; -- H Read_To_Reg <= '1'; when others => null; end case; end if; when "00100010" => if Mode = 3 then -- LDI (HL),A MCycles <= "010"; case to_integer(unsigned(MCycle)) is when 1 => Set_Addr_To <= aXY; Set_BusB_To <= "0111"; when 2 => Write <= '1'; IncDec_16 <= "0110"; when others => null; end case; else -- LD (nn),HL MCycles <= "101"; case to_integer(unsigned(MCycle)) is when 2 => Inc_PC <= '1'; LDZ <= '1'; when 3 => Set_Addr_To <= aZI; Inc_PC <= '1'; LDW <= '1'; Set_BusB_To <= "0101"; -- L when 4 => Inc_WZ <= '1'; Set_Addr_To <= aZI; Write <= '1'; Set_BusB_To <= "0100"; -- H when 5 => Write <= '1'; when others => null; end case; end if; when "11111001" => -- LD SP,HL TStates <= "110"; LDSPHL <= '1'; when "11000101"|"11010101"|"11100101"|"11110101" => -- PUSH qq MCycles <= "011"; case to_integer(unsigned(MCycle)) is when 1 => TStates <= "101"; IncDec_16 <= "1111"; Set_Addr_TO <= aSP; if DPAIR = "11" then Set_BusB_To <= "0111"; else Set_BusB_To(2 downto 1) <= DPAIR; Set_BusB_To(0) <= '0'; Set_BusB_To(3) <= '0'; end if; when 2 => IncDec_16 <= "1111"; Set_Addr_To <= aSP; if DPAIR = "11" then Set_BusB_To <= "1011"; else Set_BusB_To(2 downto 1) <= DPAIR; Set_BusB_To(0) <= '1'; Set_BusB_To(3) <= '0'; end if; Write <= '1'; when 3 => Write <= '1'; when others => null; end case; when "11000001"|"11010001"|"11100001"|"11110001" => -- POP qq MCycles <= "011"; case to_integer(unsigned(MCycle)) is when 1 => Set_Addr_To <= aSP; when 2 => IncDec_16 <= "0111"; Set_Addr_To <= aSP; Read_To_Reg <= '1'; if DPAIR = "11" then Set_BusA_To(3 downto 0) <= "1011"; else Set_BusA_To(2 downto 1) <= DPAIR; Set_BusA_To(0) <= '1'; end if; when 3 => IncDec_16 <= "0111"; Read_To_Reg <= '1'; if DPAIR = "11" then Set_BusA_To(3 downto 0) <= "0111"; else Set_BusA_To(2 downto 1) <= DPAIR; Set_BusA_To(0) <= '0'; end if; when others => null; end case; -- EXCHANGE, BLOCK TRANSFER AND SEARCH GROUP when "11101011" => if Mode /= 3 then -- EX DE,HL ExchangeDH <= '1'; end if; when "00001000" => if Mode = 3 then -- LD (nn),SP MCycles <= "101"; case to_integer(unsigned(MCycle)) is when 2 => Inc_PC <= '1'; LDZ <= '1'; when 3 => Set_Addr_To <= aZI; Inc_PC <= '1'; LDW <= '1'; Set_BusB_To <= "1000"; when 4 => Inc_WZ <= '1'; Set_Addr_To <= aZI; Write <= '1'; Set_BusB_To <= "1001"; when 5 => Write <= '1'; when others => null; end case; elsif Mode < 2 then -- EX AF,AF' ExchangeAF <= '1'; end if; when "11011001" => if Mode = 3 then -- RETI MCycles <= "011"; case to_integer(unsigned(MCycle)) is when 1 => Set_Addr_TO <= aSP; when 2 => IncDec_16 <= "0111"; Set_Addr_To <= aSP; LDZ <= '1'; when 3 => Jump <= '1'; IncDec_16 <= "0111"; I_RETN <= '1'; SetEI <= '1'; when others => null; end case; elsif Mode < 2 then -- EXX ExchangeRS <= '1'; end if; when "11100011" => if Mode /= 3 then -- EX (SP),HL MCycles <= "101"; case to_integer(unsigned(MCycle)) is when 1 => Set_Addr_To <= aSP; when 2 => Read_To_Reg <= '1'; Set_BusA_To <= "0101"; Set_BusB_To <= "0101"; Set_Addr_To <= aSP; when 3 => IncDec_16 <= "0111"; Set_Addr_To <= aSP; TStates <= "100"; Write <= '1'; when 4 => Read_To_Reg <= '1'; Set_BusA_To <= "0100"; Set_BusB_To <= "0100"; Set_Addr_To <= aSP; when 5 => IncDec_16 <= "1111"; TStates <= "101"; Write <= '1'; when others => null; end case; end if; -- 8 BIT ARITHMETIC AND LOGICAL GROUP when "10000000"|"10000001"|"10000010"|"10000011"|"10000100"|"10000101"|"10000111" |"10001000"|"10001001"|"10001010"|"10001011"|"10001100"|"10001101"|"10001111" |"10010000"|"10010001"|"10010010"|"10010011"|"10010100"|"10010101"|"10010111" |"10011000"|"10011001"|"10011010"|"10011011"|"10011100"|"10011101"|"10011111" |"10100000"|"10100001"|"10100010"|"10100011"|"10100100"|"10100101"|"10100111" |"10101000"|"10101001"|"10101010"|"10101011"|"10101100"|"10101101"|"10101111" |"10110000"|"10110001"|"10110010"|"10110011"|"10110100"|"10110101"|"10110111" |"10111000"|"10111001"|"10111010"|"10111011"|"10111100"|"10111101"|"10111111" => -- ADD A,r -- ADC A,r -- SUB A,r -- SBC A,r -- AND A,r -- OR A,r -- XOR A,r -- CP A,r Set_BusB_To(2 downto 0) <= SSS; Set_BusA_To(2 downto 0) <= "111"; Read_To_Reg <= '1'; Save_ALU <= '1'; when "10000110"|"10001110"|"10010110"|"10011110"|"10100110"|"10101110"|"10110110"|"10111110" => -- ADD A,(HL) -- ADC A,(HL) -- SUB A,(HL) -- SBC A,(HL) -- AND A,(HL) -- OR A,(HL) -- XOR A,(HL) -- CP A,(HL) MCycles <= "010"; case to_integer(unsigned(MCycle)) is when 1 => Set_Addr_To <= aXY; when 2 => Read_To_Reg <= '1'; Save_ALU <= '1'; Set_BusB_To(2 downto 0) <= SSS; Set_BusA_To(2 downto 0) <= "111"; when others => null; end case; when "11000110"|"11001110"|"11010110"|"11011110"|"11100110"|"11101110"|"11110110"|"11111110" => -- ADD A,n -- ADC A,n -- SUB A,n -- SBC A,n -- AND A,n -- OR A,n -- XOR A,n -- CP A,n MCycles <= "010"; if MCycle = "010" then Inc_PC <= '1'; Read_To_Reg <= '1'; Save_ALU <= '1'; Set_BusB_To(2 downto 0) <= SSS; Set_BusA_To(2 downto 0) <= "111"; end if; when "00000100"|"00001100"|"00010100"|"00011100"|"00100100"|"00101100"|"00111100" => -- INC r Set_BusB_To <= "1010"; Set_BusA_To(2 downto 0) <= DDD; Read_To_Reg <= '1'; Save_ALU <= '1'; PreserveC <= '1'; ALU_Op <= "0000"; when "00110100" => -- INC (HL) MCycles <= "011"; case to_integer(unsigned(MCycle)) is when 1 => Set_Addr_To <= aXY; when 2 => TStates <= "100"; Set_Addr_To <= aXY; Read_To_Reg <= '1'; Save_ALU <= '1'; PreserveC <= '1'; ALU_Op <= "0000"; Set_BusB_To <= "1010"; Set_BusA_To(2 downto 0) <= DDD; when 3 => Write <= '1'; when others => null; end case; when "00000101"|"00001101"|"00010101"|"00011101"|"00100101"|"00101101"|"00111101" => -- DEC r Set_BusB_To <= "1010"; Set_BusA_To(2 downto 0) <= DDD; Read_To_Reg <= '1'; Save_ALU <= '1'; PreserveC <= '1'; ALU_Op <= "0010"; when "00110101" => -- DEC (HL) MCycles <= "011"; case to_integer(unsigned(MCycle)) is when 1 => Set_Addr_To <= aXY; when 2 => TStates <= "100"; Set_Addr_To <= aXY; ALU_Op <= "0010"; Read_To_Reg <= '1'; Save_ALU <= '1'; PreserveC <= '1'; Set_BusB_To <= "1010"; Set_BusA_To(2 downto 0) <= DDD; when 3 => Write <= '1'; when others => null; end case; -- GENERAL PURPOSE ARITHMETIC AND CPU CONTROL GROUPS when "00100111" => -- DAA Set_BusA_To(2 downto 0) <= "111"; Read_To_Reg <= '1'; ALU_Op <= "1100"; Save_ALU <= '1'; when "00101111" => -- CPL I_CPL <= '1'; when "00111111" => -- CCF I_CCF <= '1'; when "00110111" => -- SCF I_SCF <= '1'; when "00000000" => if NMICycle = '1' then -- NMI MCycles <= "011"; case to_integer(unsigned(MCycle)) is when 1 => TStates <= "101"; IncDec_16 <= "1111"; Set_Addr_To <= aSP; Set_BusB_To <= "1101"; when 2 => TStates <= "100"; Write <= '1'; IncDec_16 <= "1111"; Set_Addr_To <= aSP; Set_BusB_To <= "1100"; when 3 => TStates <= "100"; Write <= '1'; when others => null; end case; elsif IntCycle = '1' then -- INT (IM 2) MCycles <= "101"; case to_integer(unsigned(MCycle)) is when 1 => LDZ <= '1'; TStates <= "101"; IncDec_16 <= "1111"; Set_Addr_To <= aSP; Set_BusB_To <= "1101"; when 2 => TStates <= "100"; Write <= '1'; IncDec_16 <= "1111"; Set_Addr_To <= aSP; Set_BusB_To <= "1100"; when 3 => TStates <= "100"; Write <= '1'; when 4 => Inc_PC <= '1'; LDZ <= '1'; when 5 => Jump <= '1'; when others => null; end case; else -- NOP end if; when "01110110" => -- HALT Halt <= '1'; when "11110011" => -- DI SetDI <= '1'; when "11111011" => -- EI SetEI <= '1'; -- 16 BIT ARITHMETIC GROUP when "00001001"|"00011001"|"00101001"|"00111001" => -- ADD HL,ss MCycles <= "011"; case to_integer(unsigned(MCycle)) is when 2 => NoRead <= '1'; ALU_Op <= "0000"; Read_To_Reg <= '1'; Save_ALU <= '1'; Set_BusA_To(2 downto 0) <= "101"; case to_integer(unsigned(IR(5 downto 4))) is when 0|1|2 => Set_BusB_To(2 downto 1) <= IR(5 downto 4); Set_BusB_To(0) <= '1'; when others => Set_BusB_To <= "1000"; end case; TStates <= "100"; Arith16 <= '1'; when 3 => NoRead <= '1'; Read_To_Reg <= '1'; Save_ALU <= '1'; ALU_Op <= "0001"; Set_BusA_To(2 downto 0) <= "100"; case to_integer(unsigned(IR(5 downto 4))) is when 0|1|2 => Set_BusB_To(2 downto 1) <= IR(5 downto 4); when others => Set_BusB_To <= "1001"; end case; Arith16 <= '1'; when others => end case; when "00000011"|"00010011"|"00100011"|"00110011" => -- INC ss TStates <= "110"; IncDec_16(3 downto 2) <= "01"; IncDec_16(1 downto 0) <= DPair; when "00001011"|"00011011"|"00101011"|"00111011" => -- DEC ss TStates <= "110"; IncDec_16(3 downto 2) <= "11"; IncDec_16(1 downto 0) <= DPair; -- ROTATE AND SHIFT GROUP when "00000111" -- RLCA |"00010111" -- RLA |"00001111" -- RRCA |"00011111" => -- RRA Set_BusA_To(2 downto 0) <= "111"; ALU_Op <= "1000"; Read_To_Reg <= '1'; Save_ALU <= '1'; -- JUMP GROUP when "11000011" => -- JP nn MCycles <= "011"; case to_integer(unsigned(MCycle)) is when 2 => Inc_PC <= '1'; LDZ <= '1'; when 3 => Inc_PC <= '1'; Jump <= '1'; when others => null; end case; when "11000010"|"11001010"|"11010010"|"11011010"|"11100010"|"11101010"|"11110010"|"11111010" => if IR(5) = '1' and Mode = 3 then case IRB(4 downto 3) is when "00" => -- LD ($FF00+C),A MCycles <= "010"; case to_integer(unsigned(MCycle)) is when 1 => Set_Addr_To <= aBC; Set_BusB_To <= "0111"; when 2 => Write <= '1'; IORQ <= '1'; when others => end case; when "01" => -- LD (nn),A MCycles <= "100"; case to_integer(unsigned(MCycle)) is when 2 => Inc_PC <= '1'; LDZ <= '1'; when 3 => Set_Addr_To <= aZI; Inc_PC <= '1'; Set_BusB_To <= "0111"; when 4 => Write <= '1'; when others => null; end case; when "10" => -- LD A,($FF00+C) MCycles <= "010"; case to_integer(unsigned(MCycle)) is when 1 => Set_Addr_To <= aBC; when 2 => Read_To_Acc <= '1'; IORQ <= '1'; when others => end case; when "11" => -- LD A,(nn) MCycles <= "100"; case to_integer(unsigned(MCycle)) is when 2 => Inc_PC <= '1'; LDZ <= '1'; when 3 => Set_Addr_To <= aZI; Inc_PC <= '1'; when 4 => Read_To_Acc <= '1'; when others => null; end case; end case; else -- JP cc,nn MCycles <= "011"; case to_integer(unsigned(MCycle)) is when 2 => Inc_PC <= '1'; LDZ <= '1'; when 3 => Inc_PC <= '1'; if is_cc_true(F, to_bitvector(IR(5 downto 3))) then Jump <= '1'; end if; when others => null; end case; end if; when "00011000" => if Mode /= 2 then -- JR e MCycles <= "011"; case to_integer(unsigned(MCycle)) is when 2 => Inc_PC <= '1'; when 3 => NoRead <= '1'; JumpE <= '1'; TStates <= "101"; when others => null; end case; end if; when "00111000" => if Mode /= 2 then -- JR C,e MCycles <= "011"; case to_integer(unsigned(MCycle)) is when 2 => Inc_PC <= '1'; if F(Flag_C) = '0' then MCycles <= "010"; end if; when 3 => NoRead <= '1'; JumpE <= '1'; TStates <= "101"; when others => null; end case; end if; when "00110000" => if Mode /= 2 then -- JR NC,e MCycles <= "011"; case to_integer(unsigned(MCycle)) is when 2 => Inc_PC <= '1'; if F(Flag_C) = '1' then MCycles <= "010"; end if; when 3 => NoRead <= '1'; JumpE <= '1'; TStates <= "101"; when others => null; end case; end if; when "00101000" => if Mode /= 2 then -- JR Z,e MCycles <= "011"; case to_integer(unsigned(MCycle)) is when 2 => Inc_PC <= '1'; if F(Flag_Z) = '0' then MCycles <= "010"; end if; when 3 => NoRead <= '1'; JumpE <= '1'; TStates <= "101"; when others => null; end case; end if; when "00100000" => if Mode /= 2 then -- JR NZ,e MCycles <= "011"; case to_integer(unsigned(MCycle)) is when 2 => Inc_PC <= '1'; if F(Flag_Z) = '1' then MCycles <= "010"; end if; when 3 => NoRead <= '1'; JumpE <= '1'; TStates <= "101"; when others => null; end case; end if; when "11101001" => -- JP (HL) JumpXY <= '1'; when "00010000" => if Mode = 3 then I_DJNZ <= '1'; elsif Mode < 2 then -- DJNZ,e MCycles <= "011"; case to_integer(unsigned(MCycle)) is when 1 => TStates <= "101"; I_DJNZ <= '1'; Set_BusB_To <= "1010"; Set_BusA_To(2 downto 0) <= "000"; Read_To_Reg <= '1'; Save_ALU <= '1'; ALU_Op <= "0010"; when 2 => I_DJNZ <= '1'; Inc_PC <= '1'; when 3 => NoRead <= '1'; JumpE <= '1'; TStates <= "101"; when others => null; end case; end if; -- CALL AND RETURN GROUP when "11001101" => -- CALL nn MCycles <= "101"; case to_integer(unsigned(MCycle)) is when 2 => Inc_PC <= '1'; LDZ <= '1'; when 3 => IncDec_16 <= "1111"; Inc_PC <= '1'; TStates <= "100"; Set_Addr_To <= aSP; LDW <= '1'; Set_BusB_To <= "1101"; when 4 => Write <= '1'; IncDec_16 <= "1111"; Set_Addr_To <= aSP; Set_BusB_To <= "1100"; when 5 => Write <= '1'; Call <= '1'; when others => null; end case; when "11000100"|"11001100"|"11010100"|"11011100"|"11100100"|"11101100"|"11110100"|"11111100" => if IR(5) = '0' or Mode /= 3 then -- CALL cc,nn MCycles <= "101"; case to_integer(unsigned(MCycle)) is when 2 => Inc_PC <= '1'; LDZ <= '1'; when 3 => Inc_PC <= '1'; LDW <= '1'; if is_cc_true(F, to_bitvector(IR(5 downto 3))) then IncDec_16 <= "1111"; Set_Addr_TO <= aSP; TStates <= "100"; Set_BusB_To <= "1101"; else MCycles <= "011"; end if; when 4 => Write <= '1'; IncDec_16 <= "1111"; Set_Addr_To <= aSP; Set_BusB_To <= "1100"; when 5 => Write <= '1'; Call <= '1'; when others => null; end case; end if; when "11001001" => -- RET MCycles <= "011"; case to_integer(unsigned(MCycle)) is when 1 => TStates <= "101"; Set_Addr_TO <= aSP; when 2 => IncDec_16 <= "0111"; Set_Addr_To <= aSP; LDZ <= '1'; when 3 => Jump <= '1'; IncDec_16 <= "0111"; when others => null; end case; when "11000000"|"11001000"|"11010000"|"11011000"|"11100000"|"11101000"|"11110000"|"11111000" => if IR(5) = '1' and Mode = 3 then case IRB(4 downto 3) is when "00" => -- LD ($FF00+nn),A MCycles <= "011"; case to_integer(unsigned(MCycle)) is when 2 => Inc_PC <= '1'; Set_Addr_To <= aIOA; Set_BusB_To <= "0111"; when 3 => Write <= '1'; when others => null; end case; when "01" => -- ADD SP,n MCycles <= "011"; case to_integer(unsigned(MCycle)) is when 2 => ALU_Op <= "0000"; Inc_PC <= '1'; Read_To_Reg <= '1'; Save_ALU <= '1'; Set_BusA_To <= "1000"; Set_BusB_To <= "0110"; when 3 => NoRead <= '1'; Read_To_Reg <= '1'; Save_ALU <= '1'; ALU_Op <= "0001"; Set_BusA_To <= "1001"; Set_BusB_To <= "1110"; -- Incorrect unsigned !!!!!!!!!!!!!!!!!!!!! when others => end case; when "10" => -- LD A,($FF00+nn) MCycles <= "011"; case to_integer(unsigned(MCycle)) is when 2 => Inc_PC <= '1'; Set_Addr_To <= aIOA; when 3 => Read_To_Acc <= '1'; when others => null; end case; when "11" => -- LD HL,SP+n -- Not correct !!!!!!!!!!!!!!!!!!! MCycles <= "101"; case to_integer(unsigned(MCycle)) is when 2 => Inc_PC <= '1'; LDZ <= '1'; when 3 => Set_Addr_To <= aZI; Inc_PC <= '1'; LDW <= '1'; when 4 => Set_BusA_To(2 downto 0) <= "101"; -- L Read_To_Reg <= '1'; Inc_WZ <= '1'; Set_Addr_To <= aZI; when 5 => Set_BusA_To(2 downto 0) <= "100"; -- H Read_To_Reg <= '1'; when others => null; end case; end case; else -- RET cc MCycles <= "011"; case to_integer(unsigned(MCycle)) is when 1 => if is_cc_true(F, to_bitvector(IR(5 downto 3))) then Set_Addr_TO <= aSP; else MCycles <= "001"; end if; TStates <= "101"; when 2 => IncDec_16 <= "0111"; Set_Addr_To <= aSP; LDZ <= '1'; when 3 => Jump <= '1'; IncDec_16 <= "0111"; when others => null; end case; end if; when "11000111"|"11001111"|"11010111"|"11011111"|"11100111"|"11101111"|"11110111"|"11111111" => -- RST p MCycles <= "011"; case to_integer(unsigned(MCycle)) is when 1 => TStates <= "101"; IncDec_16 <= "1111"; Set_Addr_To <= aSP; Set_BusB_To <= "1101"; when 2 => Write <= '1'; IncDec_16 <= "1111"; Set_Addr_To <= aSP; Set_BusB_To <= "1100"; when 3 => Write <= '1'; RstP <= '1'; when others => null; end case; -- INPUT AND OUTPUT GROUP when "11011011" => if Mode /= 3 then -- IN A,(n) MCycles <= "011"; case to_integer(unsigned(MCycle)) is when 2 => Inc_PC <= '1'; Set_Addr_To <= aIOA; when 3 => Read_To_Acc <= '1'; IORQ <= '1'; when others => null; end case; end if; when "11010011" => if Mode /= 3 then -- OUT (n),A MCycles <= "011"; case to_integer(unsigned(MCycle)) is when 2 => Inc_PC <= '1'; Set_Addr_To <= aIOA; Set_BusB_To <= "0111"; when 3 => Write <= '1'; IORQ <= '1'; when others => null; end case; end if; ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ -- MULTIBYTE INSTRUCTIONS ------------------------------------------------------------------------------ ------------------------------------------------------------------------------ when "11001011" => if Mode /= 2 then Prefix <= "01"; end if; when "11101101" => if Mode < 2 then Prefix <= "10"; end if; when "11011101"|"11111101" => if Mode < 2 then Prefix <= "11"; end if; end case; when "01" => ------------------------------------------------------------------------------ -- -- CB prefixed instructions -- ------------------------------------------------------------------------------ Set_BusA_To(2 downto 0) <= IR(2 downto 0); Set_BusB_To(2 downto 0) <= IR(2 downto 0); case IRB is when "00000000"|"00000001"|"00000010"|"00000011"|"00000100"|"00000101"|"00000111" |"00010000"|"00010001"|"00010010"|"00010011"|"00010100"|"00010101"|"00010111" |"00001000"|"00001001"|"00001010"|"00001011"|"00001100"|"00001101"|"00001111" |"00011000"|"00011001"|"00011010"|"00011011"|"00011100"|"00011101"|"00011111" |"00100000"|"00100001"|"00100010"|"00100011"|"00100100"|"00100101"|"00100111" |"00101000"|"00101001"|"00101010"|"00101011"|"00101100"|"00101101"|"00101111" |"00110000"|"00110001"|"00110010"|"00110011"|"00110100"|"00110101"|"00110111" |"00111000"|"00111001"|"00111010"|"00111011"|"00111100"|"00111101"|"00111111" => -- RLC r -- RL r -- RRC r -- RR r -- SLA r -- SRA r -- SRL r -- SLL r (Undocumented) / SWAP r if MCycle = "001" then ALU_Op <= "1000"; Read_To_Reg <= '1'; Save_ALU <= '1'; end if; when "00000110"|"00010110"|"00001110"|"00011110"|"00101110"|"00111110"|"00100110"|"00110110" => -- RLC (HL) -- RL (HL) -- RRC (HL) -- RR (HL) -- SRA (HL) -- SRL (HL) -- SLA (HL) -- SLL (HL) (Undocumented) / SWAP (HL) MCycles <= "011"; case to_integer(unsigned(MCycle)) is when 1 | 7 => Set_Addr_To <= aXY; when 2 => ALU_Op <= "1000"; Read_To_Reg <= '1'; Save_ALU <= '1'; Set_Addr_To <= aXY; TStates <= "100"; when 3 => Write <= '1'; when others => end case; when "01000000"|"01000001"|"01000010"|"01000011"|"01000100"|"01000101"|"01000111" |"01001000"|"01001001"|"01001010"|"01001011"|"01001100"|"01001101"|"01001111" |"01010000"|"01010001"|"01010010"|"01010011"|"01010100"|"01010101"|"01010111" |"01011000"|"01011001"|"01011010"|"01011011"|"01011100"|"01011101"|"01011111" |"01100000"|"01100001"|"01100010"|"01100011"|"01100100"|"01100101"|"01100111" |"01101000"|"01101001"|"01101010"|"01101011"|"01101100"|"01101101"|"01101111" |"01110000"|"01110001"|"01110010"|"01110011"|"01110100"|"01110101"|"01110111" |"01111000"|"01111001"|"01111010"|"01111011"|"01111100"|"01111101"|"01111111" => -- BIT b,r if MCycle = "001" then Set_BusB_To(2 downto 0) <= IR(2 downto 0); ALU_Op <= "1001"; end if; when "01000110"|"01001110"|"01010110"|"01011110"|"01100110"|"01101110"|"01110110"|"01111110" => -- BIT b,(HL) MCycles <= "010"; case to_integer(unsigned(MCycle)) is when 1 | 7 => Set_Addr_To <= aXY; when 2 => ALU_Op <= "1001"; TStates <= "100"; when others => end case; when "11000000"|"11000001"|"11000010"|"11000011"|"11000100"|"11000101"|"11000111" |"11001000"|"11001001"|"11001010"|"11001011"|"11001100"|"11001101"|"11001111" |"11010000"|"11010001"|"11010010"|"11010011"|"11010100"|"11010101"|"11010111" |"11011000"|"11011001"|"11011010"|"11011011"|"11011100"|"11011101"|"11011111" |"11100000"|"11100001"|"11100010"|"11100011"|"11100100"|"11100101"|"11100111" |"11101000"|"11101001"|"11101010"|"11101011"|"11101100"|"11101101"|"11101111" |"11110000"|"11110001"|"11110010"|"11110011"|"11110100"|"11110101"|"11110111" |"11111000"|"11111001"|"11111010"|"11111011"|"11111100"|"11111101"|"11111111" => -- SET b,r if MCycle = "001" then ALU_Op <= "1010"; Read_To_Reg <= '1'; Save_ALU <= '1'; end if; when "11000110"|"11001110"|"11010110"|"11011110"|"11100110"|"11101110"|"11110110"|"11111110" => -- SET b,(HL) MCycles <= "011"; case to_integer(unsigned(MCycle)) is when 1 | 7 => Set_Addr_To <= aXY; when 2 => ALU_Op <= "1010"; Read_To_Reg <= '1'; Save_ALU <= '1'; Set_Addr_To <= aXY; TStates <= "100"; when 3 => Write <= '1'; when others => end case; when "10000000"|"10000001"|"10000010"|"10000011"|"10000100"|"10000101"|"10000111" |"10001000"|"10001001"|"10001010"|"10001011"|"10001100"|"10001101"|"10001111" |"10010000"|"10010001"|"10010010"|"10010011"|"10010100"|"10010101"|"10010111" |"10011000"|"10011001"|"10011010"|"10011011"|"10011100"|"10011101"|"10011111" |"10100000"|"10100001"|"10100010"|"10100011"|"10100100"|"10100101"|"10100111" |"10101000"|"10101001"|"10101010"|"10101011"|"10101100"|"10101101"|"10101111" |"10110000"|"10110001"|"10110010"|"10110011"|"10110100"|"10110101"|"10110111" |"10111000"|"10111001"|"10111010"|"10111011"|"10111100"|"10111101"|"10111111" => -- RES b,r if MCycle = "001" then ALU_Op <= "1011"; Read_To_Reg <= '1'; Save_ALU <= '1'; end if; when "10000110"|"10001110"|"10010110"|"10011110"|"10100110"|"10101110"|"10110110"|"10111110" => -- RES b,(HL) MCycles <= "011"; case to_integer(unsigned(MCycle)) is when 1 | 7 => Set_Addr_To <= aXY; when 2 => ALU_Op <= "1011"; Read_To_Reg <= '1'; Save_ALU <= '1'; Set_Addr_To <= aXY; TStates <= "100"; when 3 => Write <= '1'; when others => end case; end case; when others => ------------------------------------------------------------------------------ -- -- ED prefixed instructions -- ------------------------------------------------------------------------------ case IRB is when "00000000"|"00000001"|"00000010"|"00000011"|"00000100"|"00000101"|"00000110"|"00000111" |"00001000"|"00001001"|"00001010"|"00001011"|"00001100"|"00001101"|"00001110"|"00001111" |"00010000"|"00010001"|"00010010"|"00010011"|"00010100"|"00010101"|"00010110"|"00010111" |"00011000"|"00011001"|"00011010"|"00011011"|"00011100"|"00011101"|"00011110"|"00011111" |"00100000"|"00100001"|"00100010"|"00100011"|"00100100"|"00100101"|"00100110"|"00100111" |"00101000"|"00101001"|"00101010"|"00101011"|"00101100"|"00101101"|"00101110"|"00101111" |"00110000"|"00110001"|"00110010"|"00110011"|"00110100"|"00110101"|"00110110"|"00110111" |"00111000"|"00111001"|"00111010"|"00111011"|"00111100"|"00111101"|"00111110"|"00111111" |"10000000"|"10000001"|"10000010"|"10000011"|"10000100"|"10000101"|"10000110"|"10000111" |"10001000"|"10001001"|"10001010"|"10001011"|"10001100"|"10001101"|"10001110"|"10001111" |"10010000"|"10010001"|"10010010"|"10010011"|"10010100"|"10010101"|"10010110"|"10010111" |"10011000"|"10011001"|"10011010"|"10011011"|"10011100"|"10011101"|"10011110"|"10011111" | "10100100"|"10100101"|"10100110"|"10100111" | "10101100"|"10101101"|"10101110"|"10101111" | "10110100"|"10110101"|"10110110"|"10110111" | "10111100"|"10111101"|"10111110"|"10111111" |"11000000"|"11000001"|"11000010"|"11000011"|"11000100"|"11000101"|"11000110"|"11000111" |"11001000"|"11001001"|"11001010"|"11001011"|"11001100"|"11001101"|"11001110"|"11001111" |"11010000"|"11010001"|"11010010"|"11010011"|"11010100"|"11010101"|"11010110"|"11010111" |"11011000"|"11011001"|"11011010"|"11011011"|"11011100"|"11011101"|"11011110"|"11011111" |"11100000"|"11100001"|"11100010"|"11100011"|"11100100"|"11100101"|"11100110"|"11100111" |"11101000"|"11101001"|"11101010"|"11101011"|"11101100"|"11101101"|"11101110"|"11101111" |"11110000"|"11110001"|"11110010"|"11110011"|"11110100"|"11110101"|"11110110"|"11110111" |"11111000"|"11111001"|"11111010"|"11111011"|"11111100"|"11111101"|"11111110"|"11111111" => null; -- NOP, undocumented when "01111110"|"01111111" => -- NOP, undocumented null; -- 8 BIT LOAD GROUP when "01010111" => -- LD A,I Special_LD <= "100"; TStates <= "101"; when "01011111" => -- LD A,R Special_LD <= "101"; TStates <= "101"; when "01000111" => -- LD I,A Special_LD <= "110"; TStates <= "101"; when "01001111" => -- LD R,A Special_LD <= "111"; TStates <= "101"; -- 16 BIT LOAD GROUP when "01001011"|"01011011"|"01101011"|"01111011" => -- LD dd,(nn) MCycles <= "101"; case to_integer(unsigned(MCycle)) is when 2 => Inc_PC <= '1'; LDZ <= '1'; when 3 => Set_Addr_To <= aZI; Inc_PC <= '1'; LDW <= '1'; when 4 => Read_To_Reg <= '1'; if IR(5 downto 4) = "11" then Set_BusA_To <= "1000"; else Set_BusA_To(2 downto 1) <= IR(5 downto 4); Set_BusA_To(0) <= '1'; end if; Inc_WZ <= '1'; Set_Addr_To <= aZI; when 5 => Read_To_Reg <= '1'; if IR(5 downto 4) = "11" then Set_BusA_To <= "1001"; else Set_BusA_To(2 downto 1) <= IR(5 downto 4); Set_BusA_To(0) <= '0'; end if; when others => null; end case; when "01000011"|"01010011"|"01100011"|"01110011" => -- LD (nn),dd MCycles <= "101"; case to_integer(unsigned(MCycle)) is when 2 => Inc_PC <= '1'; LDZ <= '1'; when 3 => Set_Addr_To <= aZI; Inc_PC <= '1'; LDW <= '1'; if IR(5 downto 4) = "11" then Set_BusB_To <= "1000"; else Set_BusB_To(2 downto 1) <= IR(5 downto 4); Set_BusB_To(0) <= '1'; Set_BusB_To(3) <= '0'; end if; when 4 => Inc_WZ <= '1'; Set_Addr_To <= aZI; Write <= '1'; if IR(5 downto 4) = "11" then Set_BusB_To <= "1001"; else Set_BusB_To(2 downto 1) <= IR(5 downto 4); Set_BusB_To(0) <= '0'; Set_BusB_To(3) <= '0'; end if; when 5 => Write <= '1'; when others => null; end case; when "10100000" | "10101000" | "10110000" | "10111000" => -- LDI, LDD, LDIR, LDDR MCycles <= "100"; case to_integer(unsigned(MCycle)) is when 1 => Set_Addr_To <= aXY; IncDec_16 <= "1100"; -- BC when 2 => Set_BusB_To <= "0110"; Set_BusA_To(2 downto 0) <= "111"; ALU_Op <= "0000"; Set_Addr_To <= aDE; if IR(3) = '0' then IncDec_16 <= "0110"; -- IX else IncDec_16 <= "1110"; end if; when 3 => I_BT <= '1'; TStates <= "101"; Write <= '1'; if IR(3) = '0' then IncDec_16 <= "0101"; -- DE else IncDec_16 <= "1101"; end if; when 4 => NoRead <= '1'; TStates <= "101"; when others => null; end case; when "10100001" | "10101001" | "10110001" | "10111001" => -- CPI, CPD, CPIR, CPDR MCycles <= "100"; case to_integer(unsigned(MCycle)) is when 1 => Set_Addr_To <= aXY; IncDec_16 <= "1100"; -- BC when 2 => Set_BusB_To <= "0110"; Set_BusA_To(2 downto 0) <= "111"; ALU_Op <= "0111"; Save_ALU <= '1'; PreserveC <= '1'; if IR(3) = '0' then IncDec_16 <= "0110"; else IncDec_16 <= "1110"; end if; when 3 => NoRead <= '1'; I_BC <= '1'; TStates <= "101"; when 4 => NoRead <= '1'; TStates <= "101"; when others => null; end case; when "01000100"|"01001100"|"01010100"|"01011100"|"01100100"|"01101100"|"01110100"|"01111100" => -- NEG Alu_OP <= "0010"; Set_BusB_To <= "0111"; Set_BusA_To <= "1010"; Read_To_Acc <= '1'; Save_ALU <= '1'; when "01000110"|"01001110"|"01100110"|"01101110" => -- IM 0 IMode <= "00"; when "01010110"|"01110110" => -- IM 1 IMode <= "01"; when "01011110"|"01110111" => -- IM 2 IMode <= "10"; -- 16 bit arithmetic when "01001010"|"01011010"|"01101010"|"01111010" => -- ADC HL,ss MCycles <= "011"; case to_integer(unsigned(MCycle)) is when 2 => NoRead <= '1'; ALU_Op <= "0001"; Read_To_Reg <= '1'; Save_ALU <= '1'; Set_BusA_To(2 downto 0) <= "101"; case to_integer(unsigned(IR(5 downto 4))) is when 0|1|2 => Set_BusB_To(2 downto 1) <= IR(5 downto 4); Set_BusB_To(0) <= '1'; when others => Set_BusB_To <= "1000"; end case; TStates <= "100"; when 3 => NoRead <= '1'; Read_To_Reg <= '1'; Save_ALU <= '1'; ALU_Op <= "0001"; Set_BusA_To(2 downto 0) <= "100"; case to_integer(unsigned(IR(5 downto 4))) is when 0|1|2 => Set_BusB_To(2 downto 1) <= IR(5 downto 4); Set_BusB_To(0) <= '0'; when others => Set_BusB_To <= "1001"; end case; when others => end case; when "01000010"|"01010010"|"01100010"|"01110010" => -- SBC HL,ss MCycles <= "011"; case to_integer(unsigned(MCycle)) is when 2 => NoRead <= '1'; ALU_Op <= "0011"; Read_To_Reg <= '1'; Save_ALU <= '1'; Set_BusA_To(2 downto 0) <= "101"; case to_integer(unsigned(IR(5 downto 4))) is when 0|1|2 => Set_BusB_To(2 downto 1) <= IR(5 downto 4); Set_BusB_To(0) <= '1'; when others => Set_BusB_To <= "1000"; end case; TStates <= "100"; when 3 => NoRead <= '1'; ALU_Op <= "0011"; Read_To_Reg <= '1'; Save_ALU <= '1'; Set_BusA_To(2 downto 0) <= "100"; case to_integer(unsigned(IR(5 downto 4))) is when 0|1|2 => Set_BusB_To(2 downto 1) <= IR(5 downto 4); when others => Set_BusB_To <= "1001"; end case; when others => end case; when "01101111" => -- RLD MCycles <= "100"; case to_integer(unsigned(MCycle)) is when 2 => NoRead <= '1'; Set_Addr_To <= aXY; when 3 => Read_To_Reg <= '1'; Set_BusB_To(2 downto 0) <= "110"; Set_BusA_To(2 downto 0) <= "111"; ALU_Op <= "1101"; TStates <= "100"; Set_Addr_To <= aXY; Save_ALU <= '1'; when 4 => I_RLD <= '1'; Write <= '1'; when others => end case; when "01100111" => -- RRD MCycles <= "100"; case to_integer(unsigned(MCycle)) is when 2 => Set_Addr_To <= aXY; when 3 => Read_To_Reg <= '1'; Set_BusB_To(2 downto 0) <= "110"; Set_BusA_To(2 downto 0) <= "111"; ALU_Op <= "1110"; TStates <= "100"; Set_Addr_To <= aXY; Save_ALU <= '1'; when 4 => I_RRD <= '1'; Write <= '1'; when others => end case; when "01000101"|"01001101"|"01010101"|"01011101"|"01100101"|"01101101"|"01110101"|"01111101" => -- RETI, RETN MCycles <= "011"; case to_integer(unsigned(MCycle)) is when 1 => Set_Addr_TO <= aSP; when 2 => IncDec_16 <= "0111"; Set_Addr_To <= aSP; LDZ <= '1'; when 3 => Jump <= '1'; IncDec_16 <= "0111"; I_RETN <= '1'; when others => null; end case; when "01000000"|"01001000"|"01010000"|"01011000"|"01100000"|"01101000"|"01110000"|"01111000" => -- IN r,(C) MCycles <= "010"; case to_integer(unsigned(MCycle)) is when 1 => Set_Addr_To <= aBC; when 2 => IORQ <= '1'; if IR(5 downto 3) /= "110" then Read_To_Reg <= '1'; Set_BusA_To(2 downto 0) <= IR(5 downto 3); end if; I_INRC <= '1'; when others => end case; when "01000001"|"01001001"|"01010001"|"01011001"|"01100001"|"01101001"|"01110001"|"01111001" => -- OUT (C),r -- OUT (C),0 MCycles <= "010"; case to_integer(unsigned(MCycle)) is when 1 => Set_Addr_To <= aBC; Set_BusB_To(2 downto 0) <= IR(5 downto 3); if IR(5 downto 3) = "110" then Set_BusB_To(3) <= '1'; end if; when 2 => Write <= '1'; IORQ <= '1'; when others => end case; when "10100010" | "10101010" | "10110010" | "10111010" => -- INI, IND, INIR, INDR MCycles <= "100"; case to_integer(unsigned(MCycle)) is when 1 => Set_Addr_To <= aBC; Set_BusB_To <= "1010"; Set_BusA_To <= "0000"; Read_To_Reg <= '1'; Save_ALU <= '1'; ALU_Op <= "0010"; when 2 => IORQ <= '1'; Set_BusB_To <= "0110"; Set_Addr_To <= aXY; when 3 => if IR(3) = '0' then IncDec_16 <= "0010"; else IncDec_16 <= "1010"; end if; TStates <= "100"; Write <= '1'; I_BTR <= '1'; when 4 => NoRead <= '1'; TStates <= "101"; when others => null; end case; when "10100011" | "10101011" | "10110011" | "10111011" => -- OUTI, OUTD, OTIR, OTDR MCycles <= "100"; case to_integer(unsigned(MCycle)) is when 1 => TStates <= "101"; Set_Addr_To <= aXY; Set_BusB_To <= "1010"; Set_BusA_To <= "0000"; Read_To_Reg <= '1'; Save_ALU <= '1'; ALU_Op <= "0010"; when 2 => Set_BusB_To <= "0110"; Set_Addr_To <= aBC; when 3 => if IR(3) = '0' then IncDec_16 <= "0010"; else IncDec_16 <= "1010"; end if; IORQ <= '1'; Write <= '1'; I_BTR <= '1'; when 4 => NoRead <= '1'; TStates <= "101"; when others => null; end case; end case; end case; if Mode = 1 then if MCycle = "001" then -- TStates <= "100"; else TStates <= "011"; end if; end if; if Mode = 3 then if MCycle = "001" then -- TStates <= "100"; else TStates <= "100"; end if; end if; if Mode < 2 then if MCycle = "110" then Inc_PC <= '1'; if Mode = 1 then Set_Addr_To <= aXY; TStates <= "100"; Set_BusB_To(2 downto 0) <= SSS; Set_BusB_To(3) <= '0'; end if; if IRB = "00110110" or IRB = "11001011" then Set_Addr_To <= aNone; end if; end if; if MCycle = "111" then if Mode = 0 then TStates <= "101"; end if; if ISet /= "01" then Set_Addr_To <= aXY; end if; Set_BusB_To(2 downto 0) <= SSS; Set_BusB_To(3) <= '0'; if IRB = "00110110" or ISet = "01" then -- LD (HL),n Inc_PC <= '1'; else NoRead <= '1'; end if; end if; end if; end process; end;
zx-simi
trunk/fpga/t80/trunk/rtl/vhdl/T80_MCode.vhd
VHDL
oos
50,680
-- -- Z80 compatible microprocessor core -- -- Version : 0242 -- -- Copyright (c) 2001-2002 Daniel Wallner (jesus@opencores.org) -- -- All rights reserved -- -- Redistribution and use in source and synthezised 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 synthesized 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 author nor the names of other 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 AUTHOR 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. -- -- Please report bugs to the author, but before you do so, please -- make sure that this is not a derivative work and that -- you have the latest version of this file. -- -- The latest version of this file can be found at: -- http://www.opencores.org/cvsweb.shtml/t80/ -- -- Limitations : -- -- File history : -- library IEEE; use IEEE.std_logic_1164.all; package T80_Pack is component T80 generic( Mode : integer := 0; -- 0 => Z80, 1 => Fast Z80, 2 => 8080, 3 => GB IOWait : integer := 0; -- 1 => Single cycle I/O, 1 => Std I/O cycle Flag_C : integer := 0; Flag_N : integer := 1; Flag_P : integer := 2; Flag_X : integer := 3; Flag_H : integer := 4; Flag_Y : integer := 5; Flag_Z : integer := 6; Flag_S : integer := 7 ); port( RESET_n : in std_logic; CLK_n : in std_logic; CEN : in std_logic; WAIT_n : in std_logic; INT_n : in std_logic; NMI_n : in std_logic; BUSRQ_n : in std_logic; M1_n : out std_logic; IORQ : out std_logic; NoRead : out std_logic; Write : out std_logic; RFSH_n : out std_logic; HALT_n : out std_logic; BUSAK_n : out std_logic; A : out std_logic_vector(15 downto 0); DInst : in std_logic_vector(7 downto 0); DI : in std_logic_vector(7 downto 0); DO : out std_logic_vector(7 downto 0); MC : out std_logic_vector(2 downto 0); TS : out std_logic_vector(2 downto 0); IntCycle_n : out std_logic; IntE : out std_logic; Stop : out std_logic ); end component; component T80_Reg port( Clk : in std_logic; CEN : in std_logic; WEH : in std_logic; WEL : in std_logic; AddrA : in std_logic_vector(2 downto 0); AddrB : in std_logic_vector(2 downto 0); AddrC : in std_logic_vector(2 downto 0); DIH : in std_logic_vector(7 downto 0); DIL : in std_logic_vector(7 downto 0); DOAH : out std_logic_vector(7 downto 0); DOAL : out std_logic_vector(7 downto 0); DOBH : out std_logic_vector(7 downto 0); DOBL : out std_logic_vector(7 downto 0); DOCH : out std_logic_vector(7 downto 0); DOCL : out std_logic_vector(7 downto 0) ); end component; component T80_MCode generic( Mode : integer := 0; Flag_C : integer := 0; Flag_N : integer := 1; Flag_P : integer := 2; Flag_X : integer := 3; Flag_H : integer := 4; Flag_Y : integer := 5; Flag_Z : integer := 6; Flag_S : integer := 7 ); port( IR : in std_logic_vector(7 downto 0); ISet : in std_logic_vector(1 downto 0); MCycle : in std_logic_vector(2 downto 0); F : in std_logic_vector(7 downto 0); NMICycle : in std_logic; IntCycle : in std_logic; MCycles : out std_logic_vector(2 downto 0); TStates : out std_logic_vector(2 downto 0); Prefix : out std_logic_vector(1 downto 0); -- None,BC,ED,DD/FD Inc_PC : out std_logic; Inc_WZ : out std_logic; IncDec_16 : out std_logic_vector(3 downto 0); -- BC,DE,HL,SP 0 is inc Read_To_Reg : out std_logic; Read_To_Acc : out std_logic; Set_BusA_To : out std_logic_vector(3 downto 0); -- B,C,D,E,H,L,DI/DB,A,SP(L),SP(M),0,F Set_BusB_To : out std_logic_vector(3 downto 0); -- B,C,D,E,H,L,DI,A,SP(L),SP(M),1,F,PC(L),PC(M),0 ALU_Op : out std_logic_vector(3 downto 0); -- ADD, ADC, SUB, SBC, AND, XOR, OR, CP, ROT, BIT, SET, RES, DAA, RLD, RRD, None Save_ALU : out std_logic; PreserveC : out std_logic; Arith16 : out std_logic; Set_Addr_To : out std_logic_vector(2 downto 0); -- aNone,aXY,aIOA,aSP,aBC,aDE,aZI IORQ : out std_logic; Jump : out std_logic; JumpE : out std_logic; JumpXY : out std_logic; Call : out std_logic; RstP : out std_logic; LDZ : out std_logic; LDW : out std_logic; LDSPHL : out std_logic; Special_LD : out std_logic_vector(2 downto 0); -- A,I;A,R;I,A;R,A;None ExchangeDH : out std_logic; ExchangeRp : out std_logic; ExchangeAF : out std_logic; ExchangeRS : out std_logic; I_DJNZ : out std_logic; I_CPL : out std_logic; I_CCF : out std_logic; I_SCF : out std_logic; I_RETN : out std_logic; I_BT : out std_logic; I_BC : out std_logic; I_BTR : out std_logic; I_RLD : out std_logic; I_RRD : out std_logic; I_INRC : out std_logic; SetDI : out std_logic; SetEI : out std_logic; IMode : out std_logic_vector(1 downto 0); Halt : out std_logic; NoRead : out std_logic; Write : out std_logic ); end component; component T80_ALU generic( Mode : integer := 0; Flag_C : integer := 0; Flag_N : integer := 1; Flag_P : integer := 2; Flag_X : integer := 3; Flag_H : integer := 4; Flag_Y : integer := 5; Flag_Z : integer := 6; Flag_S : integer := 7 ); port( Arith16 : in std_logic; Z16 : in std_logic; ALU_Op : in std_logic_vector(3 downto 0); IR : in std_logic_vector(5 downto 0); ISet : in std_logic_vector(1 downto 0); BusA : in std_logic_vector(7 downto 0); BusB : in std_logic_vector(7 downto 0); F_In : in std_logic_vector(7 downto 0); Q : out std_logic_vector(7 downto 0); F_Out : out std_logic_vector(7 downto 0) ); end component; end;
zx-simi
trunk/fpga/t80/trunk/rtl/vhdl/T80_Pack.vhd
VHDL
oos
6,709
-- -- Z80 compatible microprocessor core, asynchronous top level -- -- Version : 0247 -- -- Copyright (c) 2001-2002 Daniel Wallner (jesus@opencores.org) -- -- All rights reserved -- -- Redistribution and use in source and synthezised 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 synthesized 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 author nor the names of other 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 AUTHOR 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. -- -- Please report bugs to the author, but before you do so, please -- make sure that this is not a derivative work and that -- you have the latest version of this file. -- -- The latest version of this file can be found at: -- http://www.opencores.org/cvsweb.shtml/t80/ -- -- Limitations : -- -- File history : -- -- 0208 : First complete release -- -- 0211 : Fixed interrupt cycle -- -- 0235 : Updated for T80 interface change -- -- 0238 : Updated for T80 interface change -- -- 0240 : Updated for T80 interface change -- -- 0242 : Updated for T80 interface change -- -- 0247 : Fixed bus req/ack cycle -- library IEEE; use IEEE.std_logic_1164.all; use IEEE.numeric_std.all; use work.T80_Pack.all; entity T80a is generic( Mode : integer := 0 -- 0 => Z80, 1 => Fast Z80, 2 => 8080, 3 => GB ); port( RESET_n : in std_logic; CLK_n : in std_logic; WAIT_n : in std_logic; INT_n : in std_logic; NMI_n : in std_logic; BUSRQ_n : in std_logic; M1_n : out std_logic; MREQ_n : out std_logic; IORQ_n : out std_logic; RD_n : out std_logic; WR_n : out std_logic; RFSH_n : out std_logic; HALT_n : out std_logic; BUSAK_n : out std_logic; A : out std_logic_vector(15 downto 0); D : inout std_logic_vector(7 downto 0) ); end T80a; architecture rtl of T80a is signal CEN : std_logic; signal Reset_s : std_logic; signal IntCycle_n : std_logic; signal IORQ : std_logic; signal NoRead : std_logic; signal Write : std_logic; signal MREQ : std_logic; signal MReq_Inhibit : std_logic; signal Req_Inhibit : std_logic; signal RD : std_logic; signal MREQ_n_i : std_logic; signal IORQ_n_i : std_logic; signal RD_n_i : std_logic; signal WR_n_i : std_logic; signal RFSH_n_i : std_logic; signal BUSAK_n_i : std_logic; signal A_i : std_logic_vector(15 downto 0); signal DO : std_logic_vector(7 downto 0); signal DI_Reg : std_logic_vector (7 downto 0); -- Input synchroniser signal Wait_s : std_logic; signal MCycle : std_logic_vector(2 downto 0); signal TState : std_logic_vector(2 downto 0); begin CEN <= '1'; BUSAK_n <= BUSAK_n_i; MREQ_n_i <= not MREQ or (Req_Inhibit and MReq_Inhibit); RD_n_i <= not RD or Req_Inhibit; MREQ_n <= MREQ_n_i when BUSAK_n_i = '1' else 'Z'; IORQ_n <= IORQ_n_i when BUSAK_n_i = '1' else 'Z'; RD_n <= RD_n_i when BUSAK_n_i = '1' else 'Z'; WR_n <= WR_n_i when BUSAK_n_i = '1' else 'Z'; RFSH_n <= RFSH_n_i when BUSAK_n_i = '1' else 'Z'; A <= A_i when BUSAK_n_i = '1' else (others => 'Z'); D <= DO when Write = '1' and BUSAK_n_i = '1' else (others => 'Z'); process (RESET_n, CLK_n) begin if RESET_n = '0' then Reset_s <= '0'; elsif CLK_n'event and CLK_n = '1' then Reset_s <= '1'; end if; end process; u0 : T80 generic map( Mode => Mode, IOWait => 1) port map( CEN => CEN, M1_n => M1_n, IORQ => IORQ, NoRead => NoRead, Write => Write, RFSH_n => RFSH_n_i, HALT_n => HALT_n, WAIT_n => Wait_s, INT_n => INT_n, NMI_n => NMI_n, RESET_n => Reset_s, BUSRQ_n => BUSRQ_n, BUSAK_n => BUSAK_n_i, CLK_n => CLK_n, A => A_i, DInst => D, DI => DI_Reg, DO => DO, MC => MCycle, TS => TState, IntCycle_n => IntCycle_n); process (CLK_n) begin if CLK_n'event and CLK_n = '0' then Wait_s <= WAIT_n; if TState = "011" and BUSAK_n_i = '1' then DI_Reg <= to_x01(D); end if; end if; end process; process (Reset_s,CLK_n) begin if Reset_s = '0' then WR_n_i <= '1'; elsif CLK_n'event and CLK_n = '1' then WR_n_i <= '1'; if TState = "001" then -- To short for IO writes !!!!!!!!!!!!!!!!!!! WR_n_i <= not Write; end if; end if; end process; process (Reset_s,CLK_n) begin if Reset_s = '0' then Req_Inhibit <= '0'; elsif CLK_n'event and CLK_n = '1' then if MCycle = "001" and TState = "010" then Req_Inhibit <= '1'; else Req_Inhibit <= '0'; end if; end if; end process; process (Reset_s,CLK_n) begin if Reset_s = '0' then MReq_Inhibit <= '0'; elsif CLK_n'event and CLK_n = '0' then if MCycle = "001" and TState = "010" then MReq_Inhibit <= '1'; else MReq_Inhibit <= '0'; end if; end if; end process; process(Reset_s,CLK_n) begin if Reset_s = '0' then RD <= '0'; IORQ_n_i <= '1'; MREQ <= '0'; elsif CLK_n'event and CLK_n = '0' then if MCycle = "001" then if TState = "001" then RD <= IntCycle_n; MREQ <= IntCycle_n; IORQ_n_i <= IntCycle_n; end if; if TState = "011" then RD <= '0'; IORQ_n_i <= '1'; MREQ <= '1'; end if; if TState = "100" then MREQ <= '0'; end if; else if TState = "001" and NoRead = '0' then RD <= not Write; IORQ_n_i <= not IORQ; MREQ <= not IORQ; end if; if TState = "011" then RD <= '0'; IORQ_n_i <= '1'; MREQ <= '0'; end if; end if; end if; end process; end;
zx-simi
trunk/fpga/t80/trunk/rtl/vhdl/T80a.vhd
VHDL
oos
6,560
-- -- Inferrable Synchronous SRAM for Leonardo synthesis, no write through! -- -- Version : 0236 -- -- Copyright (c) 2002 Daniel Wallner (jesus@opencores.org) -- -- All rights reserved -- -- Redistribution and use in source and synthezised 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 synthesized 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 author nor the names of other 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 AUTHOR 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. -- -- Please report bugs to the author, but before you do so, please -- make sure that this is not a derivative work and that -- you have the latest version of this file. -- -- The latest version of this file can be found at: -- http://www.opencores.org/cvsweb.shtml/t51/ -- -- Limitations : -- -- File history : -- library IEEE; use IEEE.std_logic_1164.all; use IEEE.numeric_std.all; entity SSRAM is generic( AddrWidth : integer := 16; DataWidth : integer := 8 ); port( Clk : in std_logic; CE_n : in std_logic; WE_n : in std_logic; A : in std_logic_vector(AddrWidth - 1 downto 0); DIn : in std_logic_vector(DataWidth - 1 downto 0); DOut : out std_logic_vector(DataWidth - 1 downto 0) ); end SSRAM; architecture behaviour of SSRAM is type Memory_Image is array (natural range <>) of std_logic_vector(DataWidth - 1 downto 0); signal RAM : Memory_Image(0 to 2 ** AddrWidth - 1); -- signal A_r : std_logic_vector(AddrWidth - 1 downto 0); begin process (Clk) begin if Clk'event and Clk = '1' then -- pragma translate_off if not is_x(A) then -- pragma translate_on DOut <= RAM(to_integer(unsigned(A(AddrWidth - 1 downto 0)))); -- pragma translate_off end if; -- pragma translate_on if CE_n = '0' and WE_n = '0' then RAM(to_integer(unsigned(A))) <= DIn; end if; -- A_r <= A; end if; end process; end;
zx-simi
trunk/fpga/t80/trunk/rtl/vhdl/SSRAM2.vhd
VHDL
oos
3,034
-- -- T80 Registers for Xilinx Select RAM -- -- Version : 0244 -- -- Copyright (c) 2002 Daniel Wallner (jesus@opencores.org) -- -- All rights reserved -- -- Redistribution and use in source and synthezised 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 synthesized 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 author nor the names of other 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 AUTHOR 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. -- -- Please report bugs to the author, but before you do so, please -- make sure that this is not a derivative work and that -- you have the latest version of this file. -- -- The latest version of this file can be found at: -- http://www.opencores.org/cvsweb.shtml/t51/ -- -- Limitations : -- -- File history : -- -- 0242 : Initial release -- -- 0244 : Removed UNISIM library and added componet declaration -- library IEEE; use IEEE.std_logic_1164.all; use IEEE.numeric_std.all; Library UNISIM; use UNISIM.vcomponents.all; entity T80_Reg is port( Clk : in std_logic; CEN : in std_logic; WEH : in std_logic; WEL : in std_logic; AddrA : in std_logic_vector(2 downto 0); AddrB : in std_logic_vector(2 downto 0); AddrC : in std_logic_vector(2 downto 0); DIH : in std_logic_vector(7 downto 0); DIL : in std_logic_vector(7 downto 0); DOAH : out std_logic_vector(7 downto 0); DOAL : out std_logic_vector(7 downto 0); DOBH : out std_logic_vector(7 downto 0); DOBL : out std_logic_vector(7 downto 0); DOCH : out std_logic_vector(7 downto 0); DOCL : out std_logic_vector(7 downto 0) ); end T80_Reg; architecture rtl of T80_Reg is component RAM16X1D port( DPO : out std_ulogic; SPO : out std_ulogic; A0 : in std_ulogic; A1 : in std_ulogic; A2 : in std_ulogic; A3 : in std_ulogic; D : in std_ulogic; DPRA0 : in std_ulogic; DPRA1 : in std_ulogic; DPRA2 : in std_ulogic; DPRA3 : in std_ulogic; WCLK : in std_ulogic; WE : in std_ulogic); end component; signal ENH : std_logic; signal ENL : std_logic; begin ENH <= CEN and WEH; ENL <= CEN and WEL; bG1: for I in 0 to 7 generate begin Reg1H : RAM16X1D port map( DPO => DOBH(i), SPO => DOAH(i), A0 => AddrA(0), A1 => AddrA(1), A2 => AddrA(2), A3 => '0', D => DIH(i), DPRA0 => AddrB(0), DPRA1 => AddrB(1), DPRA2 => AddrB(2), DPRA3 => '0', WCLK => Clk, WE => ENH); Reg1L : RAM16X1D port map( DPO => DOBL(i), SPO => DOAL(i), A0 => AddrA(0), A1 => AddrA(1), A2 => AddrA(2), A3 => '0', D => DIL(i), DPRA0 => AddrB(0), DPRA1 => AddrB(1), DPRA2 => AddrB(2), DPRA3 => '0', WCLK => Clk, WE => ENL); Reg2H : RAM16X1D port map( DPO => DOCH(i), SPO => open, A0 => AddrA(0), A1 => AddrA(1), A2 => AddrA(2), A3 => '0', D => DIH(i), DPRA0 => AddrC(0), DPRA1 => AddrC(1), DPRA2 => AddrC(2), DPRA3 => '0', WCLK => Clk, WE => ENH); Reg2L : RAM16X1D port map( DPO => DOCL(i), SPO => open, A0 => AddrA(0), A1 => AddrA(1), A2 => AddrA(2), A3 => '0', D => DIL(i), DPRA0 => AddrC(0), DPRA1 => AddrC(1), DPRA2 => AddrC(2), DPRA3 => '0', WCLK => Clk, WE => ENL); end generate; end;
zx-simi
trunk/fpga/t80/trunk/rtl/vhdl/T80_RegX.vhd
VHDL
oos
4,443
-- -- Inferrable Synchronous SRAM for XST synthesis -- -- Version : 0220 -- -- Copyright (c) 2002 Daniel Wallner (jesus@opencores.org) -- -- All rights reserved -- -- Redistribution and use in source and synthezised 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 synthesized 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 author nor the names of other 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 AUTHOR 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. -- -- Please report bugs to the author, but before you do so, please -- make sure that this is not a derivative work and that -- you have the latest version of this file. -- -- The latest version of this file can be found at: -- http://www.opencores.org/cvsweb.shtml/t51/ -- -- Limitations : -- -- File history : -- 0208 : Initial release -- 0218 : Fixed data out at write -- 0220 : Added support for XST library IEEE; use IEEE.std_logic_1164.all; use IEEE.numeric_std.all; entity SSRAM is generic( AddrWidth : integer := 11; DataWidth : integer := 8 ); port( Clk : in std_logic; CE_n : in std_logic; WE_n : in std_logic; A : in std_logic_vector(AddrWidth - 1 downto 0); DIn : in std_logic_vector(DataWidth - 1 downto 0); DOut : out std_logic_vector(DataWidth - 1 downto 0) ); end SSRAM; architecture behaviour of SSRAM is type Memory_Image is array (natural range <>) of std_logic_vector(DataWidth - 1 downto 0); signal RAM : Memory_Image(0 to 2 ** AddrWidth - 1); signal A_r : std_logic_vector(AddrWidth - 1 downto 0); begin process (Clk) begin if Clk'event and Clk = '1' then if (CE_n nor WE_n) = '1' then RAM(to_integer(unsigned(A))) <= DIn; end if; A_r <= A; end if; end process; DOut <= RAM(to_integer(unsigned(A_r))) -- pragma translate_off when not is_x(A_r) else (others => '-') -- pragma translate_on ; end;
zx-simi
trunk/fpga/t80/trunk/rtl/vhdl/SSRAM.vhd
VHDL
oos
3,030
-- -- T80 Registers, technology independent -- -- Version : 0244 -- -- Copyright (c) 2002 Daniel Wallner (jesus@opencores.org) -- -- All rights reserved -- -- Redistribution and use in source and synthezised 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 synthesized 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 author nor the names of other 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 AUTHOR 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. -- -- Please report bugs to the author, but before you do so, please -- make sure that this is not a derivative work and that -- you have the latest version of this file. -- -- The latest version of this file can be found at: -- http://www.opencores.org/cvsweb.shtml/t51/ -- -- Limitations : -- -- File history : -- -- 0242 : Initial release -- -- 0244 : Changed to single register file -- library IEEE; use IEEE.std_logic_1164.all; use IEEE.numeric_std.all; entity T80_Reg is port( Clk : in std_logic; CEN : in std_logic; WEH : in std_logic; WEL : in std_logic; AddrA : in std_logic_vector(2 downto 0); AddrB : in std_logic_vector(2 downto 0); AddrC : in std_logic_vector(2 downto 0); DIH : in std_logic_vector(7 downto 0); DIL : in std_logic_vector(7 downto 0); DOAH : out std_logic_vector(7 downto 0); DOAL : out std_logic_vector(7 downto 0); DOBH : out std_logic_vector(7 downto 0); DOBL : out std_logic_vector(7 downto 0); DOCH : out std_logic_vector(7 downto 0); DOCL : out std_logic_vector(7 downto 0) ); end T80_Reg; architecture rtl of T80_Reg is type Register_Image is array (natural range <>) of std_logic_vector(7 downto 0); signal RegsH : Register_Image(0 to 7); signal RegsL : Register_Image(0 to 7); begin process (Clk) begin if Clk'event and Clk = '1' then if CEN = '1' then if WEH = '1' then RegsH(to_integer(unsigned(AddrA))) <= DIH; end if; if WEL = '1' then RegsL(to_integer(unsigned(AddrA))) <= DIL; end if; end if; end if; end process; DOAH <= RegsH(to_integer(unsigned(AddrA))); DOAL <= RegsL(to_integer(unsigned(AddrA))); DOBH <= RegsH(to_integer(unsigned(AddrB))); DOBL <= RegsL(to_integer(unsigned(AddrB))); DOCH <= RegsH(to_integer(unsigned(AddrC))); DOCL <= RegsL(to_integer(unsigned(AddrC))); end;
zx-simi
trunk/fpga/t80/trunk/rtl/vhdl/T80_Reg.vhd
VHDL
oos
3,474
-- Z80, Monitor ROM, 4k RAM and two 16450 UARTs -- that can be synthesized and used with -- the NoICE debugger that can be found at -- http://www.noicedebugger.com/ library IEEE; use IEEE.std_logic_1164.all; entity DebugSystem is port( Reset_n : in std_logic; Clk : in std_logic; NMI_n : in std_logic; RXD0 : in std_logic; CTS0 : in std_logic; DSR0 : in std_logic; RI0 : in std_logic; DCD0 : in std_logic; RXD1 : in std_logic; CTS1 : in std_logic; DSR1 : in std_logic; RI1 : in std_logic; DCD1 : in std_logic; TXD0 : out std_logic; RTS0 : out std_logic; DTR0 : out std_logic; TXD1 : out std_logic; RTS1 : out std_logic; DTR1 : out std_logic ); end DebugSystem; architecture struct of DebugSystem is signal M1_n : std_logic; signal MREQ_n : std_logic; signal IORQ_n : std_logic; signal RD_n : std_logic; signal WR_n : std_logic; signal RFSH_n : std_logic; signal HALT_n : std_logic; signal WAIT_n : std_logic; signal INT_n : std_logic; signal RESET_s : std_logic; signal BUSRQ_n : std_logic; signal BUSAK_n : std_logic; signal A : std_logic_vector(15 downto 0); signal D : std_logic_vector(7 downto 0); signal ROM_D : std_logic_vector(7 downto 0); signal SRAM_D : std_logic_vector(7 downto 0); signal UART0_D : std_logic_vector(7 downto 0); signal UART1_D : std_logic_vector(7 downto 0); signal CPU_D : std_logic_vector(7 downto 0); signal Mirror : std_logic; signal IOWR_n : std_logic; signal RAMCS_n : std_logic; signal UART0CS_n : std_logic; signal UART1CS_n : std_logic; signal BaudOut0 : std_logic; signal BaudOut1 : std_logic; begin Wait_n <= '1'; BusRq_n <= '1'; INT_n <= '1'; process (Reset_n, Clk) begin if Reset_n = '0' then Reset_s <= '0'; Mirror <= '0'; elsif Clk'event and Clk = '1' then Reset_s <= '1'; if IORQ_n = '0' and A(7 downto 4) = "1111" then Mirror <= D(0); end if; end if; end process; IOWR_n <= WR_n or IORQ_n; RAMCS_n <= (not Mirror and not A(15)) or MREQ_n; UART0CS_n <= '0' when IORQ_n = '0' and A(7 downto 3) = "00000" else '1'; UART1CS_n <= '0' when IORQ_n = '0' and A(7 downto 3) = "10000" else '1'; CPU_D <= SRAM_D when RAMCS_n = '0' else UART0_D when UART0CS_n = '0' else UART1_D when UART1CS_n = '0' else ROM_D; u0 : entity work.T80s generic map(Mode => 1, T2Write => 1, IOWait => 0) port map( RESET_n => RESET_s, CLK_n => Clk, WAIT_n => WAIT_n, INT_n => INT_n, NMI_n => NMI_n, BUSRQ_n => BUSRQ_n, M1_n => M1_n, MREQ_n => MREQ_n, IORQ_n => IORQ_n, RD_n => RD_n, WR_n => WR_n, RFSH_n => RFSH_n, HALT_n => HALT_n, BUSAK_n => BUSAK_n, A => A, DI => CPU_D, DO => D); u1 : entity work.MonZ80 port map( Clk => Clk, A => A(10 downto 0), D => ROM_D); u2 : entity work.SSRAM generic map( AddrWidth => 12) port map( Clk => Clk, CE_n => RAMCS_n, WE_n => WR_n, A => A(11 downto 0), DIn => D, DOut => SRAM_D); u3 : entity work.T16450 port map( MR_n => Reset_s, XIn => Clk, RClk => BaudOut0, CS_n => UART0CS_n, Rd_n => RD_n, Wr_n => IOWR_n, A => A(2 downto 0), D_In => D, D_Out => UART0_D, SIn => RXD0, CTS_n => CTS0, DSR_n => DSR0, RI_n => RI0, DCD_n => DCD0, SOut => TXD0, RTS_n => RTS0, DTR_n => DTR0, OUT1_n => open, OUT2_n => open, BaudOut => BaudOut0, Intr => open); u4 : entity work.T16450 port map( MR_n => Reset_s, XIn => Clk, RClk => BaudOut1, CS_n => UART1CS_n, Rd_n => RD_n, Wr_n => IOWR_n, A => A(2 downto 0), D_In => D, D_Out => UART1_D, SIn => RXD1, CTS_n => CTS1, DSR_n => DSR1, RI_n => RI1, DCD_n => DCD1, SOut => TXD1, RTS_n => RTS1, DTR_n => DTR1, OUT1_n => open, OUT2_n => open, BaudOut => BaudOut1, Intr => open); end;
zx-simi
trunk/fpga/t80/trunk/rtl/vhdl/DebugSystem.vhd
VHDL
oos
3,942
-- -- Z80 compatible microprocessor core -- -- Version : 0247 -- -- Copyright (c) 2001-2002 Daniel Wallner (jesus@opencores.org) -- -- All rights reserved -- -- Redistribution and use in source and synthezised 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 synthesized 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 author nor the names of other 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 AUTHOR 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. -- -- Please report bugs to the author, but before you do so, please -- make sure that this is not a derivative work and that -- you have the latest version of this file. -- -- The latest version of this file can be found at: -- http://www.opencores.org/cvsweb.shtml/t80/ -- -- Limitations : -- -- File history : -- -- 0214 : Fixed mostly flags, only the block instructions now fail the zex regression test -- -- 0238 : Fixed zero flag for 16 bit SBC and ADC -- -- 0240 : Added GB operations -- -- 0242 : Cleanup -- -- 0247 : Cleanup -- library IEEE; use IEEE.std_logic_1164.all; use IEEE.numeric_std.all; entity T80_ALU is generic( Mode : integer := 0; Flag_C : integer := 0; Flag_N : integer := 1; Flag_P : integer := 2; Flag_X : integer := 3; Flag_H : integer := 4; Flag_Y : integer := 5; Flag_Z : integer := 6; Flag_S : integer := 7 ); port( Arith16 : in std_logic; Z16 : in std_logic; ALU_Op : in std_logic_vector(3 downto 0); IR : in std_logic_vector(5 downto 0); ISet : in std_logic_vector(1 downto 0); BusA : in std_logic_vector(7 downto 0); BusB : in std_logic_vector(7 downto 0); F_In : in std_logic_vector(7 downto 0); Q : out std_logic_vector(7 downto 0); F_Out : out std_logic_vector(7 downto 0) ); end T80_ALU; architecture rtl of T80_ALU is procedure AddSub(A : std_logic_vector; B : std_logic_vector; Sub : std_logic; Carry_In : std_logic; signal Res : out std_logic_vector; signal Carry : out std_logic) is variable B_i : unsigned(A'length - 1 downto 0); variable Res_i : unsigned(A'length + 1 downto 0); begin if Sub = '1' then B_i := not unsigned(B); else B_i := unsigned(B); end if; Res_i := unsigned("0" & A & Carry_In) + unsigned("0" & B_i & "1"); Carry <= Res_i(A'length + 1); Res <= std_logic_vector(Res_i(A'length downto 1)); end; -- AddSub variables (temporary signals) signal UseCarry : std_logic; signal Carry7_v : std_logic; signal Overflow_v : std_logic; signal HalfCarry_v : std_logic; signal Carry_v : std_logic; signal Q_v : std_logic_vector(7 downto 0); signal BitMask : std_logic_vector(7 downto 0); begin with IR(5 downto 3) select BitMask <= "00000001" when "000", "00000010" when "001", "00000100" when "010", "00001000" when "011", "00010000" when "100", "00100000" when "101", "01000000" when "110", "10000000" when others; UseCarry <= not ALU_Op(2) and ALU_Op(0); AddSub(BusA(3 downto 0), BusB(3 downto 0), ALU_Op(1), ALU_Op(1) xor (UseCarry and F_In(Flag_C)), Q_v(3 downto 0), HalfCarry_v); AddSub(BusA(6 downto 4), BusB(6 downto 4), ALU_Op(1), HalfCarry_v, Q_v(6 downto 4), Carry7_v); AddSub(BusA(7 downto 7), BusB(7 downto 7), ALU_Op(1), Carry7_v, Q_v(7 downto 7), Carry_v); OverFlow_v <= Carry_v xor Carry7_v; process (Arith16, ALU_OP, F_In, BusA, BusB, IR, Q_v, Carry_v, HalfCarry_v, OverFlow_v, BitMask, ISet, Z16) variable Q_t : std_logic_vector(7 downto 0); variable DAA_Q : unsigned(8 downto 0); begin Q_t := "--------"; F_Out <= F_In; DAA_Q := "---------"; case ALU_Op is when "0000" | "0001" | "0010" | "0011" | "0100" | "0101" | "0110" | "0111" => F_Out(Flag_N) <= '0'; F_Out(Flag_C) <= '0'; case ALU_OP(2 downto 0) is when "000" | "001" => -- ADD, ADC Q_t := Q_v; F_Out(Flag_C) <= Carry_v; F_Out(Flag_H) <= HalfCarry_v; F_Out(Flag_P) <= OverFlow_v; when "010" | "011" | "111" => -- SUB, SBC, CP Q_t := Q_v; F_Out(Flag_N) <= '1'; F_Out(Flag_C) <= not Carry_v; F_Out(Flag_H) <= not HalfCarry_v; F_Out(Flag_P) <= OverFlow_v; when "100" => -- AND Q_t(7 downto 0) := BusA and BusB; F_Out(Flag_H) <= '1'; when "101" => -- XOR Q_t(7 downto 0) := BusA xor BusB; F_Out(Flag_H) <= '0'; when others => -- OR "110" Q_t(7 downto 0) := BusA or BusB; F_Out(Flag_H) <= '0'; end case; if ALU_Op(2 downto 0) = "111" then -- CP F_Out(Flag_X) <= BusB(3); F_Out(Flag_Y) <= BusB(5); else F_Out(Flag_X) <= Q_t(3); F_Out(Flag_Y) <= Q_t(5); end if; if Q_t(7 downto 0) = "00000000" then F_Out(Flag_Z) <= '1'; if Z16 = '1' then F_Out(Flag_Z) <= F_In(Flag_Z); -- 16 bit ADC,SBC end if; else F_Out(Flag_Z) <= '0'; end if; F_Out(Flag_S) <= Q_t(7); case ALU_Op(2 downto 0) is when "000" | "001" | "010" | "011" | "111" => -- ADD, ADC, SUB, SBC, CP when others => F_Out(Flag_P) <= not (Q_t(0) xor Q_t(1) xor Q_t(2) xor Q_t(3) xor Q_t(4) xor Q_t(5) xor Q_t(6) xor Q_t(7)); end case; if Arith16 = '1' then F_Out(Flag_S) <= F_In(Flag_S); F_Out(Flag_Z) <= F_In(Flag_Z); F_Out(Flag_P) <= F_In(Flag_P); end if; when "1100" => -- DAA F_Out(Flag_H) <= F_In(Flag_H); F_Out(Flag_C) <= F_In(Flag_C); DAA_Q(7 downto 0) := unsigned(BusA); DAA_Q(8) := '0'; if F_In(Flag_N) = '0' then -- After addition -- Alow > 9 or H = 1 if DAA_Q(3 downto 0) > 9 or F_In(Flag_H) = '1' then if (DAA_Q(3 downto 0) > 9) then F_Out(Flag_H) <= '1'; else F_Out(Flag_H) <= '0'; end if; DAA_Q := DAA_Q + 6; end if; -- new Ahigh > 9 or C = 1 if DAA_Q(8 downto 4) > 9 or F_In(Flag_C) = '1' then DAA_Q := DAA_Q + 96; -- 0x60 end if; else -- After subtraction if DAA_Q(3 downto 0) > 9 or F_In(Flag_H) = '1' then if DAA_Q(3 downto 0) > 5 then F_Out(Flag_H) <= '0'; end if; DAA_Q(7 downto 0) := DAA_Q(7 downto 0) - 6; end if; if unsigned(BusA) > 153 or F_In(Flag_C) = '1' then DAA_Q := DAA_Q - 352; -- 0x160 end if; end if; F_Out(Flag_X) <= DAA_Q(3); F_Out(Flag_Y) <= DAA_Q(5); F_Out(Flag_C) <= F_In(Flag_C) or DAA_Q(8); Q_t := std_logic_vector(DAA_Q(7 downto 0)); if DAA_Q(7 downto 0) = "00000000" then F_Out(Flag_Z) <= '1'; else F_Out(Flag_Z) <= '0'; end if; F_Out(Flag_S) <= DAA_Q(7); F_Out(Flag_P) <= not (DAA_Q(0) xor DAA_Q(1) xor DAA_Q(2) xor DAA_Q(3) xor DAA_Q(4) xor DAA_Q(5) xor DAA_Q(6) xor DAA_Q(7)); when "1101" | "1110" => -- RLD, RRD Q_t(7 downto 4) := BusA(7 downto 4); if ALU_Op(0) = '1' then Q_t(3 downto 0) := BusB(7 downto 4); else Q_t(3 downto 0) := BusB(3 downto 0); end if; F_Out(Flag_H) <= '0'; F_Out(Flag_N) <= '0'; F_Out(Flag_X) <= Q_t(3); F_Out(Flag_Y) <= Q_t(5); if Q_t(7 downto 0) = "00000000" then F_Out(Flag_Z) <= '1'; else F_Out(Flag_Z) <= '0'; end if; F_Out(Flag_S) <= Q_t(7); F_Out(Flag_P) <= not (Q_t(0) xor Q_t(1) xor Q_t(2) xor Q_t(3) xor Q_t(4) xor Q_t(5) xor Q_t(6) xor Q_t(7)); when "1001" => -- BIT Q_t(7 downto 0) := BusB and BitMask; F_Out(Flag_S) <= Q_t(7); if Q_t(7 downto 0) = "00000000" then F_Out(Flag_Z) <= '1'; F_Out(Flag_P) <= '1'; else F_Out(Flag_Z) <= '0'; F_Out(Flag_P) <= '0'; end if; F_Out(Flag_H) <= '1'; F_Out(Flag_N) <= '0'; F_Out(Flag_X) <= '0'; F_Out(Flag_Y) <= '0'; if IR(2 downto 0) /= "110" then F_Out(Flag_X) <= BusB(3); F_Out(Flag_Y) <= BusB(5); end if; when "1010" => -- SET Q_t(7 downto 0) := BusB or BitMask; when "1011" => -- RES Q_t(7 downto 0) := BusB and not BitMask; when "1000" => -- ROT case IR(5 downto 3) is when "000" => -- RLC Q_t(7 downto 1) := BusA(6 downto 0); Q_t(0) := BusA(7); F_Out(Flag_C) <= BusA(7); when "010" => -- RL Q_t(7 downto 1) := BusA(6 downto 0); Q_t(0) := F_In(Flag_C); F_Out(Flag_C) <= BusA(7); when "001" => -- RRC Q_t(6 downto 0) := BusA(7 downto 1); Q_t(7) := BusA(0); F_Out(Flag_C) <= BusA(0); when "011" => -- RR Q_t(6 downto 0) := BusA(7 downto 1); Q_t(7) := F_In(Flag_C); F_Out(Flag_C) <= BusA(0); when "100" => -- SLA Q_t(7 downto 1) := BusA(6 downto 0); Q_t(0) := '0'; F_Out(Flag_C) <= BusA(7); when "110" => -- SLL (Undocumented) / SWAP if Mode = 3 then Q_t(7 downto 4) := BusA(3 downto 0); Q_t(3 downto 0) := BusA(7 downto 4); F_Out(Flag_C) <= '0'; else Q_t(7 downto 1) := BusA(6 downto 0); Q_t(0) := '1'; F_Out(Flag_C) <= BusA(7); end if; when "101" => -- SRA Q_t(6 downto 0) := BusA(7 downto 1); Q_t(7) := BusA(7); F_Out(Flag_C) <= BusA(0); when others => -- SRL Q_t(6 downto 0) := BusA(7 downto 1); Q_t(7) := '0'; F_Out(Flag_C) <= BusA(0); end case; F_Out(Flag_H) <= '0'; F_Out(Flag_N) <= '0'; F_Out(Flag_X) <= Q_t(3); F_Out(Flag_Y) <= Q_t(5); F_Out(Flag_S) <= Q_t(7); if Q_t(7 downto 0) = "00000000" then F_Out(Flag_Z) <= '1'; else F_Out(Flag_Z) <= '0'; end if; F_Out(Flag_P) <= not (Q_t(0) xor Q_t(1) xor Q_t(2) xor Q_t(3) xor Q_t(4) xor Q_t(5) xor Q_t(6) xor Q_t(7)); if ISet = "00" then F_Out(Flag_P) <= F_In(Flag_P); F_Out(Flag_S) <= F_In(Flag_S); F_Out(Flag_Z) <= F_In(Flag_Z); end if; when others => null; end case; Q <= Q_t; end process; end;
zx-simi
trunk/fpga/t80/trunk/rtl/vhdl/T80_ALU.vhd
VHDL
oos
10,637
-- -- Xilinx Block RAM, 8 bit wide and variable size (Min. 512 bytes) -- -- Version : 0247 -- -- Copyright (c) 2002 Daniel Wallner (jesus@opencores.org) -- -- All rights reserved -- -- Redistribution and use in source and synthezised 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 synthesized 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 author nor the names of other 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 AUTHOR 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. -- -- Please report bugs to the author, but before you do so, please -- make sure that this is not a derivative work and that -- you have the latest version of this file. -- -- The latest version of this file can be found at: -- http://www.opencores.org/cvsweb.shtml/t51/ -- -- Limitations : -- -- File history : -- -- 0240 : Initial release -- -- 0242 : Changed RAMB4_S8 to map by name -- -- 0247 : Added RAMB4_S8 component declaration -- library IEEE; use IEEE.std_logic_1164.all; use IEEE.numeric_std.all; entity SSRAM is generic( AddrWidth : integer := 11; DataWidth : integer := 8 ); port( Clk : in std_logic; CE_n : in std_logic; WE_n : in std_logic; A : in std_logic_vector(AddrWidth - 1 downto 0); DIn : in std_logic_vector(DataWidth - 1 downto 0); DOut : out std_logic_vector(DataWidth - 1 downto 0) ); end SSRAM; architecture rtl of SSRAM is component RAMB4_S8 port( DO : out std_logic_vector(7 downto 0); ADDR : in std_logic_vector(8 downto 0); CLK : in std_ulogic; DI : in std_logic_vector(7 downto 0); EN : in std_ulogic; RST : in std_ulogic; WE : in std_ulogic); end component; constant RAMs : integer := (2 ** AddrWidth) / 512; type bRAMOut_a is array(0 to RAMs - 1) of std_logic_vector(7 downto 0); signal bRAMOut : bRAMOut_a; signal biA_r : integer; signal A_r : unsigned(A'left downto 0); -- signal A_i : std_logic_vector(8 downto 0); signal WEA : std_logic_vector(RAMs - 1 downto 0); begin process (Clk) begin if Clk'event and Clk = '1' then A_r <= unsigned(A); end if; end process; biA_r <= to_integer(A_r(A'left downto 9)); -- A_i <= std_logic_vector(A_r(8 downto 0)) when (CE_n nor WE_n) = '1' else A(8 downto 0); bG1: for I in 0 to RAMs - 1 generate begin WEA(I) <= '1' when (CE_n nor WE_n) = '1' and biA_r = I else '0'; BSSRAM : RAMB4_S8 port map( DI => DIn, EN => '1', WE => WEA(I), RST => '0', CLK => Clk, ADDR => A, DO => bRAMOut(I)); end generate; process (biA_r, bRAMOut) begin DOut <= bRAMOut(0); for I in 1 to RAMs - 1 loop if biA_r = I then DOut <= bRAMOut(I); end if; end loop; end process; end;
zx-simi
trunk/fpga/t80/trunk/rtl/vhdl/SSRAMX.vhd
VHDL
oos
3,858
-- Z80, Monitor ROM, external SRAM interface and two 16450 UARTs -- that can be synthesized and used with -- the NoICE debugger that can be found at -- http://www.noicedebugger.com/ library IEEE; use IEEE.std_logic_1164.all; entity DebugSystemXR is port( Reset_n : in std_logic; Clk : in std_logic; NMI_n : in std_logic; OE_n : out std_logic; WE_n : out std_logic; RAMCS_n : out std_logic; ROMCS_n : out std_logic; PGM_n : out std_logic; A : out std_logic_vector(16 downto 0); D : inout std_logic_vector(7 downto 0); RXD0 : in std_logic; CTS0 : in std_logic; DSR0 : in std_logic; RI0 : in std_logic; DCD0 : in std_logic; RXD1 : in std_logic; CTS1 : in std_logic; DSR1 : in std_logic; RI1 : in std_logic; DCD1 : in std_logic; TXD0 : out std_logic; RTS0 : out std_logic; DTR0 : out std_logic; TXD1 : out std_logic; RTS1 : out std_logic; DTR1 : out std_logic ); end entity DebugSystemXR; architecture struct of DebugSystemXR is signal M1_n : std_logic; signal MREQ_n : std_logic; signal IORQ_n : std_logic; signal RD_n : std_logic; signal WR_n : std_logic; signal RFSH_n : std_logic; signal HALT_n : std_logic; signal WAIT_n : std_logic; signal INT_n : std_logic; signal RESET_s : std_logic; signal BUSRQ_n : std_logic; signal BUSAK_n : std_logic; signal A_i : std_logic_vector(15 downto 0); signal D_i : std_logic_vector(7 downto 0); signal ROM_D : std_logic_vector(7 downto 0); signal UART0_D : std_logic_vector(7 downto 0); signal UART1_D : std_logic_vector(7 downto 0); signal CPU_D : std_logic_vector(7 downto 0); signal Mirror : std_logic; signal IOWR_n : std_logic; signal RAMCS_n_i : std_logic; signal UART0CS_n : std_logic; signal UART1CS_n : std_logic; signal BaudOut0 : std_logic; signal BaudOut1 : std_logic; begin Wait_n <= '1'; BusRq_n <= '1'; INT_n <= '1'; OE_n <= RD_n; WE_n <= WR_n; RAMCS_n <= RAMCS_n_i; ROMCS_n <= '1'; PGM_n <= '1'; A(14 downto 0) <= A_i(14 downto 0); A(16 downto 15) <= "00"; D <= D_i when WR_n = '0' else "ZZZZZZZZ"; process (Reset_n, Clk) begin if Reset_n = '0' then Reset_s <= '0'; Mirror <= '0'; elsif Clk'event and Clk = '1' then Reset_s <= '1'; if IORQ_n = '0' and A_i(7 downto 4) = "1111" then Mirror <= D_i(0); end if; end if; end process; IOWR_n <= WR_n or IORQ_n; RAMCS_n_i <= (not Mirror and not A_i(15)) or MREQ_n; UART0CS_n <= '0' when IORQ_n = '0' and A_i(7 downto 3) = "00000" else '1'; UART1CS_n <= '0' when IORQ_n = '0' and A_i(7 downto 3) = "10000" else '1'; CPU_D <= D when RAMCS_n_i = '0' else UART0_D when UART0CS_n = '0' else UART1_D when UART1CS_n = '0' else ROM_D; u0 : entity work.T80s generic map(Mode => 1, T2Write => 1, IOWait => 0) port map( RESET_n => RESET_s, CLK_n => Clk, WAIT_n => WAIT_n, INT_n => INT_n, NMI_n => NMI_n, BUSRQ_n => BUSRQ_n, M1_n => M1_n, MREQ_n => MREQ_n, IORQ_n => IORQ_n, RD_n => RD_n, WR_n => WR_n, RFSH_n => RFSH_n, HALT_n => HALT_n, BUSAK_n => BUSAK_n, A => A_i, DI => CPU_D, DO => D_i); u1 : entity work.MonZ80 port map( Clk => Clk, A => A_i(10 downto 0), D => ROM_D); u3 : entity work.T16450 port map( MR_n => Reset_s, XIn => Clk, RClk => BaudOut0, CS_n => UART0CS_n, Rd_n => RD_n, Wr_n => IOWR_n, A => A_i(2 downto 0), D_In => D_i, D_Out => UART0_D, SIn => RXD0, CTS_n => CTS0, DSR_n => DSR0, RI_n => RI0, DCD_n => DCD0, SOut => TXD0, RTS_n => RTS0, DTR_n => DTR0, OUT1_n => open, OUT2_n => open, BaudOut => BaudOut0, Intr => open); u4 : entity work.T16450 port map( MR_n => Reset_s, XIn => Clk, RClk => BaudOut1, CS_n => UART1CS_n, Rd_n => RD_n, Wr_n => IOWR_n, A => A_i(2 downto 0), D_In => D_i, D_Out => UART1_D, SIn => RXD1, CTS_n => CTS1, DSR_n => DSR1, RI_n => RI1, DCD_n => DCD1, SOut => TXD1, RTS_n => RTS1, DTR_n => DTR1, OUT1_n => open, OUT2_n => open, BaudOut => BaudOut1, Intr => open); end;
zx-simi
trunk/fpga/t80/trunk/rtl/vhdl/DebugSystemXR.vhd
VHDL
oos
4,171
-- -- Z80 compatible microprocessor core -- -- Version : 0247 -- -- Copyright (c) 2001-2002 Daniel Wallner (jesus@opencores.org) -- -- All rights reserved -- -- Redistribution and use in source and synthezised 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 synthesized 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 author nor the names of other 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 AUTHOR 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. -- -- Please report bugs to the author, but before you do so, please -- make sure that this is not a derivative work and that -- you have the latest version of this file. -- -- The latest version of this file can be found at: -- http://www.opencores.org/cvsweb.shtml/t80/ -- -- Limitations : -- -- File history : -- -- 0208 : First complete release -- -- 0210 : Fixed wait and halt -- -- 0211 : Fixed Refresh addition and IM 1 -- -- 0214 : Fixed mostly flags, only the block instructions now fail the zex regression test -- -- 0232 : Removed refresh address output for Mode > 1 and added DJNZ M1_n fix by Mike Johnson -- -- 0235 : Added clock enable and IM 2 fix by Mike Johnson -- -- 0237 : Changed 8080 I/O address output, added IntE output -- -- 0238 : Fixed (IX/IY+d) timing and 16 bit ADC and SBC zero flag -- -- 0240 : Added interrupt ack fix by Mike Johnson, changed (IX/IY+d) timing and changed flags in GB mode -- -- 0242 : Added I/O wait, fixed refresh address, moved some registers to RAM -- -- 0247 : Fixed bus req/ack cycle -- library IEEE; use IEEE.std_logic_1164.all; use IEEE.numeric_std.all; use work.T80_Pack.all; entity T80 is generic( Mode : integer := 0; -- 0 => Z80, 1 => Fast Z80, 2 => 8080, 3 => GB IOWait : integer := 0; -- 1 => Single cycle I/O, 1 => Std I/O cycle Flag_C : integer := 0; Flag_N : integer := 1; Flag_P : integer := 2; Flag_X : integer := 3; Flag_H : integer := 4; Flag_Y : integer := 5; Flag_Z : integer := 6; Flag_S : integer := 7 ); port( RESET_n : in std_logic; CLK_n : in std_logic; CEN : in std_logic; WAIT_n : in std_logic; INT_n : in std_logic; NMI_n : in std_logic; BUSRQ_n : in std_logic; M1_n : out std_logic; IORQ : out std_logic; NoRead : out std_logic; Write : out std_logic; RFSH_n : out std_logic; HALT_n : out std_logic; BUSAK_n : out std_logic; A : out std_logic_vector(15 downto 0); DInst : in std_logic_vector(7 downto 0); DI : in std_logic_vector(7 downto 0); DO : out std_logic_vector(7 downto 0); MC : out std_logic_vector(2 downto 0); TS : out std_logic_vector(2 downto 0); IntCycle_n : out std_logic; IntE : out std_logic; Stop : out std_logic ); end T80; architecture rtl of T80 is constant aNone : std_logic_vector(2 downto 0) := "111"; constant aBC : std_logic_vector(2 downto 0) := "000"; constant aDE : std_logic_vector(2 downto 0) := "001"; constant aXY : std_logic_vector(2 downto 0) := "010"; constant aIOA : std_logic_vector(2 downto 0) := "100"; constant aSP : std_logic_vector(2 downto 0) := "101"; constant aZI : std_logic_vector(2 downto 0) := "110"; -- Registers signal ACC, F : std_logic_vector(7 downto 0); signal Ap, Fp : std_logic_vector(7 downto 0); signal I : std_logic_vector(7 downto 0); signal R : unsigned(7 downto 0); signal SP, PC : unsigned(15 downto 0); signal RegDIH : std_logic_vector(7 downto 0); signal RegDIL : std_logic_vector(7 downto 0); signal RegBusA : std_logic_vector(15 downto 0); signal RegBusB : std_logic_vector(15 downto 0); signal RegBusC : std_logic_vector(15 downto 0); signal RegAddrA_r : std_logic_vector(2 downto 0); signal RegAddrA : std_logic_vector(2 downto 0); signal RegAddrB_r : std_logic_vector(2 downto 0); signal RegAddrB : std_logic_vector(2 downto 0); signal RegAddrC : std_logic_vector(2 downto 0); signal RegWEH : std_logic; signal RegWEL : std_logic; signal Alternate : std_logic; -- Help Registers signal TmpAddr : std_logic_vector(15 downto 0); -- Temporary address register signal IR : std_logic_vector(7 downto 0); -- Instruction register signal ISet : std_logic_vector(1 downto 0); -- Instruction set selector signal RegBusA_r : std_logic_vector(15 downto 0); signal ID16 : signed(15 downto 0); signal Save_Mux : std_logic_vector(7 downto 0); signal TState : unsigned(2 downto 0); signal MCycle : std_logic_vector(2 downto 0); signal IntE_FF1 : std_logic; signal IntE_FF2 : std_logic; signal Halt_FF : std_logic; signal BusReq_s : std_logic; signal BusAck : std_logic; signal ClkEn : std_logic; signal NMI_s : std_logic; signal INT_s : std_logic; signal IStatus : std_logic_vector(1 downto 0); signal DI_Reg : std_logic_vector(7 downto 0); signal T_Res : std_logic; signal XY_State : std_logic_vector(1 downto 0); signal Pre_XY_F_M : std_logic_vector(2 downto 0); signal NextIs_XY_Fetch : std_logic; signal XY_Ind : std_logic; signal No_BTR : std_logic; signal BTR_r : std_logic; signal Auto_Wait : std_logic; signal Auto_Wait_t1 : std_logic; signal Auto_Wait_t2 : std_logic; signal IncDecZ : std_logic; -- ALU signals signal BusB : std_logic_vector(7 downto 0); signal BusA : std_logic_vector(7 downto 0); signal ALU_Q : std_logic_vector(7 downto 0); signal F_Out : std_logic_vector(7 downto 0); -- Registered micro code outputs signal Read_To_Reg_r : std_logic_vector(4 downto 0); signal Arith16_r : std_logic; signal Z16_r : std_logic; signal ALU_Op_r : std_logic_vector(3 downto 0); signal Save_ALU_r : std_logic; signal PreserveC_r : std_logic; signal MCycles : std_logic_vector(2 downto 0); -- Micro code outputs signal MCycles_d : std_logic_vector(2 downto 0); signal TStates : std_logic_vector(2 downto 0); signal IntCycle : std_logic; signal NMICycle : std_logic; signal Inc_PC : std_logic; signal Inc_WZ : std_logic; signal IncDec_16 : std_logic_vector(3 downto 0); signal Prefix : std_logic_vector(1 downto 0); signal Read_To_Acc : std_logic; signal Read_To_Reg : std_logic; signal Set_BusB_To : std_logic_vector(3 downto 0); signal Set_BusA_To : std_logic_vector(3 downto 0); signal ALU_Op : std_logic_vector(3 downto 0); signal Save_ALU : std_logic; signal PreserveC : std_logic; signal Arith16 : std_logic; signal Set_Addr_To : std_logic_vector(2 downto 0); signal Jump : std_logic; signal JumpE : std_logic; signal JumpXY : std_logic; signal Call : std_logic; signal RstP : std_logic; signal LDZ : std_logic; signal LDW : std_logic; signal LDSPHL : std_logic; signal IORQ_i : std_logic; signal Special_LD : std_logic_vector(2 downto 0); signal ExchangeDH : std_logic; signal ExchangeRp : std_logic; signal ExchangeAF : std_logic; signal ExchangeRS : std_logic; signal I_DJNZ : std_logic; signal I_CPL : std_logic; signal I_CCF : std_logic; signal I_SCF : std_logic; signal I_RETN : std_logic; signal I_BT : std_logic; signal I_BC : std_logic; signal I_BTR : std_logic; signal I_RLD : std_logic; signal I_RRD : std_logic; signal I_INRC : std_logic; signal SetDI : std_logic; signal SetEI : std_logic; signal IMode : std_logic_vector(1 downto 0); signal Halt : std_logic; begin mcode : T80_MCode generic map( Mode => Mode, Flag_C => Flag_C, Flag_N => Flag_N, Flag_P => Flag_P, Flag_X => Flag_X, Flag_H => Flag_H, Flag_Y => Flag_Y, Flag_Z => Flag_Z, Flag_S => Flag_S) port map( IR => IR, ISet => ISet, MCycle => MCycle, F => F, NMICycle => NMICycle, IntCycle => IntCycle, MCycles => MCycles_d, TStates => TStates, Prefix => Prefix, Inc_PC => Inc_PC, Inc_WZ => Inc_WZ, IncDec_16 => IncDec_16, Read_To_Acc => Read_To_Acc, Read_To_Reg => Read_To_Reg, Set_BusB_To => Set_BusB_To, Set_BusA_To => Set_BusA_To, ALU_Op => ALU_Op, Save_ALU => Save_ALU, PreserveC => PreserveC, Arith16 => Arith16, Set_Addr_To => Set_Addr_To, IORQ => IORQ_i, Jump => Jump, JumpE => JumpE, JumpXY => JumpXY, Call => Call, RstP => RstP, LDZ => LDZ, LDW => LDW, LDSPHL => LDSPHL, Special_LD => Special_LD, ExchangeDH => ExchangeDH, ExchangeRp => ExchangeRp, ExchangeAF => ExchangeAF, ExchangeRS => ExchangeRS, I_DJNZ => I_DJNZ, I_CPL => I_CPL, I_CCF => I_CCF, I_SCF => I_SCF, I_RETN => I_RETN, I_BT => I_BT, I_BC => I_BC, I_BTR => I_BTR, I_RLD => I_RLD, I_RRD => I_RRD, I_INRC => I_INRC, SetDI => SetDI, SetEI => SetEI, IMode => IMode, Halt => Halt, NoRead => NoRead, Write => Write); alu : T80_ALU generic map( Mode => Mode, Flag_C => Flag_C, Flag_N => Flag_N, Flag_P => Flag_P, Flag_X => Flag_X, Flag_H => Flag_H, Flag_Y => Flag_Y, Flag_Z => Flag_Z, Flag_S => Flag_S) port map( Arith16 => Arith16_r, Z16 => Z16_r, ALU_Op => ALU_Op_r, IR => IR(5 downto 0), ISet => ISet, BusA => BusA, BusB => BusB, F_In => F, Q => ALU_Q, F_Out => F_Out); ClkEn <= CEN and not BusAck; T_Res <= '1' when TState = unsigned(TStates) else '0'; NextIs_XY_Fetch <= '1' when XY_State /= "00" and XY_Ind = '0' and ((Set_Addr_To = aXY) or (MCycle = "001" and IR = "11001011") or (MCycle = "001" and IR = "00110110")) else '0'; Save_Mux <= BusB when ExchangeRp = '1' else DI_Reg when Save_ALU_r = '0' else ALU_Q; process (RESET_n, CLK_n) begin if RESET_n = '0' then PC <= (others => '0'); -- Program Counter A <= (others => '0'); TmpAddr <= (others => '0'); IR <= "00000000"; ISet <= "00"; XY_State <= "00"; IStatus <= "00"; MCycles <= "000"; DO <= "00000000"; ACC <= (others => '1'); F <= (others => '1'); Ap <= (others => '1'); Fp <= (others => '1'); I <= (others => '0'); R <= (others => '0'); SP <= (others => '1'); Alternate <= '0'; Read_To_Reg_r <= "00000"; F <= (others => '1'); Arith16_r <= '0'; BTR_r <= '0'; Z16_r <= '0'; ALU_Op_r <= "0000"; Save_ALU_r <= '0'; PreserveC_r <= '0'; XY_Ind <= '0'; elsif CLK_n'event and CLK_n = '1' then if ClkEn = '1' then ALU_Op_r <= "0000"; Save_ALU_r <= '0'; Read_To_Reg_r <= "00000"; MCycles <= MCycles_d; if IMode /= "11" then IStatus <= IMode; end if; Arith16_r <= Arith16; PreserveC_r <= PreserveC; if ISet = "10" and ALU_OP(2) = '0' and ALU_OP(0) = '1' and MCycle = "011" then Z16_r <= '1'; else Z16_r <= '0'; end if; if MCycle = "001" and TState(2) = '0' then -- MCycle = 1 and TState = 1, 2, or 3 if TState = 2 and Wait_n = '1' then if Mode < 2 then A(7 downto 0) <= std_logic_vector(R); A(15 downto 8) <= I; R(6 downto 0) <= R(6 downto 0) + 1; end if; if Jump = '0' and Call = '0' and NMICycle = '0' and IntCycle = '0' and not (Halt_FF = '1' or Halt = '1') then PC <= PC + 1; end if; if IntCycle = '1' and IStatus = "01" then IR <= "11111111"; elsif Halt_FF = '1' or (IntCycle = '1' and IStatus = "10") or NMICycle = '1' then IR <= "00000000"; else IR <= DInst; end if; ISet <= "00"; if Prefix /= "00" then if Prefix = "11" then if IR(5) = '1' then XY_State <= "10"; else XY_State <= "01"; end if; else if Prefix = "10" then XY_State <= "00"; XY_Ind <= '0'; end if; ISet <= Prefix; end if; else XY_State <= "00"; XY_Ind <= '0'; end if; end if; else -- either (MCycle > 1) OR (MCycle = 1 AND TState > 3) if MCycle = "110" then XY_Ind <= '1'; if Prefix = "01" then ISet <= "01"; end if; end if; if T_Res = '1' then BTR_r <= (I_BT or I_BC or I_BTR) and not No_BTR; if Jump = '1' then A(15 downto 8) <= DI_Reg; A(7 downto 0) <= TmpAddr(7 downto 0); PC(15 downto 8) <= unsigned(DI_Reg); PC(7 downto 0) <= unsigned(TmpAddr(7 downto 0)); elsif JumpXY = '1' then A <= RegBusC; PC <= unsigned(RegBusC); elsif Call = '1' or RstP = '1' then A <= TmpAddr; PC <= unsigned(TmpAddr); elsif MCycle = MCycles and NMICycle = '1' then A <= "0000000001100110"; PC <= "0000000001100110"; elsif MCycle = "011" and IntCycle = '1' and IStatus = "10" then A(15 downto 8) <= I; A(7 downto 0) <= TmpAddr(7 downto 0); PC(15 downto 8) <= unsigned(I); PC(7 downto 0) <= unsigned(TmpAddr(7 downto 0)); else case Set_Addr_To is when aXY => if XY_State = "00" then A <= RegBusC; else if NextIs_XY_Fetch = '1' then A <= std_logic_vector(PC); else A <= TmpAddr; end if; end if; when aIOA => if Mode = 3 then -- Memory map I/O on GBZ80 A(15 downto 8) <= (others => '1'); elsif Mode = 2 then -- Duplicate I/O address on 8080 A(15 downto 8) <= DI_Reg; else A(15 downto 8) <= ACC; end if; A(7 downto 0) <= DI_Reg; when aSP => A <= std_logic_vector(SP); when aBC => if Mode = 3 and IORQ_i = '1' then -- Memory map I/O on GBZ80 A(15 downto 8) <= (others => '1'); A(7 downto 0) <= RegBusC(7 downto 0); else A <= RegBusC; end if; when aDE => A <= RegBusC; when aZI => if Inc_WZ = '1' then A <= std_logic_vector(unsigned(TmpAddr) + 1); else A(15 downto 8) <= DI_Reg; A(7 downto 0) <= TmpAddr(7 downto 0); end if; when others => A <= std_logic_vector(PC); end case; end if; Save_ALU_r <= Save_ALU; ALU_Op_r <= ALU_Op; if I_CPL = '1' then -- CPL ACC <= not ACC; F(Flag_Y) <= not ACC(5); F(Flag_H) <= '1'; F(Flag_X) <= not ACC(3); F(Flag_N) <= '1'; end if; if I_CCF = '1' then -- CCF F(Flag_C) <= not F(Flag_C); F(Flag_Y) <= ACC(5); F(Flag_H) <= F(Flag_C); F(Flag_X) <= ACC(3); F(Flag_N) <= '0'; end if; if I_SCF = '1' then -- SCF F(Flag_C) <= '1'; F(Flag_Y) <= ACC(5); F(Flag_H) <= '0'; F(Flag_X) <= ACC(3); F(Flag_N) <= '0'; end if; end if; if TState = 2 and Wait_n = '1' then if ISet = "01" and MCycle = "111" then IR <= DInst; end if; if JumpE = '1' then PC <= unsigned(signed(PC) + signed(DI_Reg)); elsif Inc_PC = '1' then PC <= PC + 1; end if; if BTR_r = '1' then PC <= PC - 2; end if; if RstP = '1' then TmpAddr <= (others =>'0'); TmpAddr(5 downto 3) <= IR(5 downto 3); end if; end if; if TState = 3 and MCycle = "110" then TmpAddr <= std_logic_vector(signed(RegBusC) + signed(DI_Reg)); end if; if (TState = 2 and Wait_n = '1') or (TState = 4 and MCycle = "001") then if IncDec_16(2 downto 0) = "111" then if IncDec_16(3) = '1' then SP <= SP - 1; else SP <= SP + 1; end if; end if; end if; if LDSPHL = '1' then SP <= unsigned(RegBusC); end if; if ExchangeAF = '1' then Ap <= ACC; ACC <= Ap; Fp <= F; F <= Fp; end if; if ExchangeRS = '1' then Alternate <= not Alternate; end if; end if; if TState = 3 then if LDZ = '1' then TmpAddr(7 downto 0) <= DI_Reg; end if; if LDW = '1' then TmpAddr(15 downto 8) <= DI_Reg; end if; if Special_LD(2) = '1' then case Special_LD(1 downto 0) is when "00" => ACC <= I; F(Flag_P) <= IntE_FF2; when "01" => ACC <= std_logic_vector(R); F(Flag_P) <= IntE_FF2; when "10" => I <= ACC; when others => R <= unsigned(ACC); end case; end if; end if; if (I_DJNZ = '0' and Save_ALU_r = '1') or ALU_Op_r = "1001" then if Mode = 3 then F(6) <= F_Out(6); F(5) <= F_Out(5); F(7) <= F_Out(7); if PreserveC_r = '0' then F(4) <= F_Out(4); end if; else F(7 downto 1) <= F_Out(7 downto 1); if PreserveC_r = '0' then F(Flag_C) <= F_Out(0); end if; end if; end if; if T_Res = '1' and I_INRC = '1' then F(Flag_H) <= '0'; F(Flag_N) <= '0'; if DI_Reg(7 downto 0) = "00000000" then F(Flag_Z) <= '1'; else F(Flag_Z) <= '0'; end if; F(Flag_S) <= DI_Reg(7); F(Flag_P) <= not (DI_Reg(0) xor DI_Reg(1) xor DI_Reg(2) xor DI_Reg(3) xor DI_Reg(4) xor DI_Reg(5) xor DI_Reg(6) xor DI_Reg(7)); end if; if TState = 1 and Auto_Wait_t1 = '0' then DO <= BusB; if I_RLD = '1' then DO(3 downto 0) <= BusA(3 downto 0); DO(7 downto 4) <= BusB(3 downto 0); end if; if I_RRD = '1' then DO(3 downto 0) <= BusB(7 downto 4); DO(7 downto 4) <= BusA(3 downto 0); end if; end if; if T_Res = '1' then Read_To_Reg_r(3 downto 0) <= Set_BusA_To; Read_To_Reg_r(4) <= Read_To_Reg; if Read_To_Acc = '1' then Read_To_Reg_r(3 downto 0) <= "0111"; Read_To_Reg_r(4) <= '1'; end if; end if; if TState = 1 and I_BT = '1' then F(Flag_X) <= ALU_Q(3); F(Flag_Y) <= ALU_Q(1); F(Flag_H) <= '0'; F(Flag_N) <= '0'; end if; if I_BC = '1' or I_BT = '1' then F(Flag_P) <= IncDecZ; end if; if (TState = 1 and Save_ALU_r = '0' and Auto_Wait_t1 = '0') or (Save_ALU_r = '1' and ALU_OP_r /= "0111") then case Read_To_Reg_r is when "10111" => ACC <= Save_Mux; when "10110" => DO <= Save_Mux; when "11000" => SP(7 downto 0) <= unsigned(Save_Mux); when "11001" => SP(15 downto 8) <= unsigned(Save_Mux); when "11011" => F <= Save_Mux; when others => end case; end if; end if; end if; end process; --------------------------------------------------------------------------- -- -- BC('), DE('), HL('), IX and IY -- --------------------------------------------------------------------------- process (CLK_n) begin if CLK_n'event and CLK_n = '1' then if ClkEn = '1' then -- Bus A / Write RegAddrA_r <= Alternate & Set_BusA_To(2 downto 1); if XY_Ind = '0' and XY_State /= "00" and Set_BusA_To(2 downto 1) = "10" then RegAddrA_r <= XY_State(1) & "11"; end if; -- Bus B RegAddrB_r <= Alternate & Set_BusB_To(2 downto 1); if XY_Ind = '0' and XY_State /= "00" and Set_BusB_To(2 downto 1) = "10" then RegAddrB_r <= XY_State(1) & "11"; end if; -- Address from register RegAddrC <= Alternate & Set_Addr_To(1 downto 0); -- Jump (HL), LD SP,HL if (JumpXY = '1' or LDSPHL = '1') then RegAddrC <= Alternate & "10"; end if; if ((JumpXY = '1' or LDSPHL = '1') and XY_State /= "00") or (MCycle = "110") then RegAddrC <= XY_State(1) & "11"; end if; if I_DJNZ = '1' and Save_ALU_r = '1' and Mode < 2 then IncDecZ <= F_Out(Flag_Z); end if; if (TState = 2 or (TState = 3 and MCycle = "001")) and IncDec_16(2 downto 0) = "100" then if ID16 = 0 then IncDecZ <= '0'; else IncDecZ <= '1'; end if; end if; RegBusA_r <= RegBusA; end if; end if; end process; RegAddrA <= -- 16 bit increment/decrement Alternate & IncDec_16(1 downto 0) when (TState = 2 or (TState = 3 and MCycle = "001" and IncDec_16(2) = '1')) and XY_State = "00" else XY_State(1) & "11" when (TState = 2 or (TState = 3 and MCycle = "001" and IncDec_16(2) = '1')) and IncDec_16(1 downto 0) = "10" else -- EX HL,DL Alternate & "10" when ExchangeDH = '1' and TState = 3 else Alternate & "01" when ExchangeDH = '1' and TState = 4 else -- Bus A / Write RegAddrA_r; RegAddrB <= -- EX HL,DL Alternate & "01" when ExchangeDH = '1' and TState = 3 else -- Bus B RegAddrB_r; ID16 <= signed(RegBusA) - 1 when IncDec_16(3) = '1' else signed(RegBusA) + 1; process (Save_ALU_r, Auto_Wait_t1, ALU_OP_r, Read_To_Reg_r, ExchangeDH, IncDec_16, MCycle, TState, Wait_n) begin RegWEH <= '0'; RegWEL <= '0'; if (TState = 1 and Save_ALU_r = '0' and Auto_Wait_t1 = '0') or (Save_ALU_r = '1' and ALU_OP_r /= "0111") then case Read_To_Reg_r is when "10000" | "10001" | "10010" | "10011" | "10100" | "10101" => RegWEH <= not Read_To_Reg_r(0); RegWEL <= Read_To_Reg_r(0); when others => end case; end if; if ExchangeDH = '1' and (TState = 3 or TState = 4) then RegWEH <= '1'; RegWEL <= '1'; end if; if IncDec_16(2) = '1' and ((TState = 2 and Wait_n = '1' and MCycle /= "001") or (TState = 3 and MCycle = "001")) then case IncDec_16(1 downto 0) is when "00" | "01" | "10" => RegWEH <= '1'; RegWEL <= '1'; when others => end case; end if; end process; process (Save_Mux, RegBusB, RegBusA_r, ID16, ExchangeDH, IncDec_16, MCycle, TState, Wait_n) begin RegDIH <= Save_Mux; RegDIL <= Save_Mux; if ExchangeDH = '1' and TState = 3 then RegDIH <= RegBusB(15 downto 8); RegDIL <= RegBusB(7 downto 0); end if; if ExchangeDH = '1' and TState = 4 then RegDIH <= RegBusA_r(15 downto 8); RegDIL <= RegBusA_r(7 downto 0); end if; if IncDec_16(2) = '1' and ((TState = 2 and MCycle /= "001") or (TState = 3 and MCycle = "001")) then RegDIH <= std_logic_vector(ID16(15 downto 8)); RegDIL <= std_logic_vector(ID16(7 downto 0)); end if; end process; Regs : T80_Reg port map( Clk => CLK_n, CEN => ClkEn, WEH => RegWEH, WEL => RegWEL, AddrA => RegAddrA, AddrB => RegAddrB, AddrC => RegAddrC, DIH => RegDIH, DIL => RegDIL, DOAH => RegBusA(15 downto 8), DOAL => RegBusA(7 downto 0), DOBH => RegBusB(15 downto 8), DOBL => RegBusB(7 downto 0), DOCH => RegBusC(15 downto 8), DOCL => RegBusC(7 downto 0)); --------------------------------------------------------------------------- -- -- Buses -- --------------------------------------------------------------------------- process (CLK_n) begin if CLK_n'event and CLK_n = '1' then if ClkEn = '1' then case Set_BusB_To is when "0111" => BusB <= ACC; when "0000" | "0001" | "0010" | "0011" | "0100" | "0101" => if Set_BusB_To(0) = '1' then BusB <= RegBusB(7 downto 0); else BusB <= RegBusB(15 downto 8); end if; when "0110" => BusB <= DI_Reg; when "1000" => BusB <= std_logic_vector(SP(7 downto 0)); when "1001" => BusB <= std_logic_vector(SP(15 downto 8)); when "1010" => BusB <= "00000001"; when "1011" => BusB <= F; when "1100" => BusB <= std_logic_vector(PC(7 downto 0)); when "1101" => BusB <= std_logic_vector(PC(15 downto 8)); when "1110" => BusB <= "00000000"; when others => BusB <= "--------"; end case; case Set_BusA_To is when "0111" => BusA <= ACC; when "0000" | "0001" | "0010" | "0011" | "0100" | "0101" => if Set_BusA_To(0) = '1' then BusA <= RegBusA(7 downto 0); else BusA <= RegBusA(15 downto 8); end if; when "0110" => BusA <= DI_Reg; when "1000" => BusA <= std_logic_vector(SP(7 downto 0)); when "1001" => BusA <= std_logic_vector(SP(15 downto 8)); when "1010" => BusA <= "00000000"; when others => BusB <= "--------"; end case; end if; end if; end process; --------------------------------------------------------------------------- -- -- Generate external control signals -- --------------------------------------------------------------------------- process (RESET_n,CLK_n) begin if RESET_n = '0' then RFSH_n <= '1'; elsif CLK_n'event and CLK_n = '1' then if CEN = '1' then if MCycle = "001" and ((TState = 2 and Wait_n = '1') or TState = 3) then RFSH_n <= '0'; else RFSH_n <= '1'; end if; end if; end if; end process; MC <= std_logic_vector(MCycle); TS <= std_logic_vector(TState); DI_Reg <= DI; HALT_n <= not Halt_FF; BUSAK_n <= not BusAck; IntCycle_n <= not IntCycle; IntE <= IntE_FF1; IORQ <= IORQ_i; Stop <= I_DJNZ; ------------------------------------------------------------------------- -- -- Syncronise inputs -- ------------------------------------------------------------------------- process (RESET_n, CLK_n) variable OldNMI_n : std_logic; begin if RESET_n = '0' then BusReq_s <= '0'; INT_s <= '0'; NMI_s <= '0'; OldNMI_n := '0'; elsif CLK_n'event and CLK_n = '1' then if CEN = '1' then BusReq_s <= not BUSRQ_n; INT_s <= not INT_n; if NMICycle = '1' then NMI_s <= '0'; elsif NMI_n = '0' and OldNMI_n = '1' then NMI_s <= '1'; end if; OldNMI_n := NMI_n; end if; end if; end process; ------------------------------------------------------------------------- -- -- Main state machine -- ------------------------------------------------------------------------- process (RESET_n, CLK_n) begin if RESET_n = '0' then MCycle <= "001"; TState <= "000"; Pre_XY_F_M <= "000"; Halt_FF <= '0'; BusAck <= '0'; NMICycle <= '0'; IntCycle <= '0'; IntE_FF1 <= '0'; IntE_FF2 <= '0'; No_BTR <= '0'; Auto_Wait_t1 <= '0'; Auto_Wait_t2 <= '0'; M1_n <= '1'; elsif CLK_n'event and CLK_n = '1' then if CEN = '1' then if T_Res = '1' then Auto_Wait_t1 <= '0'; else Auto_Wait_t1 <= Auto_Wait or IORQ_i; end if; Auto_Wait_t2 <= Auto_Wait_t1; No_BTR <= (I_BT and (not IR(4) or not F(Flag_P))) or (I_BC and (not IR(4) or F(Flag_Z) or not F(Flag_P))) or (I_BTR and (not IR(4) or F(Flag_Z))); if TState = 2 then if SetEI = '1' then IntE_FF1 <= '1'; IntE_FF2 <= '1'; end if; if I_RETN = '1' then IntE_FF1 <= IntE_FF2; end if; end if; if TState = 3 then if SetDI = '1' then IntE_FF1 <= '0'; IntE_FF2 <= '0'; end if; end if; if IntCycle = '1' or NMICycle = '1' then Halt_FF <= '0'; end if; if MCycle = "001" and TState = 2 and Wait_n = '1' then M1_n <= '1'; end if; if BusReq_s = '1' and BusAck = '1' then else BusAck <= '0'; if TState = 2 and Wait_n = '0' then elsif T_Res = '1' then if Halt = '1' then Halt_FF <= '1'; end if; if BusReq_s = '1' then BusAck <= '1'; else TState <= "001"; if NextIs_XY_Fetch = '1' then MCycle <= "110"; Pre_XY_F_M <= MCycle; if IR = "00110110" and Mode = 0 then Pre_XY_F_M <= "010"; end if; elsif (MCycle = "111") or (MCycle = "110" and Mode = 1 and ISet /= "01") then MCycle <= std_logic_vector(unsigned(Pre_XY_F_M) + 1); elsif (MCycle = MCycles) or No_BTR = '1' or (MCycle = "010" and I_DJNZ = '1' and IncDecZ = '1') then M1_n <= '0'; MCycle <= "001"; IntCycle <= '0'; NMICycle <= '0'; if NMI_s = '1' and Prefix = "00" then NMICycle <= '1'; IntE_FF1 <= '0'; elsif (IntE_FF1 = '1' and INT_s = '1') and Prefix = "00" and SetEI = '0' then IntCycle <= '1'; IntE_FF1 <= '0'; IntE_FF2 <= '0'; end if; else MCycle <= std_logic_vector(unsigned(MCycle) + 1); end if; end if; else if (Auto_Wait = '1' and Auto_Wait_t2 = '0') nor (IOWait = 1 and IORQ_i = '1' and Auto_Wait_t1 = '0') then TState <= TState + 1; end if; end if; end if; if TState = 0 then M1_n <= '0'; end if; end if; end if; end process; process (IntCycle, NMICycle, MCycle) begin Auto_Wait <= '0'; if IntCycle = '1' or NMICycle = '1' then if MCycle = "001" then Auto_Wait <= '1'; end if; end if; end process; end;
zx-simi
trunk/fpga/t80/trunk/rtl/vhdl/T80.vhd
VHDL
oos
28,911
-- -- Z80 compatible microprocessor core, synchronous top level -- Different timing than the original z80 -- Inputs needs to be synchronous and outputs may glitch -- -- Version : 0242 -- -- Copyright (c) 2001-2002 Daniel Wallner (jesus@opencores.org) -- -- All rights reserved -- -- Redistribution and use in source and synthezised 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 synthesized 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 author nor the names of other 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 AUTHOR 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. -- -- Please report bugs to the author, but before you do so, please -- make sure that this is not a derivative work and that -- you have the latest version of this file. -- -- The latest version of this file can be found at: -- http://www.opencores.org/cvsweb.shtml/t80/ -- -- Limitations : -- -- File history : -- -- 0208 : First complete release -- -- 0210 : Fixed read with wait -- -- 0211 : Fixed interrupt cycle -- -- 0235 : Updated for T80 interface change -- -- 0236 : Added T2Write generic -- -- 0237 : Fixed T2Write with wait state -- -- 0238 : Updated for T80 interface change -- -- 0240 : Updated for T80 interface change -- -- 0242 : Updated for T80 interface change -- library IEEE; use IEEE.std_logic_1164.all; use IEEE.numeric_std.all; use work.T80_Pack.all; entity T80s is generic( Mode : integer := 0; -- 0 => Z80, 1 => Fast Z80, 2 => 8080, 3 => GB T2Write : integer := 0; -- 0 => WR_n active in T3, /=0 => WR_n active in T2 IOWait : integer := 1 -- 0 => Single cycle I/O, 1 => Std I/O cycle ); port( RESET_n : in std_logic; CLK_n : in std_logic; WAIT_n : in std_logic; INT_n : in std_logic; NMI_n : in std_logic; BUSRQ_n : in std_logic; M1_n : out std_logic; MREQ_n : out std_logic; IORQ_n : out std_logic; RD_n : out std_logic; WR_n : out std_logic; RFSH_n : out std_logic; HALT_n : out std_logic; BUSAK_n : out std_logic; A : out std_logic_vector(15 downto 0); DI : in std_logic_vector(7 downto 0); DO : out std_logic_vector(7 downto 0) ); end T80s; architecture rtl of T80s is signal CEN : std_logic; signal IntCycle_n : std_logic; signal NoRead : std_logic; signal Write : std_logic; signal IORQ : std_logic; signal DI_Reg : std_logic_vector(7 downto 0); signal MCycle : std_logic_vector(2 downto 0); signal TState : std_logic_vector(2 downto 0); begin CEN <= '1'; u0 : T80 generic map( Mode => Mode, IOWait => IOWait) port map( CEN => CEN, M1_n => M1_n, IORQ => IORQ, NoRead => NoRead, Write => Write, RFSH_n => RFSH_n, HALT_n => HALT_n, WAIT_n => Wait_n, INT_n => INT_n, NMI_n => NMI_n, RESET_n => RESET_n, BUSRQ_n => BUSRQ_n, BUSAK_n => BUSAK_n, CLK_n => CLK_n, A => A, DInst => DI, DI => DI_Reg, DO => DO, MC => MCycle, TS => TState, IntCycle_n => IntCycle_n); process (RESET_n, CLK_n) begin if RESET_n = '0' then RD_n <= '1'; WR_n <= '1'; IORQ_n <= '1'; MREQ_n <= '1'; DI_Reg <= "00000000"; elsif CLK_n'event and CLK_n = '1' then RD_n <= '1'; WR_n <= '1'; IORQ_n <= '1'; MREQ_n <= '1'; if MCycle = "001" then if TState = "001" or (TState = "010" and Wait_n = '0') then RD_n <= not IntCycle_n; MREQ_n <= not IntCycle_n; IORQ_n <= IntCycle_n; end if; if TState = "011" then MREQ_n <= '0'; end if; else if (TState = "001" or (TState = "010" and Wait_n = '0')) and NoRead = '0' and Write = '0' then RD_n <= '0'; IORQ_n <= not IORQ; MREQ_n <= IORQ; end if; if T2Write = 0 then if TState = "010" and Write = '1' then WR_n <= '0'; IORQ_n <= not IORQ; MREQ_n <= IORQ; end if; else if (TState = "001" or (TState = "010" and Wait_n = '0')) and Write = '1' then WR_n <= '0'; IORQ_n <= not IORQ; MREQ_n <= IORQ; end if; end if; end if; if TState = "010" and Wait_n = '1' then DI_Reg <= DI; end if; end if; end process; end;
zx-simi
trunk/fpga/t80/trunk/rtl/vhdl/T80s.vhd
VHDL
oos
5,249
-- -- 8080 compatible microprocessor core, synchronous top level with clock enable -- Different timing than the original 8080 -- Inputs needs to be synchronous and outputs may glitch -- -- Version : 0242 -- -- Copyright (c) 2002 Daniel Wallner (jesus@opencores.org) -- -- All rights reserved -- -- Redistribution and use in source and synthezised 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 synthesized 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 author nor the names of other 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 AUTHOR 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. -- -- Please report bugs to the author, but before you do so, please -- make sure that this is not a derivative work and that -- you have the latest version of this file. -- -- The latest version of this file can be found at: -- http://www.opencores.org/cvsweb.shtml/t80/ -- -- Limitations : -- STACK status output not supported -- -- File history : -- -- 0237 : First version -- -- 0238 : Updated for T80 interface change -- -- 0240 : Updated for T80 interface change -- -- 0242 : Updated for T80 interface change -- library IEEE; use IEEE.std_logic_1164.all; use IEEE.numeric_std.all; use work.T80_Pack.all; entity T8080se is generic( Mode : integer := 2; -- 0 => Z80, 1 => Fast Z80, 2 => 8080, 3 => GB T2Write : integer := 0 -- 0 => WR_n active in T3, /=0 => WR_n active in T2 ); port( RESET_n : in std_logic; CLK : in std_logic; CLKEN : in std_logic; READY : in std_logic; HOLD : in std_logic; INT : in std_logic; INTE : out std_logic; DBIN : out std_logic; SYNC : out std_logic; VAIT : out std_logic; HLDA : out std_logic; WR_n : out std_logic; A : out std_logic_vector(15 downto 0); DI : in std_logic_vector(7 downto 0); DO : out std_logic_vector(7 downto 0) ); end T8080se; architecture rtl of T8080se is signal IntCycle_n : std_logic; signal NoRead : std_logic; signal Write : std_logic; signal IORQ : std_logic; signal INT_n : std_logic; signal HALT_n : std_logic; signal BUSRQ_n : std_logic; signal BUSAK_n : std_logic; signal DO_i : std_logic_vector(7 downto 0); signal DI_Reg : std_logic_vector(7 downto 0); signal MCycle : std_logic_vector(2 downto 0); signal TState : std_logic_vector(2 downto 0); signal One : std_logic; begin INT_n <= not INT; BUSRQ_n <= HOLD; HLDA <= not BUSAK_n; SYNC <= '1' when TState = "001" else '0'; VAIT <= '1' when TState = "010" else '0'; One <= '1'; DO(0) <= not IntCycle_n when TState = "001" else DO_i(0); -- INTA DO(1) <= Write when TState = "001" else DO_i(1); -- WO_n DO(2) <= DO_i(2); -- STACK not supported !!!!!!!!!! DO(3) <= not HALT_n when TState = "001" else DO_i(3); -- HLTA DO(4) <= IORQ and Write when TState = "001" else DO_i(4); -- OUT DO(5) <= DO_i(5) when TState /= "001" else '1' when MCycle = "001" else '0'; -- M1 DO(6) <= IORQ and not Write when TState = "001" else DO_i(6); -- INP DO(7) <= not IORQ and not Write and IntCycle_n when TState = "001" else DO_i(7); -- MEMR u0 : T80 generic map( Mode => Mode, IOWait => 0) port map( CEN => CLKEN, M1_n => open, IORQ => IORQ, NoRead => NoRead, Write => Write, RFSH_n => open, HALT_n => HALT_n, WAIT_n => READY, INT_n => INT_n, NMI_n => One, RESET_n => RESET_n, BUSRQ_n => One, BUSAK_n => BUSAK_n, CLK_n => CLK, A => A, DInst => DI, DI => DI_Reg, DO => DO_i, MC => MCycle, TS => TState, IntCycle_n => IntCycle_n, IntE => INTE); process (RESET_n, CLK) begin if RESET_n = '0' then DBIN <= '0'; WR_n <= '1'; DI_Reg <= "00000000"; elsif CLK'event and CLK = '1' then if CLKEN = '1' then DBIN <= '0'; WR_n <= '1'; if MCycle = "001" then if TState = "001" or (TState = "010" and READY = '0') then DBIN <= IntCycle_n; end if; else if (TState = "001" or (TState = "010" and READY = '0')) and NoRead = '0' and Write = '0' then DBIN <= '1'; end if; if T2Write = 0 then if TState = "010" and Write = '1' then WR_n <= '0'; end if; else if (TState = "001" or (TState = "010" and READY = '0')) and Write = '1' then WR_n <= '0'; end if; end if; end if; if TState = "010" and READY = '1' then DI_Reg <= DI; end if; end if; end if; end process; end;
zx-simi
trunk/fpga/t80/trunk/rtl/vhdl/T8080se.vhd
VHDL
oos
5,549
-- -- Z80 compatible microprocessor core, synchronous top level with clock enable -- Different timing than the original z80 -- Inputs needs to be synchronous and outputs may glitch -- -- Version : 0242 -- -- Copyright (c) 2001-2002 Daniel Wallner (jesus@opencores.org) -- -- All rights reserved -- -- Redistribution and use in source and synthezised 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 synthesized 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 author nor the names of other 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 AUTHOR 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. -- -- Please report bugs to the author, but before you do so, please -- make sure that this is not a derivative work and that -- you have the latest version of this file. -- -- The latest version of this file can be found at: -- http://www.opencores.org/cvsweb.shtml/t80/ -- -- Limitations : -- -- File history : -- -- 0235 : First release -- -- 0236 : Added T2Write generic -- -- 0237 : Fixed T2Write with wait state -- -- 0238 : Updated for T80 interface change -- -- 0240 : Updated for T80 interface change -- -- 0242 : Updated for T80 interface change -- library IEEE; use IEEE.std_logic_1164.all; use IEEE.numeric_std.all; use work.T80_Pack.all; entity T80se is generic( Mode : integer := 0; -- 0 => Z80, 1 => Fast Z80, 2 => 8080, 3 => GB T2Write : integer := 0; -- 0 => WR_n active in T3, /=0 => WR_n active in T2 IOWait : integer := 1 -- 0 => Single cycle I/O, 1 => Std I/O cycle ); port( RESET_n : in std_logic; CLK_n : in std_logic; CLKEN : in std_logic; WAIT_n : in std_logic; INT_n : in std_logic; NMI_n : in std_logic; BUSRQ_n : in std_logic; M1_n : out std_logic; MREQ_n : out std_logic; IORQ_n : out std_logic; RD_n : out std_logic; WR_n : out std_logic; RFSH_n : out std_logic; HALT_n : out std_logic; BUSAK_n : out std_logic; A : out std_logic_vector(15 downto 0); DI : in std_logic_vector(7 downto 0); DO : out std_logic_vector(7 downto 0) ); end T80se; architecture rtl of T80se is signal IntCycle_n : std_logic; signal NoRead : std_logic; signal Write : std_logic; signal IORQ : std_logic; signal DI_Reg : std_logic_vector(7 downto 0); signal MCycle : std_logic_vector(2 downto 0); signal TState : std_logic_vector(2 downto 0); begin u0 : T80 generic map( Mode => Mode, IOWait => IOWait) port map( CEN => CLKEN, M1_n => M1_n, IORQ => IORQ, NoRead => NoRead, Write => Write, RFSH_n => RFSH_n, HALT_n => HALT_n, WAIT_n => Wait_n, INT_n => INT_n, NMI_n => NMI_n, RESET_n => RESET_n, BUSRQ_n => BUSRQ_n, BUSAK_n => BUSAK_n, CLK_n => CLK_n, A => A, DInst => DI, DI => DI_Reg, DO => DO, MC => MCycle, TS => TState, IntCycle_n => IntCycle_n); process (RESET_n, CLK_n) begin if RESET_n = '0' then RD_n <= '1'; WR_n <= '1'; IORQ_n <= '1'; MREQ_n <= '1'; DI_Reg <= "00000000"; elsif CLK_n'event and CLK_n = '1' then if CLKEN = '1' then RD_n <= '1'; WR_n <= '1'; IORQ_n <= '1'; MREQ_n <= '1'; if MCycle = "001" then if TState = "001" or (TState = "010" and Wait_n = '0') then RD_n <= not IntCycle_n; MREQ_n <= not IntCycle_n; IORQ_n <= IntCycle_n; end if; if TState = "011" then MREQ_n <= '0'; end if; else if (TState = "001" or (TState = "010" and Wait_n = '0')) and NoRead = '0' and Write = '0' then RD_n <= '0'; IORQ_n <= not IORQ; MREQ_n <= IORQ; end if; if T2Write = 0 then if TState = "010" and Write = '1' then WR_n <= '0'; IORQ_n <= not IORQ; MREQ_n <= IORQ; end if; else if (TState = "001" or (TState = "010" and Wait_n = '0')) and Write = '1' then WR_n <= '0'; IORQ_n <= not IORQ; MREQ_n <= IORQ; end if; end if; end if; if TState = "010" and Wait_n = '1' then DI_Reg <= DI; end if; end if; end if; end process; end;
zx-simi
trunk/fpga/t80/trunk/rtl/vhdl/T80se.vhd
VHDL
oos
5,202
library IEEE; use ieee.std_logic_1164.ALL; use ieee.std_logic_ARITH.ALL; use ieee.std_logic_UNSIGNED.ALL; entity SPEAKER is port ( CLK : in std_logic; -- vstup z procesoru ADDR : in std_logic_vector(15 downto 0); DATA_IN : in std_logic_vector(7 downto 0); WR : in std_logic; -- vyspuni signal do reproduktoru SPEAKER : out std_logic ); end entity; architecture behav of SPEAKER is begin process(CLK) begin if CLK'event and CLK='1' then if WR='1' then SPEAKER <= DATA_IN(4); end if; end if; end process; end architecture behav;
zx-simi
trunk/fpga/speaker.vhd
VHDL
oos
631
library IEEE; use IEEE.STD_LOGIC_1164.ALL; use IEEE.STD_LOGIC_ARITH.ALL; use IEEE.STD_LOGIC_UNSIGNED.ALL; entity spi is port ( RESET : in std_logic; CLK : in std_logic; -- vstup/vystup DATA_IN : in std_logic_vector(7 downto 0); DATA_OUT : out std_logic_vector(7 downto 0); WRITE_EN : in std_logic; READY : out std_logic; -- SPI rozhrani MOSI : out std_logic; MISO : in std_logic; SCLK : out std_logic ); end spi; architecture Behavioral of spi is signal READY_SIG : std_logic; signal FLASH_CLK : std_logic_vector(3 downto 0); signal FLASH_CLK0 : std_logic; signal DATA_OUT_REG : std_logic_vector(7 downto 0); signal DATA_IN_REG : std_logic_vector(7 downto 0); signal CLK_PAUSE : std_logic; type tstate is (S_WAIT, S_SEND); signal present_state, next_state : tstate; begin DATA_OUT <= DATA_OUT_REG; READY_SIG <= '1' when FLASH_CLK(3 downto 0)="1111" else '0'; FLASH_CLK0 <= FLASH_CLK(0); SCLK <= FLASH_CLK(0); process(present_state,WRITE_EN,READY_SIG) begin CLK_PAUSE <= '1'; READY <= '0'; case present_state is when S_WAIT => READY <= '1'; if WRITE_EN='1' then next_state <= S_SEND; CLK_PAUSE <= '0'; else next_state <= S_WAIT; end if; when S_SEND => if READY_SIG='1' then next_state <= S_WAIT; else next_state <= S_SEND; CLK_PAUSE <= '0'; end if; end case; end process; process(RESET,CLK) begin if RESET='1' then present_state <= S_WAIT; elsif CLK'event and CLK='1' then present_state <= next_state; end if; end process; process(RESET,CLK) begin if RESET='1' then FLASH_CLK <= (others=>'1'); elsif CLK'event and CLK='1' then if CLK_PAUSE='0' then FLASH_CLK <= FLASH_CLK + 1; end if; end if; end process; --vstupni registr process(RESET,CLK) begin if RESET='1' then DATA_IN_REG <= (others=>'0'); elsif CLK'event and CLK='1' then if WRITE_EN='1' then DATA_IN_REG <= DATA_IN; end if; end if; end process; --prepinam na vystup bity datoveho registru with FLASH_CLK(3 downto 1) select MOSI <= DATA_IN_REG(7) when "000", DATA_IN_REG(6) when "001", DATA_IN_REG(5) when "010", DATA_IN_REG(4) when "011", DATA_IN_REG(3) when "100", DATA_IN_REG(2) when "101", DATA_IN_REG(1) when "110", DATA_IN_REG(0) when others; -- prijimani bajtu bit po bitu process(RESET,FLASH_CLK0) begin if RESET='1' then DATA_OUT_REG <= (others=>'0'); elsif FLASH_CLK0'event and FLASH_CLK0='1' then DATA_OUT_REG <= DATA_OUT_REG(6 downto 0) & MISO; end if; end process; end Behavioral;
zx-simi
trunk/fpga/spi.vhd
VHDL
oos
3,503
-- sdram.vhd: SDRAM base controller -- Copyright (C) 2006 Brno University of Technology, -- Faculty of Information Technology -- Author(s): Ladislav Capka <xcapka01 AT stud.fit.vutbr.cz> -- -- LICENSE TERMS -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions -- are met: -- 1. Redistributions of source code must retain the above copyright -- notice, this list of conditions and the following disclaimer. -- 2. 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. -- 3. All advertising materials mentioning features or use of this software -- or firmware must display the following acknowledgement: -- -- This product includes software developed by the University of -- Technology, Faculty of Information Technology, Brno and its -- contributors. -- -- 4. Neither the name of the Company 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 or firmware is provided ``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 company 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. -- -- $Id$ -- -- library ieee; use ieee.std_logic_1164.all; use ieee.std_logic_arith.all; use ieee.std_logic_unsigned.all; use work.sdram_controller_cfg.all; -- SYNTH-ISE-9.2: slices=127, slicesFF=151, 4luts=169 entity sdram_raw_controller is generic ( -- Generovani prikazu refresh radicem automaticky GEN_AUTO_REFRESH : boolean := true; OPTIMIZE_REFRESH : sdram_optimize := oAlone -- deprecated ); port ( -- Clock, reset, ... CLK : in std_logic; RST : in std_logic; ENABLE : in std_logic; BUSY : out std_logic; -- Address/data ADDR_ROW : in std_logic_vector(11 downto 0); ADDR_COLUMN : in std_logic_vector(8 downto 0); BANK : in std_logic_vector(1 downto 0); DATA_IN : in std_logic_vector(7 downto 0); DATA_OUT : out std_logic_vector(7 downto 0); DATA_VLD : out std_logic; -- Output data valid -- Command signal/set CMD : in sdram_func; CMD_WE : in std_logic; -- Signals to SDRAM RAM_A : out std_logic_vector(13 downto 0); RAM_D : inout std_logic_vector(7 downto 0); RAM_DQM : out std_logic; RAM_CS : out std_logic; RAM_RAS : out std_logic; RAM_CAS : out std_logic; RAM_WE : out std_logic; RAM_CLK : out std_logic; RAM_CKE : out std_logic ); end sdram_raw_controller; architecture arch_sdram_raw_controller of sdram_raw_controller is type tstate is (stReset, stIdle, stCmdWait, stCmdLMR, stCmdSelect, stCmdRead, stCmdWrite, stCmdCharge, stCmdRefresh); type tistate is (csi_Begin, csi_Idle, csi_Chg, csi_Ref1, csi_Ref2, csi_Ref3, csi_Ref4, csi_Ref5, csi_Ref6, csi_Ref7, csi_LMR, csi_End); type tcmd_len is (t1clk, t2clk, t3clk, t7clk); -- Init FSM states signal cstate_init : tistate; signal nstate_init : tistate; -- RAM command (RCKE RDQM CS RAS CAS WE) signal ram_cmd : std_logic_vector(5 downto 0); signal ram_a_sel : std_logic_vector(1 downto 0); -- Controler state (current/next/future) signal cstate : tstate; signal nstate : tstate; signal iready : std_logic; -- State timing counter signal cnt : std_logic_vector(2 downto 0); signal cnt_set : std_logic_vector(2 downto 0); signal cnt_mx : std_logic; signal cnt_load : std_logic; signal cnt_value : tcmd_len; -- RAM controller command signal cmd_fifo_reg : sdram_func; signal cmd_loaded : std_logic; signal cmd_ld_xor1 : std_logic; signal cmd_ld_xor2 : std_logic; signal cmd_ld_en : std_logic; signal cmd_as_state : tstate; -- Fifo row/col/bank, data signal row_fifo_reg : std_logic_vector(11 downto 0); signal col_fifo_reg : std_logic_vector(8 downto 0); signal bnk_fifo_reg : std_logic_vector(1 downto 0); signal din_fifo_reg : std_logic_vector(7 downto 0); signal dout_reg : std_logic_vector(7 downto 0); signal dout_ready : std_logic; signal din_ready : std_logic; signal row_bus_reg : std_logic_vector(11 downto 0); signal column_bus_reg : std_logic_vector(8 downto 0); signal bank_bus_reg : std_logic_vector(1 downto 0); signal data_bus_reg : std_logic_vector(7 downto 0); -- Refresh request signal ref_mx : std_logic; signal ref_cnt : std_logic_vector(9 downto 0); -- Read latency 2 shift (latency 3 need 4 bit shift) signal lat_sh : std_logic_vector(2 downto 0) := "000"; -- Additional FSM state logic signal cs_cc : std_logic; signal cs_cf : std_logic; signal cs_cs : std_logic; signal cs_cr : std_logic; signal cs_cw : std_logic; -- Generic to logic translation signal GENERIC_GAF : std_logic; -- Init logic signal init_p0 : std_logic; signal init_p1 : std_logic; signal init_p2 : std_logic; signal inited : std_logic; -- External operation signal cf_crw : std_logic; signal cf_cw : std_logic; signal cf_cr : std_logic; signal cf_cf : std_logic; -- Active bank's row signal actrows : std_logic_vector(51 downto 0); signal actrow : std_logic_vector(12 downto 0); signal arow : std_logic_vector(12 downto 0); signal resel_mx : std_logic; signal bnk1 : std_logic; signal bnk2 : std_logic; signal bnk3 : std_logic; signal bnk4 : std_logic; -- State signals/State regs signal cha : std_logic; signal chg : std_logic; signal chg_reg : std_logic; signal ref : std_logic; signal ref_reg : std_logic; signal sel : std_logic; signal sel_reg : std_logic; signal fff : std_logic; signal fff_reg : std_logic; signal out_ld : std_logic; signal out_reg : std_logic; signal waw : std_logic; signal rar : std_logic; signal raw : std_logic; begin -- Generic GEN_AUTO_REFRESH true/false -> 0/1 GENERIC_GAF <= '1' when GEN_AUTO_REFRESH = true else '0'; RAM_CLK <= CLK; RAM_CKE <= ram_cmd(5); RAM_DQM <= ram_cmd(4); RAM_CS <= ram_cmd(3); RAM_RAS <= ram_cmd(2); RAM_CAS <= ram_cmd(1); RAM_WE <= ram_cmd(0); BUSY <= not iready; DATA_VLD <= lat_sh(2); -- Read data valid after latency logic DATA_OUT <= dout_reg; -- Set data for RAM (RD) RAM_D <= data_bus_reg when din_ready = '1' else (others => 'Z'); -- Busy logic iready <= inited and not fff_reg; -- Idle count logic cnt_mx <= cnt(0) and cnt(1) and cnt(2); -- cnt=7 cnt_set <= "001" when (cnt_value = t7clk) else "101" when (cnt_value = t3clk) else "110" when (cnt_value = t2clk) else "111" when (cnt_value = t1clk) else "111"; -- Cmd load logic cmd_loaded <= cmd_ld_xor1 xor cmd_ld_xor2; cmd_ld_en <= CMD_WE and iready and ENABLE; -- Bank selection bnk1 <= chg_reg or sel_reg when bnk_fifo_reg = "00" else ref_reg; bnk2 <= chg_reg or sel_reg when bnk_fifo_reg = "01" else ref_reg; bnk3 <= chg_reg or sel_reg when bnk_fifo_reg = "10" else ref_reg; bnk4 <= chg_reg or sel_reg when bnk_fifo_reg = "11" else ref_reg; -- Row selected in next command mx actrow <= actrows(12 downto 0) when bnk_fifo_reg = "00" else actrows(25 downto 13) when bnk_fifo_reg = "01" else actrows(38 downto 26) when bnk_fifo_reg = "10" else actrows(51 downto 39) when bnk_fifo_reg = "11"; -- Need row reselection? resel_mx <= '1' when actrow(11 downto 0) /= row_fifo_reg else '0'; ----------------------------------------------------------------------------- -- Autorefresh gen counter limit (10 bit): 1100000000 = 15.360 us (50 MHz) ref_mx <= (ref_cnt(9) and ref_cnt(8) and GENERIC_GAF); ----------------------------------------------------------------------------- -- Input command logic cmd_as_state <= stCmdRead when cmd_fifo_reg = fRead else stCmdWrite when cmd_fifo_reg = fWrite else stCmdRefresh when cmd_fifo_reg = fRefresh else stCmdWait; ----------------------------------------------------------------------------- -- Next (FIFO) opration logic cf_cr <= '1' when cmd_fifo_reg = fRead else '0'; cf_cw <= '1' when cmd_fifo_reg = fWrite else '0'; cf_cf <= '1' when cmd_fifo_reg = fRefresh else '0'; cf_crw <= cf_cr or cf_cw; ----------------------------------------------------------------------------- -- State flag logic -- Charge all rows when need refresh cha <= ((cf_cf and cmd_loaded) or (ref_mx and not fff_reg)) and (actrows(12) or actrows(25) or actrows(38) or actrows(51)); -- Charge if ram will be refreshed OR loaded RD/WR & INCORRECT ROW SELECTED chg <= cha or (cf_crw and resel_mx and cmd_loaded and actrow(12)); -- Refresh flag ref <= (ref_mx and not fff_reg) or (cf_cf and cmd_loaded); -- Select if loaded RD/WR and reselect/nothing selected sel <= cf_crw and (resel_mx or not actrow(12)) and cmd_loaded; -- Fifo full if chg OR sel flag set OR -- (not prepare command finished AND operation in FIFO can't be optimized -- by read-after-read, write-after-write or read-after-write techniques) --fff <= chg or sel or (not rar and not waw and not raw and cmd_loaded) or not cnt_mx; fff <= chg or sel or (not rar and not waw and not raw and cmd_loaded) or (not cnt_mx and cmd_loaded); -- Optimize flags (read-after-read, write-after-write, read-after-write) -- WARN: when R/W state was finished and IDLE now take latency time, flags aren't set rar <= cs_cr and cf_cr and not resel_mx and cmd_loaded; waw <= cs_cw and cf_cw and not resel_mx and cmd_loaded; raw <= cs_cw and cf_cr and not resel_mx and cmd_loaded; out_ld <= (out_reg and not fff_reg) or rar or waw or raw; -- row is unselected when REFRESH flasg set arow <= (not ref_reg) & row_bus_reg; --'1' & row_bus_reg when ref_reg = '0' else (others => '0'); ----------------------------------------------------------------------------- -- State flag registers state_registers: process(RST, CLK) begin if RST = '1' then chg_reg <= '0'; ref_reg <= '0'; sel_reg <= '0'; fff_reg <= '0'; out_reg <= '0'; actrows <= (others => '0'); elsif CLK'event and CLK = '1' then chg_reg <= (chg_reg and not cs_cc) or chg; -- Simple charge flag ref_reg <= (ref_reg and not cs_cf) or ref; -- Refresh flag sel_reg <= (sel_reg and not cs_cs) or sel; -- Select flag -- cnt_ld must be set only when can't be rar/waw/raw fff_reg <= (fff_reg and (sel_reg or chg_reg or not cnt_mx)) or fff; out_reg <= fff_reg; if bnk1 = '1' then actrows(12 downto 0) <= arow; end if; if bnk2 = '1' then actrows(25 downto 13) <= arow; end if; if bnk3 = '1' then actrows(38 downto 26) <= arow; end if; if bnk4 = '1' then actrows(51 downto 39) <= arow; end if; end if; end process; ----------------------------------------------------------------------------- -- CMD_loaded control register cmd_ld_reg: process(RST, CLK, cmd_ld_xor1) begin if RST = '1' then cmd_ld_xor2 <= cmd_ld_xor1; elsif (CLK'event and CLK = '0') then cmd_ld_xor2 <= cmd_ld_xor1; end if; end process; ----------------------------------------------------------------------------- -- Data from FIFO to SDRAM output data_to_bus: process(RST, CLK) begin if RST = '1' then data_bus_reg <= (others => '0'); column_bus_reg <= (others => '0'); bank_bus_reg <= (others => '0'); row_bus_reg <= (others => '0'); elsif (CLK'event and CLK = '0') then if cmd_loaded = '1' then data_bus_reg <= din_fifo_reg; column_bus_reg <= col_fifo_reg; bank_bus_reg <= bnk_fifo_reg; row_bus_reg <= row_fifo_reg; end if; end if; end process; ----------------------------------------------------------------------------- -- Data from input to FIFO, load control flag cmd_ld_work: process(RST, CLK) begin if RST = '1' then cmd_fifo_reg <= fNop; bnk_fifo_reg <= (others => '0'); row_fifo_reg <= (others => '0'); col_fifo_reg <= (others => '0'); din_fifo_reg <= (others => '0'); cmd_ld_xor1 <= '0'; elsif (CLK'event and CLK = '0') then if cmd_ld_en = '1' then cmd_fifo_reg <= CMD; bnk_fifo_reg <= BANK; col_fifo_reg <= ADDR_COLUMN; row_fifo_reg <= ADDR_ROW; din_fifo_reg <= DATA_IN; cmd_ld_xor1 <= not cmd_ld_xor1; end if; end if; end process; ----------------------------------------------------------------------------- -- Auto refresh generator ram_refresh_gen: process(RST, CLK) begin if RST = '1' then ref_cnt <= (others => '0'); elsif CLK'event and CLK = '0' then if GEN_AUTO_REFRESH = true then if ref_reg = '1' then -- When ref flag set, reset counter ref_cnt <= (others => '0'); elsif ref_mx = '0' then ref_cnt <= ref_cnt + 1; end if; end if; end if; end process; -- Command idle timer ram_cnt: process(RST, CLK) begin if RST = '1' then cnt <= (others => '1'); elsif CLK'event and CLK = '0' then if cnt_load = '1' then cnt <= cnt_set; elsif cnt_mx = '0' then cnt <= cnt + 1; end if; end if; end process; -- Data valid shifter (latency), output reg write ram_read_flag: process(RST, CLK) begin if RST = '1' then dout_reg <= (others => '0'); elsif CLK'event and CLK = '1' then -- Output reg set if lat_sh(1) = '1' then dout_reg <= RAM_D; end if; -- Latency shift lat_sh <= lat_sh(1 downto 0) & dout_ready; end if; end process; ----------------------------------------------------------------------------- -- Init FSM fsm_init_ctrl: process(RST, CLK) begin if RST = '1' then cstate_init <= csi_Begin; elsif CLK'event and CLK = '0' then cstate_init <= nstate_init; end if; end process; fsm_init: process(cstate_init) begin init_p0 <= '0'; init_p1 <= '0'; init_p2 <= '0'; inited <= '0'; case cstate_init is when csi_Begin => null; when csi_Idle => init_p0 <= '1'; when csi_Chg => init_p0 <= '1'; when csi_Ref1 => init_p1 <= '1'; when csi_Ref2 => init_p1 <= '1'; when csi_Ref3 => init_p1 <= '1'; when csi_Ref4 => init_p1 <= '1'; when csi_Ref5 => init_p1 <= '1'; when csi_Ref6 => init_p1 <= '1'; when csi_Ref7 => init_p1 <= '1'; when csi_LMR => init_p2 <= '1'; when csi_End => inited <= '1'; end case; end process; fsm_init_ns: process(cstate_init, cnt_load) begin nstate_init <= csi_Begin; case cstate_init is when csi_Begin => nstate_init <= csi_Idle; when csi_Idle => nstate_init <= csi_Chg; when csi_Chg => if cnt_load = '1' then nstate_init <= csi_Ref1; else nstate_init <= csi_Chg; end if; when csi_Ref1 => if cnt_load = '1' then nstate_init <= csi_Ref2; else nstate_init <= csi_Ref1; end if; when csi_Ref2 => if cnt_load = '1' then nstate_init <= csi_Ref3; else nstate_init <= csi_Ref2; end if; when csi_Ref3 => if cnt_load = '1' then nstate_init <= csi_Ref4; else nstate_init <= csi_Ref3; end if; when csi_Ref4 => if cnt_load = '1' then nstate_init <= csi_Ref5; else nstate_init <= csi_Ref4; end if; when csi_Ref5 => if cnt_load = '1' then nstate_init <= csi_Ref6; else nstate_init <= csi_Ref5; end if; when csi_Ref6 => if cnt_load = '1' then nstate_init <= csi_Ref7; else nstate_init <= csi_Ref6; end if; when csi_Ref7 => if cnt_load = '1' then nstate_init <= csi_LMR; else nstate_init <= csi_Ref7; end if; when csi_LMR => if cnt_load = '1' then nstate_init <= csi_End; else nstate_init <= csi_LMR; end if; when csi_End => nstate_init <= csi_End; end case; end process; ----------------------------------------------------------------------------- -- Muxes -- Latency 2, Sequential, Burst Len 1B, Single Location Access RAM_A <= (9 => '1', 5 => '1', others => '0') when ram_a_sel = "00" else bank_bus_reg & '0' & (not ref_reg) & "0000000000" when ram_a_sel = "01" else bank_bus_reg & row_bus_reg when ram_a_sel = "10" else bank_bus_reg & "000" & column_bus_reg when ram_a_sel = "11"; ----------------------------------------------------------------------------- -- Main FSM control ram_FSM_ctrl: process(RST, CLK) begin if RST = '1' then cstate <= stReset; elsif CLK'event and CLK = '0' then cstate <= nstate; end if; end process; -- Main FSM logic ram_FSM: process(cstate, rar, waw, raw) begin -- Default ram_cmd <= "111111"; -- Idle (RCKE RDQM CS RAS CAS WE) cnt_value <= t1clk; -- Counter value cnt_load <= '0'; -- No counter set value dout_ready <= '0'; -- No data reading (from RAM) din_ready <= '0'; -- No data to write (to RAM) ram_a_sel <= (others => '0'); -- CurrentState_Cmd(Charge,reFresh,Select,Idle) cs_cc <= '0'; cs_cf <= '0'; cs_cs <= '0'; cs_cr <= '0'; cs_cw <= '0'; case cstate is when stIdle => null; when stReset => -- Start ram_cmd <= "011111"; -- RCKE RDQM CS RAS CAS WE when stCmdLMR => -- Load mode register (OP-CODE) ram_cmd <= "110000"; ram_a_sel <= "00"; cnt_value <= t1clk; cnt_load <= '1'; when stCmdWait => -- External command waiting null; when stCmdCharge => -- Precharge cs_cc <= '1'; -- Current state charge identify ram_cmd <= "110010"; ram_a_sel <= "01"; cnt_value <= t2clk; cnt_load <= '1'; when stCmdRefresh => -- Refresh cs_cf <= '1'; -- Current state refresh identify ram_cmd <= "110001"; cnt_value <= t7clk; cnt_load <= '1'; when stCmdSelect => -- Select bank/row cs_cs <= '1'; -- Current state select identify ram_cmd <= "110011"; ram_a_sel <= "10"; cnt_value <= t3clk; cnt_load <= '1'; when stCmdRead => -- Read byte bank/column cs_cr <= '1'; ram_cmd <= "100101"; ram_a_sel <= "11"; dout_ready <= '1'; cnt_value <= t2clk; cnt_load <= not rar; when stCmdWrite => -- Write byte bank/column cs_cw <= '1'; ram_cmd <= "100100"; ram_a_sel <= "11"; din_ready <= '1'; cnt_value <= t1clk; cnt_load <= not (waw or raw); end case; end process; -- Main FSM state control ram_FSM_ns: process(cstate, cnt_mx, rar, waw, raw, init_p0, chg_reg, init_p1, ref_reg, init_p2, sel_reg, out_ld, cmd_as_state) begin -- Default nstate <= stReset; -- Future state, after actual finished case cstate is when stIdle => if (not cnt_mx and not (rar or waw or raw)) = '1' then nstate <= stIdle; elsif (init_p0 or chg_reg) = '1' then nstate <= stCmdCharge; elsif (init_p1 or ref_reg) = '1' then nstate <= stCmdRefresh; elsif init_p2 = '1' then nstate <= stCmdLMR; elsif sel_reg = '1' then nstate <= stCmdSelect; elsif out_ld = '1' then nstate <= cmd_as_state; else nstate <= stCmdWait; end if; when stReset => nstate <= stIdle; when stCmdLMR => nstate <= stIdle; when stCmdCharge => nstate <= stIdle; when stCmdRefresh => nstate <= stIdle; when stCmdSelect => nstate <= stIdle; when stCmdWait => -- External command waiting if chg_reg = '1' then nstate <= stCmdCharge; elsif ref_reg = '1' then nstate <= stCmdRefresh; elsif sel_reg = '1' then nstate <= stCmdSelect; elsif out_ld = '1' then nstate <= cmd_as_state; else nstate <= stCmdWait; end if; when stCmdRead => -- Read byte bank/column if rar = '1' then nstate <= stCmdRead; -- Read after read else nstate <= stIdle; end if; when stCmdWrite => -- Write byte bank/column if (waw or raw) = '1' then nstate <= cmd_as_state; -- Write/read after write else nstate <= stIdle; end if; end case; end process; end arch_sdram_raw_controller;
zx-simi
trunk/fpga/FITkit/sdram_raw_ctrl.vhd
VHDL
oos
23,605
-------------------------------------------------------------------------------- -- Copyright (c) 1995-2006 Xilinx, Inc. All rights reserved. -------------------------------------------------------------------------------- -- ____ ____ -- / /\/ / -- /___/ \ / Vendor: Xilinx -- \ \ \/ Version : 8.2i -- \ \ Application : xaw2vhdl -- / / Filename : clkgen_100MHz.vhd -- /___/ /\ Timestamp : 09/28/2006 17:19:01 -- \ \ / \ -- \___\/\___\ -- --Command: xaw2vhdl-st F:\FITKit\Svn\units\clkgen\clkgen_100MHz.xaw F:\FITKit\Svn\units\clkgen\clkgen_100MHz --Design Name: clkgen_100MHz --Device: xc3s50-pq208-4 -- -- Module clkgen_100MHz -- Generated by Xilinx Architecture Wizard -- Written for synthesis tool: XST library ieee; use ieee.std_logic_1164.ALL; use ieee.numeric_std.ALL; use work.clkgen_cfg.ALL; library UNISIM; use UNISIM.Vcomponents.ALL; entity clkgen is generic (FREQ : dcm_freq := DCM_25MHz); port (CLK : in std_logic; RST : in std_logic; CLK1X_OUT : out std_logic; CLKFX_OUT : out std_logic; LOCKED_OUT : out std_logic); end clkgen; architecture BEHAVIORAL of clkgen is signal CLKFX_BUF : std_logic; signal CLKIN_IBUFG : std_logic; signal GND1 : std_logic; component BUFG port ( I : in std_logic; O : out std_logic); end component; component IBUFG port ( I : in std_logic; O : out std_logic); end component; component DCM generic( CLK_FEEDBACK : string := "1X"; CLKDV_DIVIDE : real := 2.0; CLKFX_DIVIDE : integer := 1; CLKFX_MULTIPLY : integer := 4; CLKIN_DIVIDE_BY_2 : boolean := FALSE; CLKIN_PERIOD : real := 10.0; CLKOUT_PHASE_SHIFT : string := "NONE"; DESKEW_ADJUST : string := "SYSTEM_SYNCHRONOUS"; DFS_FREQUENCY_MODE : string := "LOW"; DLL_FREQUENCY_MODE : string := "LOW"; DUTY_CYCLE_CORRECTION : boolean := TRUE; FACTORY_JF : bit_vector := x"C080"; PHASE_SHIFT : integer := 0; STARTUP_WAIT : boolean := FALSE; DSS_MODE : string := "NONE"); port ( CLKIN : in std_logic; CLKFB : in std_logic; RST : in std_logic; PSEN : in std_logic; PSINCDEC : in std_logic; PSCLK : in std_logic; DSSEN : in std_logic; CLK0 : out std_logic; CLK90 : out std_logic; CLK180 : out std_logic; CLK270 : out std_logic; CLKDV : out std_logic; CLK2X : out std_logic; CLK2X180 : out std_logic; CLKFX : out std_logic; CLKFX180 : out std_logic; STATUS : out std_logic_vector (7 downto 0); LOCKED : out std_logic; PSDONE : out std_logic); end component; begin GND1 <= '0'; CLK1X_OUT <= CLKIN_IBUFG; CLKFX_BUFG_INST : BUFG port map (I=>CLKFX_BUF, O=>CLKFX_OUT); CLKIN_IBUFG_INST : IBUFG port map (I=>CLK, O=>CLKIN_IBUFG); DCM_INST : DCM generic map( CLK_FEEDBACK => "NONE", CLKDV_DIVIDE => 2.0, CLKFX_DIVIDE => getdiv(FREQ), CLKFX_MULTIPLY => getmul(FREQ), CLKIN_DIVIDE_BY_2 => FALSE, CLKIN_PERIOD => 135.634, CLKOUT_PHASE_SHIFT => "NONE", DESKEW_ADJUST => "SYSTEM_SYNCHRONOUS", DFS_FREQUENCY_MODE => "LOW", DLL_FREQUENCY_MODE => "LOW", DUTY_CYCLE_CORRECTION => TRUE, FACTORY_JF => x"C080", PHASE_SHIFT => 0, STARTUP_WAIT => FALSE) port map (CLKFB=>GND1, CLKIN=>CLKIN_IBUFG, DSSEN=>GND1, PSCLK=>GND1, PSEN=>GND1, PSINCDEC=>GND1, RST=>RST, CLKDV=>open, CLKFX=>CLKFX_BUF, CLKFX180=>open, CLK0=>open, CLK2X=>open, CLK2X180=>open, CLK90=>open, CLK180=>open, CLK270=>open, LOCKED=>LOCKED_OUT, PSDONE=>open, STATUS=>open); end BEHAVIORAL;
zx-simi
trunk/fpga/FITkit/clkgen.vhd
VHDL
oos
4,577
-- sdram_config.vhd: SDRAM constants & definitions -- Copyright (C) 2006 Brno University of Technology, -- Faculty of Information Technology -- Author(s): Ladislav Capka <xcapka01 AT stud.fit.vutbr.cz> -- -- LICENSE TERMS -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions -- are met: -- 1. Redistributions of source code must retain the above copyright -- notice, this list of conditions and the following disclaimer. -- 2. 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. -- 3. All advertising materials mentioning features or use of this software -- or firmware must display the following acknowledgement: -- -- This product includes software developed by the University of -- Technology, Faculty of Information Technology, Brno and its -- contributors. -- -- 4. Neither the name of the Company 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 or firmware is provided ``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 company 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. -- -- $Id$ -- -- library ieee; use ieee.std_logic_1164.all; use ieee.std_logic_arith.all; package sdram_controller_cfg is type sdram_func is (fNop, fRead, fWrite, fRefresh); type sdram_optimize is (oMultiple, oAlone); end sdram_controller_cfg; package body sdram_controller_cfg is end sdram_controller_cfg;
zx-simi
trunk/fpga/FITkit/sdram_config.vhd
VHDL
oos
2,333
-- ps2full_ctrl.vhd: PS/2 Controller -- Copyright (C) 2006 Brno University of Technology, -- Faculty of Information Technology -- Author(s): Zdenek Vasicek <xvasic11 AT stud.fit.vutbr.cz> -- -- LICENSE TERMS -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions -- are met: -- 1. Redistributions of source code must retain the above copyright -- notice, this list of conditions and the following disclaimer. -- 2. 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. -- 3. All advertising materials mentioning features or use of this software -- or firmware must display the following acknowledgement: -- -- This product includes software developed by the University of -- Technology, Faculty of Information Technology, Brno and its -- contributors. -- -- 4. Neither the name of the Company 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 or firmware is provided ``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 company 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. -- -- $Id$ -- -- library IEEE; use IEEE.STD_LOGIC_1164.ALL; use IEEE.STD_LOGIC_ARITH.ALL; use IEEE.STD_LOGIC_UNSIGNED.ALL; architecture full of PS2_controller is type FSMstate is (SInit, SRcvData, SRcvParity, SRcvStop, SStart0, SStart1, SStart2, SSndData, SSndParity, SSndStop, SRcvAck); signal pstate : FSMstate; -- actual state signal nstate : FSMstate; -- next state signal ps2clk_reg : std_logic; signal ps2clk_dreg : std_logic; signal ps2data_reg : std_logic; signal di_en : std_logic; --read from PS/2 data signal do_en : std_logic; --write to PS/2 data signal cntr_reg : std_logic_vector(8 downto 0); signal cntr_en : std_logic; signal cntr_rst : std_logic; signal cntr_cmp8 : std_logic; signal cntr_cmp511 : std_logic; signal data_reg : std_logic_vector(7 downto 0); signal data_en : std_logic; signal parity_reg : std_logic; signal parity_en : std_logic; signal parity_rst : std_logic; signal parity_in : std_logic; signal parity_sel : std_logic; signal clk_we : std_logic; signal data_sel : std_logic_vector(1 downto 0); signal busy : std_logic; begin DATA_OUT <= data_reg; -- PS/2 interface PS2_CLK <= '0' when clk_we='1' else 'Z' ; PS2_DATA <= data_reg(0) when data_sel="00" else parity_reg when data_sel="01" else '0' when data_sel="10" else 'Z'; -- PS/2 CLK edge detector process (RST, CLK) begin if (RST = '1') then ps2clk_reg <= '1'; ps2clk_dreg <= '1'; ps2data_reg <= '1'; elsif (CLK'event) and (CLK = '1') then ps2clk_reg <= PS2_CLK; ps2clk_dreg <= ps2clk_reg; ps2data_reg <= PS2_DATA; end if; end process; di_en <= ps2clk_dreg and (not ps2clk_reg); --Falling edge do_en <= (not ps2clk_dreg) and ps2clk_reg; --Rising edge -- Bits counter bitscntr: process(RST, CLK) begin if (RST = '1') then cntr_reg <= (others => '0'); elsif (CLK'event) and (CLK='1') then if (cntr_rst = '1') then cntr_reg <= (others => '0'); elsif (cntr_en='1') then cntr_reg <= cntr_reg + 1; end if; end if; end process; -- Comparators cntr_cmp8 <= '1' when (cntr_reg = 16#008#) else '0'; cntr_cmp511 <= '1' when (cntr_reg = 16#1ff#) else '0'; --Data IN/OUT shift register process (RST, CLK) begin if (RST = '1') then --datain_reg <= (others=>'0'); elsif (CLK'event) and (CLK = '1') then if (WRITE_EN='1') and (busy='0') then --load data_reg <= DATA_IN; elsif (data_en='1') then data_reg <= ps2data_reg & data_reg(7 downto 1); end if; end if; end process; --Data ODD parity calculator process (RST, CLK) begin if (RST = '1') then parity_reg <= '1'; elsif (CLK'event) and (CLK = '1') then if (parity_rst = '1') then parity_reg <= '1'; elsif (parity_en='1') then parity_reg <= parity_reg xor parity_in; end if; end if; end process; parity_in <= ps2data_reg when parity_sel='0' else data_reg(0); --data bit mx --FSM present state process (RST, CLK) begin if (RST = '1') then pstate <= sinit; elsif (CLK'event) and (CLK = '1') then pstate <= nstate; end if; end process; --FSM next state logic process (pstate, di_en, do_en, ps2data_reg, parity_reg, cntr_cmp8, cntr_cmp511, WRITE_EN) begin nstate <= SInit; cntr_rst <= '0'; cntr_en <= '0'; parity_rst <= '0'; parity_sel <= '0'; parity_en <= '0'; data_en <= '0'; data_sel <= "11"; clk_we <= '0'; DATA_ERR <= '0'; DATA_VLD <= '0'; busy <= '1'; case pstate is when SInit => busy <= '0'; if (di_en='1') and (ps2data_reg='0') then nstate <= SRcvData; cntr_rst <= '1'; parity_rst <= '1'; end if; if (WRITE_EN='1') then cntr_rst <= '1'; nstate <= SStart0; end if; --==================================================================== --Receiver --==================================================================== -- Receive data bits when SRcvData => if (cntr_cmp8='0') then nstate <= SRcvData; cntr_en <= di_en; data_en <= di_en; parity_en <= di_en; else nstate <= SRcvParity; end if; --Receive parity bit when SRcvParity => if (di_en='1') then nstate <= SRcvStop; assert (ps2data_reg=parity_reg) report "PS/2 Data Parity Error" severity note; if (ps2data_reg=parity_reg) then DATA_VLD <= '1'; else DATA_ERR <= '1'; end if; else nstate <= SRcvParity; end if; --Receive stop bit when SRcvStop => if (di_en='0') then nstate <= SRcvStop; end if; --==================================================================== -- Transmitter --==================================================================== when SStart0 => clk_we <= '1'; if (cntr_cmp511='1') then nstate <= SStart1; cntr_rst <= '1'; else nstate <= SStart0; cntr_en <= '1'; end if; --Init data transfer when SStart1 => clk_we <= '1'; data_sel <= "10"; if (cntr_cmp511='1') then nstate <= SStart2; else nstate <= SStart1; cntr_en <= '1'; end if; --Release CLK when SStart2 => data_sel <= "10"; if (di_en='1') then nstate <= SSndData; cntr_rst <= '1'; parity_rst <= '1'; else nstate <= SStart2; end if; --Transmit data bits when SSndData => data_sel <= "00"; if (cntr_cmp8='0') then nstate <= SSndData; parity_sel <= '1'; parity_en <= di_en; data_en <= di_en; cntr_en <= di_en; else nstate <= SSndParity; end if; --Transmit parity bit when SSndParity => data_sel <= "01"; if (di_en='1') then nstate <= SSndStop; else nstate <= SSndParity; end if; --Transmit stop bit when SSndStop => data_sel <= "11"; if (di_en='1') then nstate <= SRcvAck; else nstate <= SSndStop; end if; --Receive acknowledge when SRcvAck => if (do_en='1') then assert (ps2data_reg='0') report "PS/2 ACK Error" severity note; if (ps2data_reg='1') then DATA_ERR <= '1'; end if; else nstate <= SRcvAck; end if; when others => null; end case; end process; end full;
zx-simi
trunk/fpga/FITkit/ps2full_ctrl.vhd
VHDL
oos
9,786
-- ps2half_ctrl.vhd: Simple PS/2 Controller (readonly version) -- Copyright (C) 2006 Brno University of Technology, -- Faculty of Information Technology -- Author(s): Zdenek Vasicek <xvasic11 AT stud.fit.vutbr.cz> -- -- LICENSE TERMS -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions -- are met: -- 1. Redistributions of source code must retain the above copyright -- notice, this list of conditions and the following disclaimer. -- 2. 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. -- 3. All advertising materials mentioning features or use of this software -- or firmware must display the following acknowledgement: -- -- This product includes software developed by the University of -- Technology, Faculty of Information Technology, Brno and its -- contributors. -- -- 4. Neither the name of the Company 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 or firmware is provided ``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 company 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. -- -- $Id$ -- -- library IEEE; use IEEE.STD_LOGIC_1164.ALL; use IEEE.STD_LOGIC_ARITH.ALL; use IEEE.STD_LOGIC_UNSIGNED.ALL; architecture half of PS2_controller is type FSMstate is (SInit, SRcvData, SRcvParity, SRcvStop); signal pstate : FSMstate; -- actual state signal nstate : FSMstate; -- next state signal ps2clk_reg : std_logic; signal ps2clk_dreg : std_logic; signal ps2data_reg : std_logic; signal di_en : std_logic; --read from PS/2 data signal bitcntr : std_logic_vector(7 downto 0); signal bitcntr_en : std_logic; signal bitcntr_rst : std_logic; signal bits_cmp8 : std_logic; signal datain_reg : std_logic_vector(7 downto 0); signal datain_en : std_logic; signal datain_rst : std_logic; signal datain_parity : std_logic; begin PS2_CLK <= 'Z'; PS2_DATA <= 'Z'; DATA_OUT <= datain_reg; -- PS/2 CLK edge detector process (RST, CLK) begin if (RST = '1') then ps2clk_reg <= '1'; ps2clk_dreg <= '1'; ps2data_reg <= '1'; elsif (CLK'event) and (CLK = '1') then ps2clk_reg <= PS2_CLK; ps2clk_dreg <= ps2clk_reg; ps2data_reg <= PS2_DATA; end if; end process; di_en <= ps2clk_dreg and (not ps2clk_reg); -- Bits counter bitscntr: process(RST, CLK) begin if (RST = '1') then bitcntr <= (others => '0'); elsif (CLK'event) and (CLK='1') then if (bitcntr_rst = '1') then bitcntr <= (others => '0'); elsif (bitcntr_en='1') then bitcntr <= bitcntr + 1; end if; end if; end process; -- Comparators bits_cmp8 <= '1' when (bitcntr = 16#08#) else '0'; --DataIN shift register process (RST, CLK) begin if (RST = '1') then --datain_reg <= (others=>'0'); elsif (CLK'event) and (CLK = '1') then if (datain_en='1') then datain_reg <= ps2data_reg & datain_reg(7 downto 1); end if; end if; end process; --DataIN odd parity process (RST, CLK) begin if (RST = '1') then datain_parity <= '1'; elsif (CLK'event) and (CLK = '1') then if (datain_rst = '1') then datain_parity <= '1'; elsif (datain_en='1') then datain_parity <= datain_parity xor ps2data_reg; end if; end if; end process; --FSM present state process (RST, CLK) begin if (RST = '1') then pstate <= sinit; elsif (CLK'event) and (CLK = '1') then pstate <= nstate; end if; end process; --FSM next state logic process (pstate, di_en, ps2data_reg, datain_parity, bits_cmp8) begin nstate <= SInit; bitcntr_rst <= '0'; bitcntr_en <= '0'; datain_en <= '0'; datain_rst <= '0'; DATA_ERR <= '0'; DATA_VLD <= '0'; case pstate is when SInit => if (di_en='1') and (ps2data_reg='0') then nstate <= SRcvData; bitcntr_rst <= '1'; datain_rst <= '1'; end if; --Receive data bits when SRcvData => if (bits_cmp8='0') then nstate <= SRcvData; bitcntr_en <= di_en; datain_en <= di_en; else nstate <= SRcvParity; end if; -- Receive parity when SRcvParity => if (di_en='1') then nstate <= SRcvStop; assert (ps2data_reg=datain_parity) report "PS/2 Data Parity Error" severity note; if (ps2data_reg=datain_parity) then DATA_VLD <= '1'; else DATA_ERR <= '1'; end if; else nstate <= SRcvParity; end if; -- Receive stop bit when SRcvStop => if (di_en='0') then nstate <= SRcvStop; end if; when others => null; end case; end process; end half;
zx-simi
trunk/fpga/FITkit/ps2half_ctrl.vhd
VHDL
oos
6,149
-- arch_pc_ifc: PC interface architecture -- Copyright (C) 2006 Brno University of Technology, -- Faculty of Information Technology -- Author(s): Zdenek Vasicek <vasicek AT fit.vutbr.cz> -- -- LICENSE TERMS -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions -- are met: -- 1. Redistributions of source code must retain the above copyright -- notice, this list of conditions and the following disclaimer. -- 2. 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. -- 3. All advertising materials mentioning features or use of this software -- or firmware must display the following acknowledgement: -- -- This product includes software developed by the University of -- Technology, Faculty of Information Technology, Brno and its -- contributors. -- -- 4. Neither the name of the Company 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 or firmware is provided ``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 company 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. -- -- $Id$ -- -- library IEEE; use IEEE.std_logic_1164.all; use work.clkgen_cfg.all; use work.fpga_cfg.all; entity fpga is port ( -- hodiny SMCLK : in std_logic; -- SDRAM RA : out std_logic_vector(14 downto 0); RD : inout std_logic_vector(7 downto 0) := (others => 'Z'); RDQM : out std_logic; RCS : out std_logic; RRAS : out std_logic; RCAS : out std_logic; RWE : out std_logic; RCLK : out std_logic; RCKE : out std_logic; -- SD Card SD_CLK : out std_logic; SD_CS : out std_logic; SD_MOSI : out std_logic; SD_MISO : in std_logic; -- VGA BLUE_V : out std_logic_vector(2 downto 0); GREEN_V : out std_logic_vector(2 downto 0); RED_V : out std_logic_vector(2 downto 0); VSYNC_V : out std_logic; HSYNC_V : out std_logic; -- PS/2 mouse M_DATA : inout std_logic := 'Z'; M_CLK : inout std_logic := 'Z'; -- PS/2 keyboard K_DATA : inout std_logic := 'Z'; K_CLK : inout std_logic := 'Z'; -- SPEAKER SPEAK_OUT : out std_logic; -- PC interface X : inout std_logic_vector(40 downto 1) := (others => 'Z') ); end fpga; architecture arch of fpga is signal clk : std_logic; signal clk_locked : std_logic; signal clkdv : std_logic; signal reset : std_logic; signal smclk_x1 : std_logic; component clkgen is generic ( FREQ : dcm_freq := DCM_FREQUENCY ); port ( CLK : in std_logic; RST : in std_logic; CLK1X_OUT : out std_logic; CLKFX_OUT : out std_logic; LOCKED_OUT : out std_logic ); end component; begin -- DCM - clock generator (default 25MHz) DCMclkgen: entity work.clkgen generic map ( FREQ => DCM_FREQUENCY ) port map ( CLK => SMCLK, RST => '0', CLK1X_OUT => smclk_x1, CLKFX_OUT => clk, LOCKED_OUT => clk_locked ); -- FPGA design fpga_inst: entity work.top_level port map ( SMCLK => smclk_x1, CLK => clk, RESET => reset, RA => RA, RD => RD, RDQM => RDQM, RCS => RCS, RRAS => RRAS, RCAS => RCAS, RWE => RWE, RCKE => RCKE, RCLK => RCLK, X => X(40 downto 1), BLUE_V(2) => BLUE_V(2), BLUE_V(1) => BLUE_V(1), BLUE_V(0) => BLUE_V(0), GREEN_V(2) => GREEN_V(2), GREEN_V(1) => GREEN_V(1), GREEN_V(0) => GREEN_V(0), RED_V(2) => RED_V(2), RED_V(1) => RED_V(1), RED_V(0) => RED_V(0), VSYNC_V => VSYNC_V, HSYNC_V => HSYNC_V, K_DATA => K_DATA, K_CLK => K_CLK, M_DATA => M_DATA, M_CLK => M_CLK, -- SD Card SD_CLK => SD_CLK, SD_CS => SD_CS, SD_MOSI => SD_MOSI, SD_MISO => SD_MISO, -- Speaker SPEAK_OUT => SPEAK_OUT ); end architecture;
zx-simi
trunk/fpga/FITkit/fpga.vhd
VHDL
oos
5,510
-- clkgen_config.vhd: DCM constants & definitions -- Copyright (C) 2006 Brno University of Technology, -- Faculty of Information Technology -- Author(s): Ladislav Capka <xcapka01 AT stud.fit.vutbr.cz> -- -- LICENSE TERMS -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions -- are met: -- 1. Redistributions of source code must retain the above copyright -- notice, this list of conditions and the following disclaimer. -- 2. 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. -- 3. All advertising materials mentioning features or use of this software -- or firmware must display the following acknowledgement: -- -- This product includes software developed by the University of -- Technology, Faculty of Information Technology, Brno and its -- contributors. -- -- 4. Neither the name of the Company 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 or firmware is provided ``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 company 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. -- -- $Id$ -- -- library ieee; use ieee.std_logic_1164.all; use ieee.std_logic_arith.all; package clkgen_cfg is type dcm_freq is (DCM_100MHz, DCM_75MHz, DCM_50MHz, DCM_40MHz, DCM_25MHz, DCM_20MHz); -- DCM_100MHz -> 99.5328 MHz -- DCM_75MHz -> 73.7280 MHz -- DCM_50MHz -> 49.7664 MHz -- DCM_40MHz -> 39.8131 MHz -- DCM_25MHz -> 24.8832 MHz -- DCM_20MHz -> 19.9066 MHz -- DCM coeficients for input 7.3728 MHz (SMCLK) function getdiv(constant mode : dcm_freq) return integer; function getmul(constant mode : dcm_freq) return integer; end clkgen_cfg; package body clkgen_cfg is function getdiv(constant mode : dcm_freq) return integer is begin if mode = DCM_100MHz then return 2; elsif mode = DCM_75MHz then return 1; elsif mode = DCM_50MHz then return 4; elsif mode = DCM_40MHz then return 5; elsif mode = DCM_25MHz then return 7; elsif mode = DCM_20MHz then return 10; end if; -- default 25 MHz return 7; end function; function getmul(constant mode : dcm_freq) return integer is begin if mode = DCM_100MHz then return 27; elsif mode = DCM_75MHz then return 10; elsif mode = DCM_50MHz then return 27; elsif mode = DCM_40MHz then return 27; elsif mode = DCM_25MHz then return 25; elsif mode = DCM_20MHz then return 27; end if; -- default 25 MHz return 25; end function; end clkgen_cfg;
zx-simi
trunk/fpga/FITkit/clkgen_config.vhd
VHDL
oos
3,472
-- vga_ctrl.vhd: VGA base controller -- Copyright (C) 2006 Brno University of Technology, -- Faculty of Information Technology -- Author(s): Ladislav Capka <xcapka01 AT @stud.fit.vutbr.cz> -- -- LICENSE TERMS -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions -- are met: -- 1. Redistributions of source code must retain the above copyright -- notice, this list of conditions and the following disclaimer. -- 2. 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. -- 3. All advertising materials mentioning features or use of this software -- or firmware must display the following acknowledgement: -- -- This product includes software developed by the University of -- Technology, Faculty of Information Technology, Brno and its -- contributors. -- -- 4. Neither the name of the Company 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 or firmware is provided ``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 company 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. -- -- $Id$ -- -- -- SYNTH-ISE-8.1: slices=87, slicesFF=34, 4luts=159 -- SYNTH-ISE-8.2: slices=81, slicesFF=31, 4luts=152 library ieee; use ieee.std_logic_1164.all; use ieee.std_logic_arith.conv_std_logic_vector; use ieee.std_logic_unsigned.all; use work.vga_controller_cfg.all; entity vga_controller is generic ( REQ_DELAY : natural := 1 ); port ( -- Hodiny + reset CLK : in std_logic; RST : in std_logic; ENABLE : in std_logic; -- Nastaveni rozliseni (popis v VGA_CONFIG.VHD) -- Pozor: Hodnota musi zustat stale platna! MODE : in std_logic_vector(60 downto 0); -- Vstup / pozadavek DATA_RED : in std_logic_vector(2 downto 0); DATA_GREEN : in std_logic_vector(2 downto 0); DATA_BLUE : in std_logic_vector(2 downto 0); ADDR_COLUMN : out std_logic_vector(11 downto 0); ADDR_ROW : out std_logic_vector(11 downto 0); -- Vystup na VGA VGA_RED : out std_logic_vector(2 downto 0); VGA_GREEN : out std_logic_vector(2 downto 0); VGA_BLUE : out std_logic_vector(2 downto 0); VGA_HSYNC : out std_logic; VGA_VSYNC : out std_logic; -- H/V Status STATUS_H : out vga_hfsm_state; STATUS_V : out vga_vfsm_state ); end vga_controller; architecture arch_vga_controller of vga_controller is -- Aktivace radice signal ienable : std_logic := '1'; -- Vnitrni reset radice signal ireset : std_logic := '1'; -- Horizontalni hodnoty signal h_pixels : std_logic_vector(11 downto 0); signal h_syncstart : std_logic_vector(6 downto 0); signal h_syncend : std_logic_vector(6 downto 0); signal h_period : std_logic_vector(6 downto 0); -- Vertikalni hodnoty signal v_lines : std_logic_vector(11 downto 0); signal v_syncstart : std_logic_vector(5 downto 0); signal v_syncend : std_logic_vector(3 downto 0); signal v_period : std_logic_vector(5 downto 0); -- MX pro citace signal req_delay_mx : std_logic; signal h_pixels_mx : std_logic; signal v_lines_mx : std_logic; signal h_syncstart_mx : std_logic; signal h_syncend_mx : std_logic; signal h_period_mx : std_logic; signal v_syncstart_mx : std_logic; signal v_syncend_mx : std_logic; signal v_period_mx : std_logic; -- H/V citac signal hcnt : std_logic_vector(11 downto 0) := (others => '0'); signal vcnt : std_logic_vector(11 downto 0) := (others => '0'); -- Reset H/V citace signal hcnt_reset : std_logic := '1'; signal vcnt_reset : std_logic := '1'; -- Aktivace V citace signal vcnt_en : std_logic := '0'; -- Aktivace vstupu/vystupu VGA radice signal out_en : std_logic_vector(1 downto 0); signal req_en : std_logic_vector(1 downto 0); signal use_rqdelay : std_logic := '0'; -- H/V synchronizacni puls signal hsync_en : std_logic := '0'; signal vsync_en : std_logic := '0'; -- Stavy FSMs signal hfsm_cst : vga_hfsm_state; signal hfsm_nst : vga_hfsm_state; signal vfsm_cst : vga_vfsm_state; signal vfsm_nst : vga_vfsm_state; begin -- Nastaveni h_pixels <= MODE(60 downto 49); v_lines <= MODE(48 downto 37); h_syncstart <= MODE(36 downto 30); h_syncend <= MODE(29 downto 23); h_period <= MODE(22 downto 16); v_syncstart <= MODE(15 downto 10); v_syncend <= MODE(9 downto 6); v_period <= MODE(5 downto 0); STATUS_H <= hfsm_cst; STATUS_V <= vfsm_cst; VGA_RED <= DATA_RED when out_en = "11" else (others => '0'); VGA_GREEN <= DATA_GREEN when out_en = "11" else (others => '0'); VGA_BLUE <= DATA_BLUE when out_en = "11" else (others => '0'); VGA_HSYNC <= not hsync_en; VGA_VSYNC <= not vsync_en; ADDR_COLUMN <= hcnt when req_en = "11" else (others => '0'); ADDR_ROW <= vcnt when req_en(1) = '1' else (others => '0'); ireset <= '1' when (RST = '1') or (ienable = '0') else '0'; use_rqdelay <= '0' when REQ_DELAY = 0 else '1'; enable_sync: process (CLK) begin if CLK'event and CLK = '1' then ienable <= ENABLE; end if; end process; fsm_control: process(CLK, ireset) begin if (ireset = '1') then hfsm_cst <= hstDisabled; vfsm_cst <= vstPrepare; elsif CLK'event and CLK = '1' then hfsm_cst <= hfsm_nst; -- Horizontal FSM vfsm_cst <= vfsm_nst; -- Vertical FSM end if; end process; line_fsm: process(hfsm_cst, hcnt, ireset, req_delay_mx, h_pixels_mx, h_syncstart_mx, h_syncend_mx, h_period_mx) begin -- Default hfsm_nst <= hstDisabled; -- Dalsi stav = radic neaktivni vcnt_en <= '0'; -- V citac zastaven out_en(0) <= '0'; -- VGA vystup neaktivni req_en(0) <= '0'; -- Vstupni pozadavky neaktivni hsync_en <= '0'; -- H sync neaktivni hcnt_reset <= '0'; -- Neresetujeme citac case hfsm_cst is when hstDisabled => -- Radic neaktivni hcnt_reset <= '1'; if ireset = '0' then hfsm_nst <= hstPrepare; else hfsm_nst <= hstDisabled; end if; when hstPrepare => -- Citace online hcnt_reset <= '1'; if use_rqdelay = '0' then hfsm_nst <= hstDraw; else hfsm_nst <= hstRequestOnly; end if; when hstRequestOnly => -- Cekani REQ_DELAY pred kreslenim req_en(0) <= '1'; if req_delay_mx = '1' then hfsm_nst <= hstDraw; else hfsm_nst <= hstRequestOnly; end if; when hstDraw => -- Kresleni out_en(0) <= '1'; req_en(0) <= '1'; if h_pixels_mx = '1' then hcnt_reset <= '1'; if use_rqdelay = '0' then hfsm_nst <= hstWaitSync; else hfsm_nst <= hstDrawOnly; end if; else hfsm_nst <= hstDraw; end if; when hstDrawOnly => -- Konec kresleni se spozdenim REQ_DELAY out_en(0) <= '1'; if req_delay_mx = '1' then hcnt_reset <= '1'; hfsm_nst <= hstWaitSync; else hfsm_nst <= hstDrawOnly; end if; when hstWaitSync => -- Cekani pred H sync if h_syncstart_mx = '1' then hcnt_reset <= '1'; hfsm_nst <= hstSync; else hfsm_nst <= hstWaitSync; end if; when hstSync => -- H synchronizacni pulz hsync_en <= '1'; if h_syncend_mx = '1' then hcnt_reset <= '1'; vcnt_en <= '1'; hfsm_nst <= hstWaitPeriod; else hfsm_nst <= hstSync; end if; when hstWaitPeriod => -- Cekani po H sync if h_period_mx = '1' then hcnt_reset <= '1'; if use_rqdelay = '0' then hfsm_nst <= hstDraw; else hfsm_nst <= hstRequestOnly; end if; else hfsm_nst <= hstWaitPeriod; end if; end case; end process; frame_fsm: process(vfsm_cst, vcnt, ireset, v_lines_mx, v_syncstart_mx, v_syncend_mx, v_period_mx) begin vfsm_nst <= vstPrepare; out_en(1) <= '0'; req_en(1) <= '0'; vcnt_reset <= '0'; vsync_en <= '0'; case vfsm_cst is when vstPrepare => -- Start vcnt_reset <= '1'; req_en(1) <= '1'; out_en(1) <= '1'; vfsm_nst <= vstDraw; when vstDraw => -- Kresleni if v_lines_mx = '1' then vcnt_reset <= '1'; vfsm_nst <= vstWaitSync; else req_en(1) <= '1'; out_en(1) <= '1'; vfsm_nst <= vstDraw; end if; when vstWaitSync => -- Cekani pred V sync if v_syncstart_mx = '1' then vcnt_reset <= '1'; vsync_en <= '1'; vfsm_nst <= vstSync; else vfsm_nst <= vstWaitSync; end if; when vstSync => -- V synchronizacni pulz if v_syncend_mx = '1' then vcnt_reset <= '1'; vsync_en <= '0'; vfsm_nst <= vstWaitPeriod; else vsync_en <= '1'; vfsm_nst <= vstSync; end if; when vstWaitPeriod => -- Cekani po V sync if v_period_mx = '1' then vcnt_reset <= '1'; req_en(1) <= '1'; out_en(1) <= '1'; vfsm_nst <= vstDraw; else vfsm_nst <= vstWaitPeriod; end if; end case; end process; -- Comparators req_delay_mx <= use_rqdelay when hcnt(2 downto 0) = conv_std_logic_vector(REQ_DELAY-1, 3) else '0'; h_pixels_mx <= '1' when hcnt(11 downto 0) = h_pixels else '0'; v_lines_mx <= '1' when vcnt(11 downto 0) = v_lines else '0'; h_syncstart_mx <= '1' when hcnt(6 downto 0) = h_syncstart else '0'; h_syncend_mx <= '1' when hcnt(6 downto 0) = h_syncend else '0'; h_period_mx <= '1' when hcnt(6 downto 0) = h_period else '0'; v_syncstart_mx <= '1' when vcnt(5 downto 0) = v_syncstart else '0'; v_syncend_mx <= '1' when vcnt(3 downto 0) = v_syncend else '0'; v_period_mx <= '1' when vcnt(5 downto 0) = v_period else '0'; -- Horizontal/vertical counter hcnt_ctrl: process(CLK, ireset, hcnt_reset) begin if (ireset = '1') then hcnt <= (others => '0'); elsif (CLK'event and CLK = '1') then if hcnt_reset = '1' then hcnt <= (others => '0'); else hcnt <= hcnt + 1; end if; end if; end process; vcnt_ctrl: process(CLK, ireset, vcnt_reset, vcnt_en) begin if (ireset = '1') then vcnt <= (others => '0'); elsif (CLK'event and CLK = '1') then if (vcnt_reset = '1') then vcnt <= (others => '0'); elsif vcnt_en = '1' then vcnt <= vcnt + 1; end if; end if; end process; end arch_vga_controller;
zx-simi
trunk/fpga/FITkit/vga_ctrl.vhd
VHDL
oos
12,669
-- vga_config.vhd: VGA constants & definitions -- Copyright (C) 2006 Brno University of Technology, -- Faculty of Information Technology -- Author(s): Ladislav Capka <xcapka01 AT stud.fit.vutbr.cz> -- -- LICENSE TERMS -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions -- are met: -- 1. Redistributions of source code must retain the above copyright -- notice, this list of conditions and the following disclaimer. -- 2. 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. -- 3. All advertising materials mentioning features or use of this software -- or firmware must display the following acknowledgement: -- -- This product includes software developed by the University of -- Technology, Faculty of Information Technology, Brno and its -- contributors. -- -- 4. Neither the name of the Company 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 or firmware is provided ``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 company 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. -- -- $Id$ -- -- library ieee; use ieee.std_logic_1164.all; use ieee.std_logic_arith.all; package vga_controller_cfg is type modes is (rUnknown, r640x480x60, r640x480x66, --r640x480x72, r640x480x75, --r720x400x70, r720x350x70, --r800x600x56, r800x600x60, r800x600x72); type vga_hfsm_state is (hstDisabled, hstPrepare, hstRequestOnly, hstDraw, hstDrawOnly, hstWaitSync, hstSync, hstWaitPeriod); type vga_vfsm_state is (vstPrepare, vstDraw, vstWaitSync, vstSync, vstWaitPeriod); subtype resolution is std_logic_vector(11 downto 0); subtype color is integer range 0 to 7; procedure setrgb(signal r, g, b : out std_logic_vector(2 downto 0); constant val_r, val_g, val_b : color); procedure setmode(constant mode : modes; signal settings : out std_logic_vector(60 downto 0)); end vga_controller_cfg; package body vga_controller_cfg is procedure setrgb(signal r, g, b : out std_logic_vector(2 downto 0); constant val_r, val_g, val_b : color) is begin r <= conv_std_logic_vector(val_r, 3); g <= conv_std_logic_vector(val_g, 3); b <= conv_std_logic_vector(val_b, 3); end setrgb; procedure setmode(constant mode : modes; signal settings : out std_logic_vector(60 downto 0)) is begin case mode is when r640x480x60 => settings(60 downto 49) <= conv_std_logic_vector(640 -1, 12); -- h_pixels 12 bit (0-4095) settings(48 downto 37) <= conv_std_logic_vector(480 -0, 12); -- v_lines 12 bit (0-4095) settings(36 downto 30) <= conv_std_logic_vector(16 -1, 7); -- h_syncstart 7 bit (0-127) settings(29 downto 23) <= conv_std_logic_vector(96 -1, 7); -- h_syncend 7 bit (0-127) settings(22 downto 16) <= conv_std_logic_vector(48 -1, 7); -- h_period 7 bit (0-127) settings(15 downto 10) <= conv_std_logic_vector(10 -0, 6); -- v_syncstart 6 bit (0-63) settings(9 downto 6) <= conv_std_logic_vector(2 -0, 4); -- v_syncend 4 bit (0-63) settings(5 downto 0) <= conv_std_logic_vector(33 -0, 6); -- v_period 6 bit (0-63) when r640x480x66 => settings(60 downto 49) <= conv_std_logic_vector(640 -1, 12); settings(48 downto 37) <= conv_std_logic_vector(480 -0, 12); settings(36 downto 30) <= conv_std_logic_vector(61 -1, 7); settings(29 downto 23) <= conv_std_logic_vector(64 -1, 7); settings(22 downto 16) <= conv_std_logic_vector(99 -1, 7); settings(15 downto 10) <= conv_std_logic_vector(1 -0, 6); settings(9 downto 6) <= conv_std_logic_vector(3 -0, 4); settings(5 downto 0) <= conv_std_logic_vector(41 -0, 6); when r800x600x72 => settings(60 downto 49) <= conv_std_logic_vector(800 -1, 12); settings(48 downto 37) <= conv_std_logic_vector(600 -0, 12); settings(36 downto 30) <= conv_std_logic_vector(53 -1, 7); settings(29 downto 23) <= conv_std_logic_vector(120 -1, 7); settings(22 downto 16) <= conv_std_logic_vector(67 -1, 7); settings(15 downto 10) <= conv_std_logic_vector(35 -0, 6); settings(9 downto 6) <= conv_std_logic_vector(6 -0, 4); settings(5 downto 0) <= conv_std_logic_vector(25 -0, 6); when others => settings(60 downto 49) <= conv_std_logic_vector(0, 12); settings(48 downto 37) <= conv_std_logic_vector(0, 12); settings(36 downto 30) <= conv_std_logic_vector(0, 7); settings(29 downto 23) <= conv_std_logic_vector(0, 7); settings(22 downto 16) <= conv_std_logic_vector(0, 7); settings(15 downto 10) <= conv_std_logic_vector(0, 6); settings(9 downto 6) <= conv_std_logic_vector(0, 4); settings(5 downto 0) <= conv_std_logic_vector(0, 6); end case; end setmode; end vga_controller_cfg;
zx-simi
trunk/fpga/FITkit/vga_config.vhd
VHDL
oos
6,214
-- ps2_entity.vhd: PS/2 Controller entity -- Copyright (C) 2006 Brno University of Technology, -- Faculty of Information Technology -- Author(s): Zdenek Vasicek <xvasic11 AT stud.fit.vutbr.cz> -- -- LICENSE TERMS -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions -- are met: -- 1. Redistributions of source code must retain the above copyright -- notice, this list of conditions and the following disclaimer. -- 2. 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. -- 3. All advertising materials mentioning features or use of this software -- or firmware must display the following acknowledgement: -- -- This product includes software developed by the University of -- Technology, Faculty of Information Technology, Brno and its -- contributors. -- -- 4. Neither the name of the Company 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 or firmware is provided ``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 company 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. -- -- $Id$ -- -- library IEEE; use IEEE.STD_LOGIC_1164.ALL; use IEEE.STD_LOGIC_ARITH.ALL; use IEEE.STD_LOGIC_UNSIGNED.ALL; entity PS2_controller is port ( -- Reset a synchronizace RST : in std_logic; CLK : in std_logic; -- Rozhrani PS/2 PS2_CLK : inout std_logic; PS2_DATA : inout std_logic; -- Vstup (zapis do zarizeni) DATA_IN : in std_logic_vector(7 downto 0); WRITE_EN : in std_logic; -- Vystup (cteni ze zarizeni) DATA_OUT : out std_logic_vector(7 downto 0); DATA_VLD : out std_logic; DATA_ERR : out std_logic ); end PS2_controller;
zx-simi
trunk/fpga/FITkit/ps2_entity.vhd
VHDL
oos
2,668
-- trilobot_entity.vhd: Trilobot driver entity -- Copyright (C) 2009 Brno University of Technology, -- Faculty of Information Technology -- Author(s): Michal Růžek <xruzek01 AT stud.fit.vutbr.cz> -- -- LICENSE TERMS -- -- Redistribution and use in source and binary forms, with or without -- modification, are permitted provided that the following conditions -- are met: -- 1. Redistributions of source code must retain the above copyright -- notice, this list of conditions and the following disclaimer. -- 2. 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. -- 3. All advertising materials mentioning features or use of this software -- or firmware must display the following acknowledgement: -- -- This product includes software developed by the University of -- Technology, Faculty of Information Technology, Brno and its -- contributors. -- -- 4. Neither the name of the Company 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 or firmware is provided ``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 company 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. -- -- $Id$ -- -- library IEEE; use IEEE.STD_LOGIC_1164.ALL; use IEEE.STD_LOGIC_ARITH.ALL; use IEEE.STD_LOGIC_UNSIGNED.ALL; use ieee.numeric_std.all; entity SDCARD is port ( -- Reset a synchronizace RESET : in std_logic; CLK : in std_logic; -- Datova a adresova sbernice DATA_IN : in std_logic_vector(7 downto 0); DATA_OUT : out std_logic_vector(7 downto 0); ADDR : in std_logic_vector(2 downto 0); WRITE_EN : in std_logic; READ_EN : in std_logic; WAIT_n : out std_logic; ACK : out std_logic; -- Rozhrani SD karty SD_CLK : out std_logic; SD_CS : out std_logic; SD_MOSI : out std_logic; SD_MISO : in std_logic ); end SDCARD; architecture behav of sdcard is -- SPI component spi port ( -- Reset a synchronizace RESET : in std_logic; CLK : in std_logic; -- Datova a adresova sbernice DATA_IN : in std_logic_vector(7 downto 0); DATA_OUT : out std_logic_vector(7 downto 0); WRITE_EN : in std_logic; READY : out std_logic; -- Rozhrani SD karty SCLK : out std_logic; MOSI : out std_logic; MISO : in std_logic ); end component; signal spi_data_out : std_logic_vector(7 downto 0); signal spi_data_in : std_logic_vector(7 downto 0); signal spi_write_en : std_logic; signal spi_ready : std_logic; signal spi_ready_out : std_logic; signal spi_sd_data_out : std_logic; signal spi_data_out_00 : std_logic; signal spi_data_out_01 : std_logic; signal spi_data_out_FF : std_logic; -- zbytek signal count : std_logic_vector(8 downto 0); signal count_rst : std_logic; signal count_inc : std_logic; signal count_FF : std_logic; signal reg0 : std_logic_vector(5 downto 0); signal reg1 : std_logic_vector(7 downto 0); signal reg2 : std_logic_vector(7 downto 0); signal reg3 : std_logic_vector(7 downto 0); signal reg4 : std_logic_vector(7 downto 0); signal reg_rst : std_logic; -- signal status : std_logic_vector(7 downto 0); -- status registr signal control : std_logic_vector(7 downto 0); -- ridici registr type tstate is (S_AAA, S_RESET, S_RESET2, S_RESET3, S_CMD0, S_CMD0_2, S_CMD0_R1, S_CMD0_R1_test, S_CMD0_R1_test2, S_CMD1, S_CMD1_2, S_CMD1_R1, S_CMD1_R1_test, S_CMD1_R1_test2, S_CMD17, S_CMD17_2, S_CMD17_R1, S_CMD17_R1_test, S_CMD17_START, S_CMD17_STARTtest, S_CMD17_R1_test2, S_READ, S_READ_test, S_CRC1, S_CRC1a, S_CRC2, S_CRC2a, S_READY, S_HALT); signal present_state, next_state : tstate; type tcmdstate is (S_CMD, S_CMDa, S_CMD_2, S_CMD_2a, S_CMD_3, S_CMD_3a, S_CMD_4, S_CMD_4a, S_CMD_5, S_CMD_5a, S_CMD_6, S_CMD_6a, S_R1, S_R1a, SS_READY); signal cmd_present, cmd_next : tcmdstate; signal cmd_ready : std_logic; signal cmd_r1 : std_logic; signal cmd_command : std_logic; signal command0 : std_logic_vector(7 downto 0); signal command1 : std_logic_vector(7 downto 0); signal command2 : std_logic_vector(7 downto 0); signal command3 : std_logic_vector(7 downto 0); signal command4 : std_logic_vector(7 downto 0); signal clk_div : std_logic; signal clk_div_reg : std_logic_vector(3 downto 0); begin process(RESET,CLK) begin if RESET='1' then CLK_DIV_reg <= (others=>'0'); elsif CLK'event and CLK='1' then CLK_DIV_reg <= clk_div_reg + 1; end if; end process; clk_div <= clk_div_reg(1); karta_spi : spi port map ( RESET => RESET, CLK => clk_div, -- Datova a adresova sbernice DATA_IN => spi_data_in, DATA_OUT => spi_data_out, WRITE_EN => spi_write_en, READY => spi_ready_out, -- Rozhrani SD karty SCLK => SD_CLK, MOSI => spi_sd_data_out, MISO => SD_MISO ); process(CLK) begin if CLK'event and CLK='1' then spi_ready <= spi_ready_out; end if; end process; -- pokud neni povoleno odesilani, pripojim na vystup log 1 SD_MOSI <= spi_sd_data_out; -- zapis do registru process(CLK, reg_rst) begin if reg_rst='1' then control <= (others=>'0'); elsif CLK'event and CLK='1' then if WRITE_EN='1' then case ADDR is when "000" => reg0 <= DATA_IN(5 downto 0); -- Prikaz when "001" => reg1 <= DATA_IN; -- Argument nejvyssi bajt when "010" => reg2 <= DATA_IN; when "011" => reg3 <= DATA_IN; when "100" => reg4 <= DATA_IN; -- Argument nejnizsi bajt when "101" => control <= DATA_IN; -- ridici registr when others => null; end case; end if; end if; end process; DATA_OUT <= spi_data_out; --adresovy dekoder na vystupu -- with ADDR select -- DATA_OUT <= "00" & reg0 when "000", -- reg1 when "001", -- reg2 when "010", -- reg3 when "011", -- reg4 when "100", -- control when "101", -- status when "110", -- spi_data_out when others; -------------------------------------------------------------------------------- -- komunikace s SPI jednotkou SD_SPI_FSM: process(cmd_present, cmd_command, cmd_r1, command0, spi_ready, command1, command2, command3, command4) begin spi_data_in <= "00000000"; spi_write_en <= '0'; cmd_ready <= '0'; case cmd_present is when SS_READY => cmd_ready <= '1'; cmd_next<= SS_READY; if cmd_command='1' then cmd_next <= S_CMD; elsif cmd_r1='1' then cmd_next <= S_R1; end if; when S_CMD => -- kod prikazu spi_data_in <= command0; spi_write_en <= '1'; cmd_next <= S_CMD; if spi_ready='0' then cmd_next <= S_CMDa; end if; when S_CMDa => cmd_next <= S_CMDa; if spi_ready='1' then cmd_next <= S_CMD_2; end if; when S_CMD_2 => -- druhy bajt 4. cast adresy spi_data_in <= command1; spi_write_en <= '1'; cmd_next <= S_CMD_2; if spi_ready='0' then cmd_next <= S_CMD_2a; end if; when S_CMD_2a => cmd_next <= S_CMD_2a; if spi_ready='1' then cmd_next <= S_CMD_3; end if; when S_CMD_3 => -- treti bajt 3. cast adresy spi_data_in <= command2; spi_write_en <= '1'; cmd_next <= S_CMD_3; if spi_ready='0' then cmd_next <= S_CMD_3a; end if; when S_CMD_3a => cmd_next <= S_CMD_3a; if spi_ready='1' then cmd_next <= S_CMD_4; end if; when S_CMD_4 => -- ctvrty bajt 2. cast adresy spi_data_in <= command3; spi_write_en <= '1'; cmd_next <= S_CMD_4; if spi_ready='0' then cmd_next <= S_CMD_4a; end if; when S_CMD_4a => cmd_next <= S_CMD_4a; if spi_ready='1' then cmd_next <= S_CMD_5; end if; when S_CMD_5 => -- paty bajt 1. cast adresy spi_data_in <= command4; spi_write_en <= '1'; cmd_next <= S_CMD_5; if spi_ready='0' then cmd_next <= S_CMD_5a; end if; when S_CMD_5a => cmd_next <= S_CMD_5a; if spi_ready='1' then cmd_next <= S_CMD_6; end if; when S_CMD_6 => -- sesty bajt (CRC) spi_data_in <= X"95"; spi_write_en <= '1'; cmd_next <= S_CMD_6; if spi_ready='0' then cmd_next <= S_CMD_6a; end if; when S_CMD_6a => cmd_next <= S_CMD_6a; if spi_ready='1' then cmd_next <= SS_READY; end if; -- cekam na odpoved R1 nebo pouze prijimam nejaky bajt a odesilam "FF" when S_R1 => spi_data_in <= X"FF"; spi_write_en <= '1'; cmd_next <= S_R1; if spi_ready='0' then cmd_next <= S_R1a; end if; when S_R1a => cmd_next <= S_R1a; if spi_ready='1' then cmd_next <= SS_READY; end if; when others => cmd_next <= SS_READY; end case; end process; -- prepinani stavu FSM process(RESET,CLK) begin if RESET='1' then cmd_present <= SS_READY; elsif CLK'event and CLK='1' then cmd_present <= cmd_next; end if; end process; -------------------------------------------------------------------------------- -- registr pocitadlo process (count_rst,CLK) begin if count_rst='1' then count <= (others=>'0'); elsif CLK'event and CLK='1' then if count_inc='1' then count <= count + 1; end if; end if; end process; count_FF <= '1' when count="111111111" else '0'; spi_data_out_00 <= '1' when spi_data_out=X"00" else '0'; spi_data_out_01 <= '1' when spi_data_out=X"01" else '0'; spi_data_out_FF <= '1' when spi_data_out=X"FF" else '0'; SD_FSM : process (present_state, count, reg0,reg1,reg2,reg3,reg4,spi_data_out,cmd_ready, control, count_FF, spi_data_out_01, spi_data_out_00, spi_data_out_FF, READ_EN) begin SD_CS <= '1'; count_rst <= '0'; count_inc <= '0'; reg_rst <= '0'; cmd_command <= '0'; cmd_r1 <= '0'; command0 <= (others=>'1'); command1 <= (others=>'1'); command2 <= (others=>'1'); command3 <= (others=>'1'); command4 <= (others=>'1'); -- status <= X"00"; WAIT_n <= '1'; ACK <= '0'; case present_state is when S_AAA => -- status <= X"01"; count_rst <= '1'; reg_rst <= '1'; next_state <= S_RESET; -- po resetu musim pockat minimalne 74 taktu, nez prejdu do dalsiho stavu when S_RESET => -- status <= X"02"; cmd_r1 <= '1'; next_state <= S_RESET; if cmd_ready='0' then next_state <= S_RESET2; end if; when S_RESET2 => -- status <= X"03"; next_state <= S_RESET2; if cmd_ready='1' then next_state <= S_RESET3; end if; when S_RESET3 => -- status <= X"04"; count_inc <= '1'; next_state <= S_RESET; if count_FF='1' then next_state <= S_CMD0; end if; -------------------------------------------------------------------- -- prikaz CMD0 - softwarovy reset when S_CMD0 => -- status <= X"05"; SD_CS <= '0'; cmd_command <= '1'; command0 <= X"40"; command1 <= X"00"; command2 <= X"00"; command3 <= X"00"; command4 <= X"00"; next_state <= S_CMD0; if cmd_ready='0' then next_state <= S_CMD0_2; end if; -- cekam na dokonceni odesilani when S_CMD0_2 => -- status <= X"06"; SD_CS <= '0'; command0 <= X"40"; command1 <= X"00"; command2 <= X"00"; command3 <= X"00"; command4 <= X"00"; next_state <= S_CMD0_2; if cmd_ready='1' then next_state <= S_CMD0_R1; end if; -- prijmu odpoved R1 when S_CMD0_R1 => -- status <= X"07"; SD_CS <= '0'; cmd_r1 <= '1'; next_state <= S_CMD0_R1; if cmd_ready='0' then next_state <= S_CMD0_R1_test; end if; -- vyhodnotim odpoved R1 when S_CMD0_R1_test => -- status <= X"08"; SD_CS <= '0'; next_state <= S_CMD0_R1_test; if cmd_ready='1' then next_state <= S_CMD0_R1_test2; end if; when S_CMD0_R1_test2 => next_state <= s_CMD0_R1; if spi_data_out_01='1' then -- jsem v iddle stavu next_state <= S_CMD1; end if; -------------------------------------------------------------------- -- prikaz CMD1 - inicializace karty when S_CMD1 => --- status <= X"09"; SD_CS <= '0'; cmd_command <= '1'; command0 <= X"41"; command1 <= X"00"; command2 <= X"00"; command3 <= X"00"; command4 <= X"00"; next_state <= S_CMD1; if cmd_ready='0' then next_state <= S_CMD1_2; end if; --cekam na dokonceni odesilani when S_CMD1_2 => -- status <= X"0A"; SD_CS <= '0'; command0 <= X"41"; command1 <= X"00"; command2 <= X"00"; command3 <= X"00"; command4 <= X"00"; next_state <= S_CMD1_2; if cmd_ready='1' then next_state <= S_CMD1_R1; end if; -- prijmu odpoved R1 when S_CMD1_R1 => -- status <= X"0B"; SD_CS <= '0'; cmd_r1 <= '1'; next_state <= S_CMD1_R1; if cmd_ready='0' then next_state <= S_CMD1_R1_test; end if; -- vyhodnotim odpoved R1 when S_CMD1_R1_test => -- status <= X"0C"; SD_CS <= '0'; next_state <= S_CMD1_R1_test; if cmd_ready='1' then next_state <= S_CMD1_R1_test2; end if; when S_CMD1_R1_test2 => next_state <= S_CMD1_R1; if spi_data_out_00='1' then next_state <= S_READY; elsif spi_data_out_01='1' then next_state <= S_CMD1; end if; -------------------------------------------------------------------- -- prikaz CMD17 - cteni z karty when S_CMD17 => -- status <= X"0D"; reg_rst <= '1'; -- vymazu prikaz z registru, aby se po dokonceni znovu nespustil SD_CS <= '0'; cmd_command <= '1'; command0 <= "01" & reg0; command1 <= reg1; command2 <= reg2; command3 <= reg3; command4 <= reg4; next_state <= S_CMD17; if cmd_ready='0' then next_state <= S_CMD17_2; end if; --cekam na dokonceni odesilani when S_CMD17_2 => -- status <= X"0E"; SD_CS <= '0'; command0 <= "01" & reg0; command1 <= reg1; command2 <= reg2; command3 <= reg3; command4 <= reg4; next_state <= S_CMD17_2; if cmd_ready='1' then next_state <= S_CMD17_R1; end if; -- prijmu odpoved R1 when S_CMD17_R1 => -- status <= X"0F"; SD_CS <= '0'; cmd_r1 <= '1'; next_state <= S_CMD17_R1; if cmd_ready='0' then next_state <= S_CMD17_R1_test; end if; -- vyhodnotim odpoved R1 when S_CMD17_R1_test => -- status <= X"10"; SD_CS <= '0'; next_state <= S_CMD17_R1_test; if cmd_ready='1' then next_state <= S_CMD17_R1_test2; end if; when S_CMD17_R1_test2 => next_state <= S_READY; if spi_data_out_FF='1' then -- zatim jsem nedostal odpoved next_state <= S_CMD17_R1; end if; when S_READ => WAIT_n <= '0'; -- status <= X"11"; SD_CS <= '0'; cmd_r1 <= '1'; -- prijmu jeden bajt reg_rst <= '1'; -- vymazu prikaz z registru, aby se po dokonceni znovu nespustil next_state <= S_READ; if cmd_ready='0' then next_state <= S_READ_test; end if; when S_READ_test => WAIT_n <= '0'; -- status <= X"12"; SD_CS <= '0'; next_state <= S_READ_test; if cmd_ready='1' then next_state <= S_READY; ACK <= '1'; end if; -- Radic je volny a ceka na nejaky prikaz na vstupu. Akce se odstartuje zapisem do registru reg0 when S_READY => -- status <= X"13"; SD_CS <= '0'; next_state <= S_READY; if control(0)='1' then -- odeslat prikaz next_state <= S_CMD17; elsif READ_EN='1' then -- precte bajt next_state <= S_READ; WAIT_n <= '0'; end if; when S_HALT => next_state <= S_HALT; when others => next_state <= S_HALT; end case; end process; -- prepinani stavu u FSM process (RESET,CLK) begin if RESET='1' then present_state <= S_AAA; elsif CLK'event and CLK='1' then present_state <= next_state; end if; end process; end behav;
zx-simi
trunk/fpga/sdcard.vhd
VHDL
oos
21,718
library IEEE; use ieee.std_logic_1164.ALL; use ieee.std_logic_ARITH.ALL; use ieee.std_logic_UNSIGNED.ALL; entity MOUSE is port ( CLK : in std_logic; RESET : in std_logic; -- komunikace s procesorem ADDR : in std_logic_vector(15 downto 0); DATA_OUT : out std_logic_vector(7 downto 0); -- signaly pro komunikaci s PS2 vystupem z FPGA M_CLK : inout std_logic; M_DATA : inout std_logic ); end entity; architecture behav of MOUSE is -- PS/2 controller component PS2_controller is port ( -- Reset a synchronizace RST : in std_logic; CLK : in std_logic; -- Rozhrani PS/2 PS2_CLK : inout std_logic; PS2_DATA : inout std_logic; -- Vstup (zapis do zarizeni) DATA_IN : in std_logic_vector(7 downto 0); WRITE_EN : in std_logic; -- Vystup (cteni ze zarizeni) DATA_OUT : out std_logic_vector(7 downto 0); DATA_VLD : out std_logic; DATA_ERR : out std_logic ); end component; for ps2mouse: PS2_controller use entity work.PS2_controller(full); signal PS2_DATA_OUT : std_logic_vector(7 downto 0); signal PS2_DATA_IN : std_logic_vector(7 downto 0); signal PS2_WRITE_EN : std_logic; signal PS2_DATA_OUT_VLD : std_logic; type t_state is (S_RESET, S_WAIT, S_ENABLE_DATA_REPORTING1, S_ENABLE_DATA_REPORTING2, S_BYTE2, S_BYTE3, S_CHANGE); signal present_state, next_state : t_state; signal K_ADDR : std_logic_vector(1 downto 0); signal BYTE1 : std_logic_vector(7 downto 0); signal BYTE1_NOT : std_logic_vector(2 downto 0); signal BYTE1_VLD : std_logic; signal BYTE2 : std_logic_vector(7 downto 0); signal BYTE2_VLD : std_logic; signal BYTE3 : std_logic_vector(7 downto 0); signal BYTE3_VLD : std_logic; signal CHANGE : std_logic; -- registry kempston mys signal K_AXIS_X : std_logic_vector(7 downto 0); signal K_AXIS_Y : std_logic_vector(7 downto 0); signal K_BUTTON : std_logic_vector(2 downto 0); begin ps2mouse: PS2_controller port map ( RST => RESET, CLK => CLK, PS2_CLK => M_CLK, PS2_DATA => M_DATA, DATA_IN => PS2_DATA_IN, WRITE_EN => PS2_WRITE_EN, DATA_OUT => PS2_DATA_OUT, DATA_VLD => PS2_DATA_OUT_VLD, DATA_ERR => open ); K_ADDR <= ADDR(10) & ADDR(8); with K_ADDR select DATA_OUT <= "11111" & K_BUTTON(2 downto 0) when "00", K_AXIS_X when "01", K_AXIS_Y when "11", X"00" when others; BYTE1_NOT <= not BYTE1(2 downto 0); -- kempston mouse registr se stavem tlacitek process(RESET,CLK) begin if RESET='1' then K_BUTTON <= (others=>'1'); elsif CLK'event and CLK='1' then if CHANGE='1' then K_BUTTON(0) <= BYTE1_NOT(1); K_BUTTON(1) <= BYTE1_NOT(0); K_BUTTON(2) <= BYTE1_NOT(2); end if; end if; end process; -- kempston mouse osa X process(RESET,CLK) begin if RESET='1' then K_AXIS_X <= (others=>'0'); elsif CLK'event and CLK='1' then if CHANGE='1' then K_AXIS_X <= K_AXIS_X + BYTE2; end if; end if; end process; -- kempston mouse osa Y process(RESET, CLK) begin if RESET='1' then K_AXIS_Y <= (others=>'0'); elsif CLK'event and CLK='1' then if CHANGE='1' then K_AXIS_Y <= K_AXIS_Y + BYTE3; end if; end if; end process; -- prvni zachytny registr process(CLK) begin if CLK'event and CLK='1' then if BYTE1_VLD='1' then BYTE1 <= PS2_DATA_OUT; end if; end if; end process; -- druhy zachytny registr process(CLK) begin if CLK'event and CLK='1' then if BYTE2_VLD='1' then BYTE2 <= PS2_DATA_OUT; end if; end if; end process; -- treti zachytny registr process(CLK) begin if CLK'event and CLK='1' then if BYTE3_VLD='1' then BYTE3 <= PS2_DATA_OUT; end if; end if; end process; FSM_MOUSE: process (present_state, PS2_DATA_OUT_VLD, PS2_DATA_OUT, BYTE1) begin PS2_DATA_IN <= X"00"; PS2_WRITE_EN <= '0'; BYTE1_VLD <= '0'; BYTE2_VLD <= '0'; BYTE3_VLD <= '0'; CHANGE <= '0'; case(present_state) is when S_RESET => next_state <= S_ENABLE_DATA_REPORTING1; when S_ENABLE_DATA_REPORTING1 => PS2_DATA_IN <= X"F4"; PS2_WRITE_EN <= '1'; next_state <= S_ENABLE_DATA_REPORTING2; when S_ENABLE_DATA_REPORTING2 => next_state <= S_ENABLE_DATA_REPORTING2; if PS2_DATA_OUT_VLD='1' and PS2_DATA_OUT=X"FA" then next_state <= S_WAIT; end if; when S_WAIT => BYTE1_VLD <= '1'; -- budu zachytavat data do prvniho registru next_state <= S_WAIT; if PS2_DATA_OUT_VLD='1' and BYTE1(3)='1' then next_state <= S_BYTE2; end if; when S_BYTE2 => BYTE2_VLD <= '1'; -- budu zachytavat data do druheho registru next_state <= S_BYTE2; if PS2_DATA_OUT_VLD='1' then next_state <= S_BYTE3; end if; when S_BYTE3 => BYTE3_VLD <= '1'; -- budu zachytavat data do tretiho registru next_state <= S_BYTE3; if PS2_DATA_OUT_VLD='1' then next_state <= S_CHANGE; end if; when S_CHANGE => CHANGE <= '1'; next_state <= S_WAIT; when others => next_state <= S_RESET; end case; end process; process (RESET,CLK) begin if RESET='1' then present_state <= S_RESET; elsif CLK'event and CLK='1' then present_state <= next_state; end if; end process; end architecture behav;
zx-simi
trunk/fpga/mouse.vhd
VHDL
oos
7,081
-------------------------------------------------------------------------------- -- Company: -- Engineer: -- -- Create Date: 20:31:46 11/29/2013 -- Design Name: -- Module Name: D:/fuck/fpga/cpu_wrapper_tb.vhd -- Project Name: Xilinx -- Target Device: -- Tool versions: -- Description: -- -- VHDL Test Bench Created by ISE for module: cpu_wrapper -- -- Dependencies: -- -- Revision: -- Revision 0.01 - File Created -- Additional Comments: -- -- Notes: -- This testbench has been automatically generated using types std_logic and -- std_logic_vector for the ports of the unit under test. Xilinx recommends -- that these types always be used for the top-level I/O of a design in order -- to guarantee that the testbench will bind correctly to the post-implementation -- simulation model. -------------------------------------------------------------------------------- LIBRARY ieee; USE ieee.std_logic_1164.ALL; Library UNISIM; use UNISIM.vcomponents.all; -- Uncomment the following library declaration if using -- arithmetic functions with Signed or Unsigned values --USE ieee.numeric_std.ALL; ENTITY cpu_wrapper_tb IS END cpu_wrapper_tb; ARCHITECTURE behavior OF cpu_wrapper_tb IS --Inputs signal RESET : std_logic := '0'; signal CLK : std_logic := '0'; signal CLK_CPU : std_logic := '0'; signal DIN : std_logic_vector(7 downto 0) := (others => '0'); signal MEM_DIN_VLD : std_logic := '0'; signal MEM_DOUT_VLD : std_logic := '0'; signal IO_DIN_VLD : std_logic := '0'; signal IO_DOUT_VLD : std_logic := '0'; signal INT : std_logic := '0'; --Outputs signal ADDR : std_logic_vector(15 downto 0); signal MEM_DIN_RD : std_logic; signal DOUT : std_logic_vector(7 downto 0); signal MEM_DOUT_WR : std_logic; signal IO_DIN_RD : std_logic; signal IO_DOUT_WR : std_logic; -- Clock period definitions constant CLK_period : time := 10 ns; BEGIN -- Instantiate the Unit Under Test (UUT) uut: entity work.cpu_wrapper_clk PORT MAP ( RESET => RESET, CLK => CLK, CLK_CPU => CLK_CPU, ADDR => ADDR, DIN => DIN, DOUT => DOUT, MEM_DIN_RD => MEM_DIN_RD, MEM_DIN_VLD => MEM_DIN_VLD, MEM_DOUT_WR => MEM_DOUT_WR, MEM_DOUT_VLD => MEM_DOUT_VLD, IO_DIN_RD => IO_DIN_RD, IO_DIN_VLD => IO_DIN_VLD, IO_DOUT_WR => IO_DOUT_WR, IO_DOUT_VLD => IO_DOUT_VLD, INT => INT ); -- Clock process definitions CLK_process :process begin CLK <= '0'; wait for CLK_period/2; CLK <= '1'; wait for CLK_period/2; end process; -- Clock process definitions CLK_CPU_process :process begin CLK_CPU <= '0'; wait for CLK_period*3; CLK_CPU <= '1'; wait for CLK_period*3; end process; process(ADDR, MEM_DIN_VLD, IO_DIN_VLD) begin DIN <= (others=>'0'); if MEM_DIN_VLD='1' then case ADDR is when X"0001" => DIN <= X"C3"; -- JP 0x0025 when X"0002" => DIN <= X"25"; when X"0003" => DIN <= X"00"; -- LD A,0xA5 when X"0025" => DIN <= X"3E"; when X"0026" => DIN <= X"A5"; -- LD B, 0x45 when X"0027" => DIN <= X"06"; when X"0028" => DIN <= X"46"; -- LD C, 0x46 when X"0029" => DIN <= X"0E"; when X"002A" => DIN <= X"45"; -- LD (BC), A when X"002B" => DIN <= X"02"; -- IN A, when X"002C" => DIN <= X"DB"; when X"002D" => DIN <= X"1F"; -- OUT (C),B when X"002E" => DIN <= X"ED"; when X"002F" => DIN <= X"41"; when others => null; end case; elsif IO_DIN_VLD='1' then case ADDR is when X"A51F" => DIN <= X"88"; when others => null; end case; end if; end process; process begin wait until MEM_DIN_RD='1'; wait until CLK'event and CLK='1'; wait until CLK'event and CLK='1'; wait until CLK'event and CLK='1'; wait until CLK'event and CLK='1'; wait until CLK'event and CLK='1'; wait until CLK'event and CLK='1'; wait until CLK'event and CLK='1'; wait until CLK'event and CLK='1'; MEM_DIN_VLD <= '1'; wait until CLK'event and CLK='1'; MEM_DIN_VLD <= '0'; end process; process begin wait until IO_DIN_RD='1'; wait until CLK'event and CLK='1'; wait until CLK'event and CLK='1'; wait until CLK'event and CLK='1'; wait until CLK'event and CLK='1'; wait until CLK'event and CLK='1'; wait until CLK'event and CLK='1'; wait until CLK'event and CLK='1'; wait until CLK'event and CLK='1'; IO_DIN_VLD <= '1'; wait until CLK'event and CLK='1'; IO_DIN_VLD <= '0'; end process; process begin wait until MEM_DOUT_WR='1'; wait until CLK'event and CLK='1'; wait until CLK'event and CLK='1'; wait until CLK'event and CLK='1'; wait until CLK'event and CLK='1'; wait until CLK'event and CLK='1'; wait until CLK'event and CLK='1'; wait until CLK'event and CLK='1'; wait until CLK'event and CLK='1'; MEM_DOUT_VLD <= '1'; wait until CLK'event and CLK='1'; MEM_DOUT_VLD <= '0'; end process; process begin wait until IO_DOUT_WR='1'; wait until CLK'event and CLK='1'; wait until CLK'event and CLK='1'; wait until CLK'event and CLK='1'; wait until CLK'event and CLK='1'; wait until CLK'event and CLK='1'; wait until CLK'event and CLK='1'; wait until CLK'event and CLK='1'; wait until CLK'event and CLK='1'; IO_DOUT_VLD <= '1'; wait until CLK'event and CLK='1'; IO_DOUT_VLD <= '0'; end process; -- Stimulus process stim_proc: process begin -- hold reset state for 100 ns. reset <= '1'; wait for 100 ns; reset <= '0'; -- insert stimulus here wait; end process; END;
zx-simi
trunk/fpga/testbench/cpu_wrapper_tb.vhd
VHDL
oos
6,326
library IEEE; Library UNISIM; use UNISIM.vcomponents.all; use ieee.std_logic_1164.ALL; use ieee.std_logic_ARITH.ALL; use ieee.std_logic_UNSIGNED.ALL; entity cpu_wrapper_clk is port ( RESET : in std_logic; CLK : in std_logic; CLK_CPU : in std_logic; ADDR : out std_logic_vector(15 downto 0); DIN : in std_logic_vector(7 downto 0); DOUT : out std_logic_vector(7 downto 0); MEM_DIN_RD : out std_logic; MEM_DIN_VLD : in std_logic; MEM_DOUT_WR : out std_logic; MEM_DOUT_VLD : in std_logic; IO_DIN_RD : out std_logic; IO_DIN_VLD : in std_logic; IO_DOUT_WR : out std_logic; IO_DOUT_VLD : in std_logic; INT : in std_logic ); end entity; architecture cpu_wrapper_clk_inst of cpu_wrapper_clk is signal cpu_addr : std_logic_vector(15 downto 0); signal cpu_din : std_logic_vector(7 downto 0); signal cpu_dout : std_logic_vector(7 downto 0); signal cpu_mem_din_rd : std_logic; signal cpu_mem_din_vld : std_logic; signal cpu_mem_dout_wr : std_logic; signal cpu_mem_dout_vld : std_logic; signal cpu_io_din_rd : std_logic; signal cpu_io_din_vld : std_logic; signal cpu_io_dout_wr : std_logic; signal cpu_io_dout_vld : std_logic; signal din_reset : std_logic; signal reg_cpu_mem_din_rd : std_logic; signal reg_cpu_mem_dout_wr : std_logic; signal reg_cpu_io_din_rd : std_logic; signal reg_cpu_io_dout_wr : std_logic; signal cpu_int : std_logic; signal cpu_int_counter : std_logic_vector(5 downto 0); begin process(CLK) begin if CLK'event and CLK='1' then ADDR <= cpu_addr; DOUT <= cpu_dout; if RESET='1' or din_reset='1' then cpu_din <= (others=>'0'); cpu_mem_din_vld <= '0'; cpu_mem_dout_vld <= '0'; cpu_io_din_vld <= '0'; cpu_io_dout_vld <= '0'; elsif MEM_DIN_VLD='1' or MEM_DOUT_VLD='1' or IO_DIN_VLD='1' or IO_DOUT_VLD='1' then cpu_din <= DIN; cpu_mem_din_vld <= MEM_DIN_VLD; cpu_mem_dout_vld <= MEM_DOUT_VLD; cpu_io_din_vld <= IO_DIN_VLD; cpu_io_dout_vld <= IO_DOUT_VLD; end if; if RESET='1' or cpu_int_counter(5)='1' then cpu_int <= '0'; elsif INT='1' then cpu_int <= '1'; end if; reg_cpu_mem_din_rd <= cpu_mem_din_rd; if RESET='1' or MEM_DIN_VLD='1' then MEM_DIN_RD <= '0'; elsif cpu_mem_din_rd='1' and reg_cpu_mem_din_rd='0' then MEM_DIN_RD <= '1'; end if; reg_cpu_mem_dout_wr <= cpu_mem_dout_wr; if RESET='1' or MEM_DOUT_VLD='1' then MEM_DOUT_WR <= '0'; elsif cpu_mem_dout_wr='1' and reg_cpu_mem_dout_wr='0' then MEM_DOUT_WR <= '1'; end if; reg_cpu_io_din_rd <= cpu_io_din_rd; if RESET='1' or IO_DIN_VLD='1' then IO_DIN_RD <= '0'; elsif cpu_io_din_rd='1' and reg_cpu_io_din_rd='0' then IO_DIN_RD <= '1'; end if; reg_cpu_io_dout_wr <= cpu_io_dout_wr; if RESET='1' or IO_DOUT_VLD='1' then IO_DOUT_WR <= '0'; elsif cpu_io_dout_wr='1' and reg_cpu_io_dout_wr='0' then IO_DOUT_WR <= '1'; end if; end if; end process; din_reset <= not (cpu_mem_din_rd or cpu_mem_dout_wr or cpu_io_din_rd or cpu_io_dout_wr); process(CLK_CPU) begin if CLK_CPU'event and CLK_CPU='1' then if RESET='1' or cpu_int='0' then cpu_int_counter <= (others=>'0'); else cpu_int_counter <= cpu_int_counter + 1; end if; end if; end process; cpu_wrapper_inst : entity work.cpu_wrapper port map ( RESET => RESET, CLK => CLK_CPU, ADDR => cpu_addr, DIN => cpu_din, DOUT => cpu_dout, MEM_DIN_RD => cpu_mem_din_rd, MEM_DIN_VLD => cpu_mem_din_vld, MEM_DOUT_WR => cpu_mem_dout_wr, MEM_DOUT_VLD => cpu_mem_dout_vld, IO_DIN_RD => cpu_io_din_rd, IO_DIN_VLD => cpu_io_din_vld, IO_DOUT_WR => cpu_io_dout_wr, IO_DOUT_VLD => cpu_io_dout_vld, INT => cpu_int ); end cpu_wrapper_clk_inst;
zx-simi
trunk/fpga/cpu_wrapper_clk.vhd
VHDL
oos
5,026
library IEEE; use ieee.std_logic_1164.ALL; use ieee.std_logic_ARITH.ALL; use ieee.std_logic_UNSIGNED.ALL; entity KEMPSTON_JOYSTICK is port ( CLK : in std_logic; RESET : in std_logic; -- rozhrani pro komunikaci s procesorem ADDR : in std_logic_vector(15 downto 0); DATA_OUT : out std_logic_vector(7 downto 0); -- joystick pinout UP : in std_logic; DOWN : in std_logic; LEFT : in std_logic; RIGHT : in std_logic; BUTTON1 : in std_logic; BUTTON2 : in std_logic; BUTTON3 : in std_logic ); end entity; architecture kempston_joystick_arch of kempston_joystick is begin DATA_OUT(7 downto 0) <= (not BUTTON2) & '0' & (not BUTTON3) & (not BUTTON1) & (not UP) & (not DOWN) & (not LEFT) & (not RIGHT); end architecture;
zx-simi
trunk/fpga/kempston_joystick.vhd
VHDL
oos
828
library IEEE; use IEEE.STD_LOGIC_1164.ALL; use IEEE.STD_LOGIC_ARITH.ALL; use IEEE.STD_LOGIC_UNSIGNED.ALL; entity sdcard_spi is port ( RESET : in std_logic; CLK : in std_logic; -- Datova a adresova sbernice DATA_IN : in std_logic_vector(7 downto 0); DATA_OUT : out std_logic_vector(7 downto 0); WRITE_EN : in std_logic; READY : out std_logic; -- signalizace pripravenosti ke komunikaci -- Rozhrani SD karty SCLK : out std_logic; MOSI : out std_logic; MISO : in std_logic ); end sdcard_spi; architecture behav of sdcard_spi is -- SPI signaly signal spi_data : std_logic_vector(7 downto 0); -- datovy IO registr signal spi_data_in_reg : std_logic; -- zachytny registr na vstupu. Vzorkuje s nastupnou hranou hodin signal spi_rotate : std_logic; -- rotace datoveho registru signal spi_clk_en : std_logic; -- registr povolujici vystupni hodiny signal spi_last : std_logic; -- priznak ze se odesila posledni bit signal spi_data_wr : std_logic; -- povoleni zapisu do spi_data registru signal spi_output_en : std_logic; -- povolovaci signal vystupu type tspistate is (S_WAIT,S_WRITE,S_SPI0,S_SPI1,S_SPI2,S_SPI3,S_SPI4,S_SPI5,S_SPI6,S_SPI7); signal spi_present, spi_next : tspistate; begin -- povoleni hodin do pametove karty SCLK <= CLK when spi_clk_en='1' else '0'; -- na vystup do SD karty pripojim MSB MOSI <= spi_data(7) when spi_output_en='1' else '1'; -- pripojim na vystup datovy registr spi_data DATA_OUT <= spi_data; -- registr povolujici vystupni hodiny process(RESET,CLK) begin if RESET='1' then spi_clk_en <= '0'; elsif CLK'event and CLK='0' then if spi_last='1' then -- pokud odesilam posledni bit, zablokuji vystupni hodiny spi_clk_en <= '0'; spi_output_en <= '0'; elsif spi_data_wr='1' then -- pri zapisu do datoveho registru povolim hodiny, protoze se bude odesilat spi_clk_en <= '1'; spi_output_en <= '1'; end if; end if; end process; -- zachytny registr na vstupu. Vzorkuje pri nastupne hrane hodin. process(CLK) begin if CLK'event and CLK='1' then spi_data_in_reg <= MISO; end if; end process; -- SPI datovy registr process(CLK) begin if CLK'event and CLK='0' then if spi_rotate='1' then -- posunu vystupni data doleva a na 0. bit prilozim vstupni hodnotu spi_data <= spi_data(6 downto 0) & spi_data_in_reg; elsif spi_data_wr='1' then -- zapisu do registru data, ktera chci odeslat spi_data <= DATA_IN; end if; end if; end process; -- FSM, ktery zajistuje odeslani/prijem bajtu fsm_spi : process (spi_present,WRITE_EN) begin spi_rotate <= '0'; spi_last <= '0'; READY <= '0'; spi_data_wr <= '0'; case spi_present is when S_WAIT => READY <= '1'; -- signalizuji, ze SPI je pripraveno k odesilani spi_next <= S_WAIT; if WRITE_EN='1' then spi_next <= S_WRITE; end if; when S_WRITE => spi_next <= S_SPI0; READY <= '1'; spi_data_wr <= '1'; when S_SPI0 => spi_next <= S_SPI1; spi_rotate <= '1'; when S_SPI1 => spi_next <= S_SPI2; spi_rotate <= '1'; when S_SPI2 => spi_next <= S_SPI3; spi_rotate <= '1'; when S_SPI3 => spi_next <= S_SPI4; spi_rotate <= '1'; when S_SPI4 => spi_next <= S_SPI5; spi_rotate <= '1'; when S_SPI5 => spi_next <= S_SPI6; spi_rotate <= '1'; when S_SPI6 => spi_next <= S_SPI7; spi_rotate <= '1'; when S_SPI7 => spi_next <= S_WAIT; spi_rotate <= '1'; spi_last <= '1'; when others => spi_next <= S_WAIT; end case; end process; -- prepinani stavu u FSM process (RESET,CLK) begin if RESET='1' then spi_present <= S_WAIT; elsif CLK'event and CLK='1' then spi_present <= spi_next; end if; end process; end architecture;
zx-simi
trunk/fpga/old/sdcard_spi.vhd
VHDL
oos
5,000
-------------------------------------------------------------------------------- -- Company: -- Engineer: -- -- Create Date: 12:56:40 02/19/2012 -- Design Name: -- Module Name: D:/ZX Simi/fpga/flash_tb.vhd -- Project Name: Xilinx -- Target Device: -- Tool versions: -- Description: -- -- VHDL Test Bench Created by ISE for module: FLASH -- -- Dependencies: -- -- Revision: -- Revision 0.01 - File Created -- Additional Comments: -- -- Notes: -- This testbench has been automatically generated using types std_logic and -- std_logic_vector for the ports of the unit under test. Xilinx recommends -- that these types always be used for the top-level I/O of a design in order -- to guarantee that the testbench will bind correctly to the post-implementation -- simulation model. -------------------------------------------------------------------------------- LIBRARY ieee; USE ieee.std_logic_1164.ALL; -- Uncomment the following library declaration if using -- arithmetic functions with Signed or Unsigned values --USE ieee.numeric_std.ALL; ENTITY flash_tb IS END flash_tb; ARCHITECTURE behavior OF flash_tb IS -- Component Declaration for the Unit Under Test (UUT) COMPONENT FLASH PORT( CLK : IN std_logic; RESET : IN std_logic; DATA_OUT : OUT std_logic_vector(7 downto 0); ADDR : OUT std_logic_vector(22 downto 0); WR : OUT std_logic; ACK : IN std_logic ); END COMPONENT; --Inputs signal CLK : std_logic := '0'; signal RESET : std_logic := '0'; signal ACK : std_logic := '0'; --Outputs signal DATA_OUT : std_logic_vector(7 downto 0); signal ADDR : std_logic_vector(22 downto 0); signal WR : std_logic; -- Clock period definitions constant CLK_period : time := 10 ns; BEGIN -- Instantiate the Unit Under Test (UUT) uut: FLASH PORT MAP ( CLK => CLK, RESET => RESET, DATA_OUT => DATA_OUT, ADDR => ADDR, WR => WR, ACK => ACK ); -- Clock process definitions CLK_process :process begin CLK <= '0'; wait for CLK_period/2; CLK <= '1'; wait for CLK_period/2; end process; process(CLK) begin if CLK'event and CLK='1' then ACK <= WR; end if; end process; -- Stimulus process stim_proc: process begin RESET <= '1'; -- hold reset state for 100 ns. wait for 100 ns; RESET <= '0'; wait for CLK_period*100; -- insert stimulus here wait; end process; END;
zx-simi
trunk/fpga/old/flash_tb.vhd
VHDL
oos
2,693
#include <stdio.h> #include <stdlib.h> #include <graphics.h> #include <spectrum.h> #include "textgui.h" unsigned char imgTitleTriangle[8] = {0xFF, 0xFE, 0xFC, 0xF8, 0xF0, 0xE0, 0xC0, 0x80}; /* unsigned char imgError0[8] = {0x03, 0x0F, 0x1F, 0x37, 0x63, 0x71, 0xF8, 0xFC}; unsigned char imgError1[8] = {0xC0, 0xF0, 0xF8, 0xEC, 0xC6, 0x8E, 0x1F, 0x3F}; unsigned char imgError2[8] = {0xFC, 0xF8, 0x71, 0x63, 0x37, 0x1F, 0x0F, 0x03}; unsigned char imgError3[8] = {0x3F, 0x1F, 0x8E, 0xC6, 0xEC, 0xF8, 0xF0, 0xC0}; unsigned char imgWarning0[8] = {0x01, 0x01, 0x03, 0x03, 0x06, 0x06, 0x0E, 0x0E}; unsigned char imgWarning1[8] = {0x80, 0x80, 0xC0, 0xC0, 0x60, 0x60, 0x70, 0x70}; unsigned char imgWarning2[8] = {0x1E, 0x1E, 0x3E, 0x3F, 0x7F, 0x7E, 0xFE, 0xFF}; unsigned char imgWarning3[8] = {0x78, 0x78, 0x7C, 0xFC, 0xFE, 0x7E, 0x7F, 0xFF}; */ void drawChar(unsigned char x,unsigned char y,unsigned char *img) { unsigned char ch; for (ch=0;ch<8;ch++) drawCharLine(x,y,ch,img[ch]); } void setBackgroundColor(unsigned char inkColor) { printf("%c%c",17,'0'+inkColor); } void setTextColor(unsigned char inkColor) { printf("%c%c",16,'0'+inkColor); } void setBright(unsigned char bright) { printf("%c%c",19,1); } void gotoXY(unsigned char x,unsigned char y) { unsigned char xx,yy; if (x==0) xx=1; else xx=x; if (y==0) yy=1; else yy=y; xx <<=1; printf("%c%c%c",22,32+yy,32+xx); if (x==0) printf("%c",8); if (y==0) printf("%c",11); } void drawProgressBar(unsigned char x, unsigned char y, unsigned char width, unsigned long max, unsigned long current) { unsigned char i; drawb(x*8,y*8,width*8,8); for (i=0;i<width*current/max;i++) setScreenAttr(i+x,y,PAPER_GREEN | INK_BLACK) } void drawWindow(unsigned char x, unsigned char y, unsigned char width, unsigned char height, char *title) { unsigned char xx,yy; //vymazu data pod oknem. clga(x*8,y*8,width*8,height*8); gotoXY(x+1,y); puts_cons(title); //nakreslim horni cerny pruh for (xx=x;xx<width+x-6;xx++) setScreenAttr(xx,y,PAPER_BLACK | INK_WHITE | BRIGHT); //nastavim barevne atributy pro vykresleni barevneho prouzku vpravo nahore setScreenAttr(x+width-1,y,PAPER_BLACK | INK_BLACK | BRIGHT); setScreenAttr(x+width-2,y,PAPER_BLACK | INK_CYAN | BRIGHT); setScreenAttr(x+width-3,y,PAPER_CYAN | INK_GREEN | BRIGHT); setScreenAttr(x+width-4,y,PAPER_GREEN | INK_YELLOW | BRIGHT); setScreenAttr(x+width-5,y,PAPER_YELLOW | INK_RED | BRIGHT); setScreenAttr(x+width-6,y,PAPER_RED | INK_BLACK | BRIGHT); //ted ty pruhy udelam zkosene for (xx=x+width-6;xx<x+width-1;xx++) drawChar(xx,y,imgTitleTriangle); //nastavim pro cele okno atributy barev for (xx=x; xx<(x+width); xx++) for (yy=y+1;yy<y+height;yy++) setScreenAttr(xx,yy,PAPER_WHITE | INK_BLACK); //nakreslim ohraniceni okolo okna draw(x*8,(y+1)*8,x*8,(y+height)*8-1); //leva hrana draw((x+width)*8-1,(y+1)*8,(x+width)*8-1,(y+height)*8-1); //prava hrana draw(x*8,(y+height)*8-1,(x+width)*8-1,(y+height)*8-1); //spodni hrana }
zx-simi
trunk/zx_simi_os/textgui.c
C
oos
3,349
/* ========================================================================== */ /* */ /* fat32.h */ /* (c) 2011 Petr Simon */ /* */ /* Knihovna pro praci se souborovym systemem FAT32 */ /* */ /* ========================================================================== */ #ifndef _FAT32_H_ #define _FAT32_H_ #include "error.h" #include "filesystem.h" typedef struct { unsigned char sectorsCluster; //pocet sektoru na cluster unsigned int reservedSectors; //rezervované sektory od zacatku partition do 1. tabulky FAT unsigned char numberOfFAT; //pocet kopii FAT tabulky unsigned long numberOfTotalSectors; //pocet sektoru v partition unsigned int sizeOfFAT; //pocet sektoru v 1. FAT tabulce unsigned long rootCluster; //cislo prvniho clusteru rootu //vypocitane hodnoty unsigned long firstFATSector; //cislo sektoru, kde zacina prvni fat tabulka unsigned long firstDataSector; //cislo sektoru prvniho datoveho clusteru (root adresar) unsigned long maxCluster; //Maximalni platny cluster } tFAT32BootSector; extern errc FAT32readBootSector(tFAT32BootSector *bootSector, unsigned long firstSector); extern errc FAT32getNextAddrOfCluster(tFAT32BootSector *bootSector, unsigned long addr, unsigned long *next); extern errc FAT32readDir(tFAT32BootSector *bootSector, unsigned int pos, tFileSystemDir *dir); extern errc FAT32readFile(tFAT32BootSector *bootSector, unsigned long firstCluster, unsigned int sectorNumber, unsigned char *data); #endif
zx-simi
trunk/zx_simi_os/fat32.h
C
oos
1,968
#include "error.h" #include "filesystem.h" extern errc loadFileRom(tFileSystemDirEntry *dir); extern errc loadFileRunRom(tFileSystemDirEntry *dir);
zx-simi
trunk/zx_simi_os/file_rom.h
C
oos
156
#include "error.h" #include "filesystem.h" extern errc loadFileSna(tFileSystemDirEntry *dir);
zx-simi
trunk/zx_simi_os/file_sna.h
C
oos
99
/* ========================================================================== */ /* */ /* filesystem.h */ /* (c) 2011 Petr Simon */ /* */ /* Knihovna pro praci se souborovym systemem */ /* */ /* ========================================================================== */ #ifndef _FILESYSTEM_H_ #define _FILESYSTEM_H_ #include "error.h" typedef struct { unsigned char fileSystem; //typ souboroveho systemu unsigned long firstSector; //cislo prvniho sektoru unsigned long size; //pocet sektoru } tPartitionTableEntry; typedef struct { unsigned char name[9]; unsigned char ext[4]; unsigned char longName[30]; unsigned char useLongName; unsigned char attr; unsigned long size; unsigned long cluster; } tFileSystemDirEntry; //maximalni pocet ctenych zaznamu z adresare #define FS_DIR_SIZE 22 typedef struct { unsigned int size; unsigned long dirCluster; //cislo clusteru aktualniho adresare unsigned char moreFiles; //priznak, ktery bude rikat, ze ve slozce je jeste vic souboru, nez kolik jsem jich prave obdrzel tFileSystemDirEntry dirEntry[FS_DIR_SIZE]; } tFileSystemDir; extern errc fsStart(tFileSystemDir *dir); extern errc fsDir(unsigned int pos, tFileSystemDir *dir); extern errc fsReadFile(unsigned long fileCluster, unsigned long sectorNumber, unsigned char *data); #endif
zx-simi
trunk/zx_simi_os/filesystem.h
C
oos
1,785
#include <stdio.h> #include <spectrum.h> #include <string.h> #include <stdlib.h> #include <graphics.h> #include "keyboard.h" #include "error.h" #include "filesystem.h" #include "sdcard.h" #include "textgui.h" #include "dma.h" #include "file_z80.h" #include "file_sna.h" #include "file_tap.h" #include "file_tzx.h" #include "file_rom.h" unsigned char text1[] = "Loading a file. Please wait..."; unsigned char text2[] = "Loading"; unsigned char text3[] = "Loading a tape into memory. Please run \"Tape Loader\" in the 128K Basic or run LOAD command in the 48K Basic."; void printList(tFileSystemDir *dir, unsigned char from, unsigned char to) { unsigned char i; //vymazu seznam clga(8,8,30*8,22*8); setTextColor(INK_BLACK); setBackgroundColor(INK_WHITE); for (i=from;i<=to;i++) { gotoXY(1,i+1); if ((dir->dirEntry[i].attr & 0x10) != 0) putchar('/'); else putchar(' '); if (dir->dirEntry[i].useLongName==0) { printf("%s%c%s", dir->dirEntry[i].name,((dir->dirEntry[i].attr & 0x10) != 0 ? ' ' : '.'),dir->dirEntry[i].ext); } else { printf("%s",dir->dirEntry[i].longName); } } } void printListUnselect(unsigned char s, unsigned char left, unsigned char top, unsigned char width) { unsigned char x; for (x=left;x<left+width;x++) { setScreenAttr(x,s+top,INK_BLACK | PAPER_WHITE); } } void printListSelect(unsigned char s, unsigned char left, unsigned char top, unsigned char width) { unsigned char x; for (x=left;x<left+width;x++) { setScreenAttr(x,s+top,INK_BLACK | PAPER_CYAN | BRIGHT); } } /* unsigned char guiRomMenu() { unsigned char selected; unsigned int key; drawWindow(7,8,18,6,"ROM file"); gotoXY(8,10); puts_cons("Run"); gotoXY(8,11); puts_cons("Load into memory"); gotoXY(8,12); puts_cons("Cancel"); selected=0; do { printListSelect(selected,7,10,18); key = waitForKey(); waitForNoKey(); switch(key) { case KEY_UP: if (selected>0) { printListUnselect(selected,7,10,18); selected--; } break; case KEY_DOWN: if (selected<2) { //vymazu oznaceni radku printListUnselect(selected,7,10,18); selected++; } break; } } while (key != KEY_ENTER); return selected; } */ void guiMainWindow() { //nakreslim okno drawWindow(0,0,32,24,"ZX Simi OS v1.0"); // draw(14*8-1,8,14*8-1,8*24-1); } void printfBlock(unsigned char x, unsigned char y, unsigned char width, char *text) { unsigned char i,ii; while(1) { //jedu zprava a hledam prvni mezeru, kde to muzu rozriznout a skocit na novy radek for (i=width; text[i]!=' ' && text[i]!=0; i--) ; gotoXY(x,y); //ted ten text vytisknu az do mezery for (ii=0; ii<i; ii++) { if (text[ii]==0) return; putchar(text[ii]); } text+=i; if (text[0]==' ') text++; //zvysim cislo radku y++; }; } //**************************************************************************** int main() { tFileSystemDir dir; unsigned int key; unsigned int skip; errc err; unsigned char ch; unsigned char selected; unsigned long target; //rezim 32 znaku na radek set32columnMode(); //okraj zx_border(INK_BLUE); // zx_colour(PAPER_RED | INK_RED); //zobrazim hlavni okno guiMainWindow(); /////////////////////////////////////////// //inicializuji filesystem if ((err = fsStart(&dir)) != ERR_OK) return err; //nastavim se na zacatek adresare (nebudu preskakovat zadne soubory) skip = 0; //nastavim prvni soubor jako oznaceny selected=0; //nactu seznam souboru if ((err = fsDir(0,&dir)) != ERR_OK) return err; printList(&dir,0,dir.size-1); /* drawChar(20,10,imgWarning0); drawChar(21,10,imgWarning1); drawChar(20,11,imgWarning2); drawChar(21,11,imgWarning3); */ while(1) { printListSelect(selected,0,1,32); key = waitForKey(); waitForNoKey(); switch(key) { case KEY_UP: if (selected==0) { //jsem na konci seznamu //pokud jsem uplne na zacatku adresaru, tak se nikam posunovat nebudu a skoncim if (skip==0) break; //snizim pocet souboru, ktere mam pri nacitani preskocit skip -= FS_DIR_SIZE; if ((err = fsDir(skip,&dir)) != ERR_OK) return err; //vymazu oznaceni radku printListUnselect(selected,0,1,32); selected = FS_DIR_SIZE-1; printList(&dir,0,dir.size-1); } else { //jsem uprostred seznamu, takze prekreslim jen predchozi radek printListUnselect(selected,0,1,32); selected--; } break; case KEY_DOWN: if (selected==dir.size-1 && dir.moreFiles==0) {} else if (selected==FS_DIR_SIZE-1) { //jsem na konci seznamu //zvysim pocet souboru, ktere mam pri nacitani preskocit skip += FS_DIR_SIZE; if ((err = fsDir(skip,&dir)) != ERR_OK) return err; //vymazu oznaceni radku printListUnselect(selected,0,1,32); selected = 0; printList(&dir,0,dir.size-1); } else { printListUnselect(selected,0,1,32); selected++; } break; case KEY_ENTER: if ((dir.dirEntry[selected].attr & 0x10) == 0) { //aktualni polozka je soubor if (memcmp(dir.dirEntry[selected].ext,"ROM",3)==0) { drawWindow(7,8,18,6,text2); printfBlock(8, 10, 18, text1); loadFileRunRom(&(dir.dirEntry[selected])); /* switch(guiRomMenu()) { case 0: loadFileRunRom(&(dir.dirEntry[selected])); case 1: loadFileRom(&(dir.dirEntry[selected])); case 2: guiMainWindow(); printList(&dir,0,dir.size-1); break; }*/ } else if (memcmp(dir.dirEntry[selected].ext,"SNA",3)==0) { drawWindow(7,8,18,6,text2); printfBlock(8, 10, 18, text1); loadFileSna(&(dir.dirEntry[selected])); } else if (memcmp(dir.dirEntry[selected].ext,"Z80",3)==0) { drawWindow(7,8,18,6,text2); printfBlock(8, 10, 18, text1); loadFileZ80(&(dir.dirEntry[selected])); } else if (memcmp(dir.dirEntry[selected].ext,"TAP",3)==0) { drawWindow(4,6,24,9,text2); printfBlock(5, 8, 22, text3); tapLoadFile(&(dir.dirEntry[selected])); } else if (memcmp(dir.dirEntry[selected].ext,"TZX",3)==0) { drawWindow(4,6,24,9,text2); printfBlock(5, 8, 22, text3); tzxLoadFile(&(dir.dirEntry[selected])); } } else { //aktualni polozka je adresar //nastavim oznaceny odresar jako aktualni dir.dirCluster = dir.dirEntry[selected].cluster; //nactu seznam souboru if ((err = fsDir(0,&dir)) != ERR_OK) return err; //vymazu oznaceny radek printListUnselect(selected,0,1,32); selected = 0; skip = 0; printList(&dir,0,dir.size-1); } break; default: break; } } //////////////////////////////////////// /* while(1) { if ((err = guiMainWindow()) != ERR_OK) { setTextColor(INK_WHITE); zx_border(INK_RED); gotoXY(0,0); printf("ERROR %d\n",err); key = waitForKey(); waitForNoKey(); } } zx_border(INK_RED); while(1) { key = waitForKey(); waitForNoKey(); switch(key) { case 'q': //status karty data = inp(0x06F7); printf("s:%x ",data); break; default: gotoXY(3,3); printf("%d ",key); break; } } */ return 0; }
zx-simi
trunk/zx_simi_os/zxsimi.c
C
oos
9,563
#include <stdlib.h> #include "dma.h" void dmaSetDestAddr(unsigned long addr) { outp(DMA_DEST_ADDR0,(addr ) & 0xFF); //nejnizsi bajt adresy outp(DMA_DEST_ADDR1,(addr >> 8) & 0xFF); //prostredni bajt adresy outp(DMA_DEST_ADDR2,(addr >> 16) & 0xFF); //nejvyssi bajt adresy } void dmaSetSrcAddr(unsigned long addr) { outp(DMA_SRC_ADDR0,(addr ) & 0xFF); //nejnizsi bajt adresy outp(DMA_SRC_ADDR1,(addr >> 8) & 0xFF); //prostredni bajt adresy outp(DMA_SRC_ADDR2,(addr >> 16) & 0xFF); //nejvyssi bajt adresy } void dmaSetConfig(unsigned char conf) { outp(DMA_CONFIG,conf); } void dmaSendByte(unsigned char byte) { outp(DMA_SEND_BYTE,byte); } void dmaTransfer(unsigned int length) { outp(DMA_LENGTH0,(length ) & 0xFF); outp(DMA_LENGTH1,(length >> 8) & 0xFF); } unsigned long swAddr2hwAddr(unsigned long addr) { //0x0000 - 0x3FFF if (addr<0x4000) return addr+0x60000; //0x4000 - 0x7FFF else if (addr<0x8000) return addr+0x14000-0x4000; //0x8000 - 0xBFFF else if (addr<0xC000) return addr; //0xC000 - 0xFFFF else return addr-0xC000; }
zx-simi
trunk/zx_simi_os/dma.c
C
oos
1,173
#define TASK_RAM_BASE_ADDR 0x40000 #define TASK_ROM0 (0x20000) #define TASK_RAM0 (TASK_RAM_BASE_ADDR) #define TASK_RAM2 (TASK_RAM_BASE_ADDR + 0x8000) #define TASK_RAM5 (TASK_RAM_BASE_ADDR + 0x14000) extern unsigned char taskSetA(unsigned char *pole, unsigned char byte); extern unsigned char taskSetB(unsigned char *pole, unsigned char byte); extern unsigned char taskSetC(unsigned char *pole, unsigned char byte); extern unsigned char taskSetD(unsigned char *pole, unsigned char byte); extern unsigned char taskSetE(unsigned char *pole, unsigned char byte); extern unsigned char taskSetH(unsigned char *pole, unsigned char byte); extern unsigned char taskSetL(unsigned char *pole, unsigned char byte); extern unsigned char taskSetBORDER(unsigned char *pole, unsigned char byte); extern unsigned char taskSetI(unsigned char *pole, unsigned char byte); extern unsigned char taskSetR(unsigned char *pole, unsigned char byte); extern unsigned char taskSetEXX(unsigned char *pole); extern unsigned char taskSetEXAF(unsigned char *pole); extern unsigned char taskSetAF(unsigned char *pole, unsigned char low, unsigned char high); extern unsigned char taskSetIX(unsigned char *pole, unsigned char low, unsigned char high); extern unsigned char taskSetIY(unsigned char *pole, unsigned char low, unsigned char high); extern unsigned char taskSetSP(unsigned char *pole, unsigned char low, unsigned char high); extern unsigned char taskSetPC(unsigned char *pole, unsigned char low, unsigned char high); extern unsigned char taskSetRETN(unsigned char *pole); extern unsigned char taskSetIM(unsigned char *pole, unsigned char byte); /** * Nastavi IFF1 a IFF2 na hodnotu 0 nebo 1 * byte == 0 DI * byte != 0 EI */ extern unsigned char taskSetIFF(unsigned char *pole, unsigned char byte); extern void taskOut7FFD(unsigned char byte); extern void taskRun(unsigned char *ind, unsigned char *pole);
zx-simi
trunk/zx_simi_os/task.h
C
oos
1,972
/* ========================================================================== */ /* */ /* keyboard.h */ /* (c) 2011 Petr Simon */ /* */ /* Obsluha klavesnice */ /* */ /* ========================================================================== */ #ifndef _KEYBOARD_H_ #define _KEYBOARD_H_ #define KEY_UP 11 #define KEY_DOWN 10 #define KEY_ENTER 13 /** * Ceka na stisk klavesy * * @return ASCII kod stisknute klavesy */ unsigned int waitForKey(); /** * Ceka na uvolneni klaves */ void waitForNoKey(); #endif
zx-simi
trunk/zx_simi_os/keyboard.h
C
oos
953
#include "error.h" #include "filesystem.h" extern errc tzxLoadFile(tFileSystemDirEntry *dir);
zx-simi
trunk/zx_simi_os/file_tzx.h
C
oos
99
/* ========================================================================== */ /* */ /* sdcard.h */ /* (c) 2001 Petr Simon */ /* */ /* Obsluha SD/MMC pametove karty */ /* */ /* ========================================================================== */ #ifndef _SDCARD_H_ #define _SDCARD_H_ #include "error.h" //Bazova adresa SD karty #define SD_ADDR 0xF7 //Adresy registru #define SD_REG0 SD_ADDR+0x0000 #define SD_REG1 SD_ADDR+0x0100 #define SD_REG2 SD_ADDR+0x0200 #define SD_REG3 SD_ADDR+0x0300 #define SD_REG4 SD_ADDR+0x0400 #define SD_REG5 SD_ADDR+0x0500 /** * Precte datovy blok o velikosti 512 bajtu ze zadane adresy * * /param sector 32bitova adresa sektoru * /param *array ukazatel na pole. Je ocekavano pole o velikosti 512 bajtu */ extern errc sdReadSector(unsigned long sector,unsigned char*); #endif
zx-simi
trunk/zx_simi_os/sdcard.h
C
oos
1,257
#include <stdlib.h> #include "textgui.h" #include "error.h" #include "filesystem.h" #include "dma.h" #include "task.h" #include "file_rom.h" errc loadFileRom(tFileSystemDirEntry *dir) { unsigned long size, pocet,zdroj,targetAddr; unsigned char data[512]; unsigned int memInd, sector; errc err; targetAddr = TASK_ROM0; sector=0; for (size = 0; size<(dir->size); size += 512) { //prectu odpovidajici sektor v souboru if ((err = fsReadFile(dir->cluster, sector, data)) != ERR_OK) return err; sector++; //ulozim cilovou adresu, kam budu ukladat soubor dmaSetDestAddr(targetAddr); targetAddr += 512; //konfiguracni registr dmaSetConfig(DMA_INC_DST | DMA_INC_SRC); //zdrojova adresa, z ktere se bude cist dmaSetSrcAddr(swAddr2hwAddr(((unsigned long)data))); //spocitam, kolik jeste musim prenest bajtu pocet = dir->size - size; if (pocet>512) pocet = 512; //spustim prenos dmaTransfer(pocet); } return ERR_OK; } errc loadFileRunRom(tFileSystemDirEntry *dir) { unsigned char pole[3]; unsigned char *ind; errc err; if ((err = loadFileRom(dir)) != ERR_OK) return err; ind = pole; ind += taskSetPC(ind,0,0); ind--; taskRun(ind,pole); return ERR_OK; }
zx-simi
trunk/zx_simi_os/file_rom.c
C
oos
1,445
#include <stdlib.h> //bazova adresa DMA radice #define TASK_BASE_ADDR 0x1F //registr pro ulozeni cilove adresy (kam se bude ukladat) #define TASK_ADDR0 (0x0000 + TASK_BASE_ADDR) #define TASK_ADDR1 (0x0100 + TASK_BASE_ADDR) #define TASK_7FFD (0x0200 + TASK_BASE_ADDR) #define TASK_CMD (0x0400 + TASK_BASE_ADDR) unsigned char taskSetA(unsigned char *pole, unsigned char byte) { //LD r,n pole[0] = 0x3E; pole[1] = byte; return 2; } unsigned char taskSetB(unsigned char *pole, unsigned char byte) { //LD r,n pole[0] = 0x06; pole[1] = byte; return 2; } unsigned char taskSetC(unsigned char *pole, unsigned char byte) { //LD r,n pole[0] = 0x0E; pole[1] = byte; return 2; } unsigned char taskSetD(unsigned char *pole, unsigned char byte) { //LD r,n pole[0] = 0x16; pole[1] = byte; return 2; } unsigned char taskSetE(unsigned char *pole, unsigned char byte) { //LD r,n pole[0] = 0x1E; pole[1] = byte; return 2; } unsigned char taskSetH(unsigned char *pole, unsigned char byte) { //LD r,n pole[0] = 0x26; pole[1] = byte; return 2; } unsigned char taskSetL(unsigned char *pole, unsigned char byte) { //LD r,n pole[0] = 0x2E; pole[1] = byte; return 2; } /** * likviduje registr A */ unsigned char taskSetBORDER(unsigned char *pole, unsigned char byte) { //LD A,n pole[0] = 0x3E; pole[1] = byte; //OUT (n),A pole[2] = 0xD3; pole[3] = 0xFE; return 4; } /** * likviduje registr A */ unsigned char taskSetI(unsigned char *pole, unsigned char byte) { //LD A,n pole[0] = 0x3E; pole[1] = byte; //LD I,A pole[2] = 0xED; pole[3] = 0x47; return 4; } /** * likviduje registr A */ unsigned char taskSetR(unsigned char *pole, unsigned char byte) { //LD A,n pole[0] = 0x3E; pole[1] = byte; //LD R,A pole[2] = 0xED; pole[3] = 0x4F; return 4; } unsigned char taskSetEXX(unsigned char *pole) { //EXX pole[0] = 0xD9; return 1; } unsigned char taskSetEXAF(unsigned char *pole) { //EX AF,AF' pole[0] = 0x08; return 1; } /** * Likviduje registr IX */ unsigned char taskSetAF(unsigned char *pole, unsigned char low, unsigned char high) { //LD IX,nn pole[0] = 0xDD; pole[1] = 0x21; pole[2] = low; pole[3] = high; //PUSH IX pole[4] = 0xDD; pole[5] = 0xE5; //POP AF pole[6] = 0xF1; return 7; } unsigned char taskSetIX(unsigned char *pole, unsigned char low, unsigned char high) { //LD IX,nn pole[0] = 0xDD; pole[1] = 0x21; pole[2] = low; pole[3] = high; return 4; } unsigned char taskSetIY(unsigned char *pole, unsigned char low, unsigned char high) { //LD IY,nn pole[0] = 0xFD; pole[1] = 0x21; pole[2] = low; pole[3] = high; return 4; } unsigned char taskSetSP(unsigned char *pole, unsigned char low, unsigned char high) { //LD SP,nn pole[0] = 0x31; pole[1] = low; pole[2] = high; return 3; } /** * Tato instrukce musi byt jako posledni. */ unsigned char taskSetPC(unsigned char *pole, unsigned char low, unsigned char high) { //JP nn pole[0] = 0xC3; pole[1] = low; pole[2] = high; return 3; } unsigned char taskSetRETN(unsigned char *pole) { pole[0] = 0xED; pole[1] = 0x45; return 2; } unsigned char taskSetIM(unsigned char *pole, unsigned char byte) { pole[0] = 0xED; if (byte==1) pole[1] = 0x56; //IM 1 else if (byte==2) pole[1] = 0x5E; //IM 2 else pole[1] = 0x46; //IM 0 return 2; } unsigned char taskSetIFF(unsigned char *pole, unsigned char byte) { if (byte == 0) pole[0] = 0xF3; //DI else pole[0] = 0xFB; //EI return 1; } int (*taskFunc)(); void taskOut7FFD(unsigned char byte) { outp(TASK_7FFD, byte); } void taskRun(unsigned char *ind, unsigned char *pole) { outp(TASK_ADDR0, ((unsigned int)ind ) & 0xFF); //nejnizsi bajt adresy outp(TASK_ADDR1, ((unsigned int)ind >> 8) & 0xFF); outp(TASK_CMD, 0x01); //dam prikaz pro monitorovani adresy z CPU. Pokud bude CPU adresovat stejnou adresu, ktera je ulozena v SIMI_ADDR, pak provedu prepnuti pameti taskFunc = pole; taskFunc(); }
zx-simi
trunk/zx_simi_os/task.c
C
oos
4,462
#include "error.h" #include "filesystem.h" extern errc loadFileZ80(tFileSystemDirEntry *dir);
zx-simi
trunk/zx_simi_os/file_z80.h
C
oos
99
//bazova adresa DMA radice #define DMA_BASE_ADDR 0xF3 //registr pro ulozeni cilove adresy (kam se bude ukladat) #define DMA_DEST_ADDR0 (0x0000 + DMA_BASE_ADDR) #define DMA_DEST_ADDR1 (0x0100 + DMA_BASE_ADDR) #define DMA_DEST_ADDR2 (0x0200 + DMA_BASE_ADDR) //registr pro odeslani jednoho bajtu #define DMA_SEND_BYTE (0x0300 + DMA_BASE_ADDR) //registr pro ulozeni zdrojove adresy (odkud se bude nacitat) #define DMA_SRC_ADDR0 (0x0400 + DMA_BASE_ADDR) #define DMA_SRC_ADDR1 (0x0500 + DMA_BASE_ADDR) #define DMA_SRC_ADDR2 (0x0600 + DMA_BASE_ADDR) //registr pro ulozeni delky prenaseneho bloku #define DMA_LENGTH0 (0x0700 + DMA_BASE_ADDR) #define DMA_LENGTH1 (0x0800 + DMA_BASE_ADDR) //konfiguracni registr #define DMA_CONFIG (0x0900 + DMA_BASE_ADDR) //priznak inkrementace cilove adresy #define DMA_INC_DST 0x01 //cilova adresa je IO #define DMA_IORQ_DST 0x02 //priznak inkrementace zdrojove adresy #define DMA_INC_SRC 0x10 //zdrojova adresa je IO #define DMA_IORQ_SRC 0x20 /** * Nastavi cilovou fyzickou adresu * * @param addr Fyzicka adresa */ extern void dmaSetDestAddr(unsigned long addr); /** * Nastavi zdrojovou fyzickou adresu * * @param addr Fyzicka adresa */ extern void dmaSetSrcAddr(unsigned long addr); /** * Nastavi konfiguraci DMA radice * * @param conf Konfigurace */ extern void dmaSetConfig(unsigned char conf); /** * Prenese blok dat o zadane delce * * @param length Delka prenasenych dat */ extern void dmaTransfer(unsigned int length); /** * Precte jeden bajt */ #define dmaReadByte() inp(DMA_BASE_ADDR) /** * Ulozi jeden bajt */ extern void dmaSendByte(unsigned char byte); extern unsigned long swAddr2hwAddr(unsigned long addr);
zx-simi
trunk/zx_simi_os/dma.h
C
oos
1,783
/* ========================================================================== */ /* */ /* error.h */ /* (c) 2011 Petr Simon */ /* */ /* Zpracovani chyb */ /* */ /* ========================================================================== */ #ifndef _ERROR_H_ #define _ERROR_H_ typedef enum { ERR_OK = 0, //bez chyby //SD karta ERR_SDREADSECTOR, //problem pri cteni sektoru ERR_SD_START_TOKEN, //neobdrzel jsem startovni datovy token po prikazu CMD17/18/24 ERR_MBR, //chyba MBR zaznamu ERR_UNKNOWN_FS, //neznamy souborovy system //FAT32 chyby ERR_FAT32_BOOT_SECTOR, //chybny Boot Sector ERR_BAD_CLUSTER, //vadny cluster ERR_CLUSTER_NOT_EXISTS, //cluster neexistuje //TZX soubor ERR_TZX_HEADER, //chybna hlavicka TZX souboru ERR_TZX_VERSION, //nepodporovana verze ERR_TZX_UNKNOWN_DATA_BLOCK //neznamy data block } errc; #endif
zx-simi
trunk/zx_simi_os/error.h
C
oos
1,447
/* ========================================================================== */ /* */ /* fat32.c */ /* (c) 2011 Petr Simon */ /* */ /* Knihovna pro praci se souborovym systemem FAT32 */ /* */ /* ========================================================================== */ #include <stdio.h> #include <string.h> #include "fat32.h" #include "error.h" #include "sdcard.h" #include "filesystem.h" /** * Precte Boot Sektor */ errc FAT32readBootSector(tFAT32BootSector *bootSector, unsigned long firstSector) { unsigned char pole[512]; errc err; //prectu Boot Sector if ((err = sdReadSector(firstSector,pole)) != ERR_OK) return err; //zkontroluji, zda se opravdu jedna o boot sector if (pole[0x1FE]!=0x55 || pole[0x1FF]!=0xAA) return ERR_FAT32_BOOT_SECTOR; //naplnim datove struktutury bootSector->sectorsCluster=pole[0x0D]; bootSector->reservedSectors=(pole[0x0E + 1] << 8) | (pole[0x0E]); bootSector->numberOfFAT=pole[0x10]; bootSector->numberOfTotalSectors=((unsigned long)pole[0x20 + 3]<<24) | ((unsigned long)pole[0x20 + 2]<<16) | (pole[0x20 + 1]<<8) | pole[0x20]; bootSector->sizeOfFAT=((unsigned long)pole[0x24 + 3]<<24) | ((unsigned long)pole[0x24 + 2]<<16) | (pole[0x24 + 1]<<8) | pole[0x24]; bootSector->rootCluster=((unsigned long)pole[0x2C + 3]<<24) | ((unsigned long)pole[0x2C + 2]<<16) | (pole[0x2C + 1]<<8) | pole[0x2C]; //vypocitam si adresu sektoru zacatku prvni FAT tabulky bootSector->firstFATSector=firstSector + bootSector->reservedSectors; //vypocitam si adresu sektoru prvniho datoveho clusteru bootSector->firstDataSector=firstSector + bootSector->reservedSectors + bootSector->numberOfFAT * bootSector->sizeOfFAT + (bootSector->rootCluster - 2) * bootSector->sectorsCluster; //vypocitam si hodnotu maximalniho platneho clusteru bootSector->maxCluster=(bootSector->numberOfTotalSectors - bootSector->numberOfFAT * bootSector->sizeOfFAT - bootSector->reservedSectors) / bootSector->sectorsCluster; /* printf("sectors/cluster: %x\n",bootSector->sectorsCluster); printf("Reserved sectors: %x\n",bootSector->reservedSectors); printf("number of FATs: %x\n",bootSector->numberOfFAT); printf("number of total sectors: %lx\n",bootSector->numberOfTotalSectors); printf("pocet sektoru v 1. FAT tabulce: %x\n",bootSector->sizeOfFAT); printf("root cluster: %lx\n",bootSector->rootCluster); printf("first FAT sector: %lx\n",bootSector->firstFATSector); printf("first data sector: %lx\n",bootSector->firstDataSector); printf("max cluster: %lx\n",bootSector->maxCluster); */ return ERR_OK; } /** * Precte z FAT tabulky adresu nasledujiciho clusteru pro zadany cluster * * \param addr cislo clusteru, pro ktery chceme urcit naslednika * \param *next reference na promennou, do ktere se ulozi vysledek */ errc FAT32getNextAddrOfCluster(tFAT32BootSector *bootSector, unsigned long addr, unsigned long *next) { unsigned char pole[512]; errc err; unsigned long sektor; unsigned long tmp; //vypocitam si adresu cteneho sektoru. K zacatku FAT tabulky prictu hodnotu: //512 ... velikost sektoru //4 ... velikost jednoho zaznamu ve FAT je 4 bajty //podelim adresu touto hodnotou, cimz dostanu odpovidajici sektor sektor = bootSector->firstFATSector + addr/(512/4); //prectu si spravny sektor if ((err = sdReadSector(sektor,pole)) != ERR_OK) return err; //sirka jednoho zaznamu je 4 bajty. Modulo 512 zajistuje rozsah jednoho sektoru tmp = addr * 4 % 512; //z precteneho sektoru prectu odpovidajici zaznam na adrese *next=(pole[tmp + 3]<<24) | (pole[tmp + 2]<<16) | (pole[tmp + 1]<<8) | pole[tmp]; return ERR_OK; } errc FAT32readFile(tFAT32BootSector *bootSector, unsigned long firstCluster, unsigned int sectorNumber, unsigned char *data) { errc err; unsigned long first_sector; unsigned long cluster; cluster = firstCluster; //pokud chci cist sektor, ktery je uz v jinem clusteru, tak se musim do tohoto clusteru nejdrive dostat while (sectorNumber >= bootSector->sectorsCluster) { //snizim cislo sektoru o hodnotu poctu sektoru na cluster sectorNumber -= bootSector->sectorsCluster; //prectu z FAT tabulky cislo nasledujiciho clusteru if ((err = FAT32getNextAddrOfCluster(bootSector,cluster, &cluster)) != ERR_OK) return err; } //zjistim si adresu prvniho sektoru v danem clusteru first_sector = bootSector->firstDataSector + (cluster-2)*bootSector->sectorsCluster; if ((err = sdReadSector(first_sector+sectorNumber,data)) != ERR_OK) return err; return ERR_OK; } /** * Precte obsah adresare * * \param bootSector ukazatel na strukturu s informacemi o FS * \param pos poradove cislo souboru/adresare, od ktereho chci zacit vypisovat zaznamy (tzn. pocet zaznamu, ktere mam vynechat) * \param dir vraceny vysledek */ errc FAT32readDir(tFAT32BootSector *bootSector, unsigned int pos, tFileSystemDir *dir) { unsigned char pole[512]; unsigned int i,i32; errc err; unsigned long first_sector; unsigned long sector; unsigned char longn,longn13; unsigned long cluster = dir->dirCluster; //inicializace datove struktury for (i=0;i<FS_DIR_SIZE;i++) { dir->dirEntry[i].useLongName = 0; //nepouzivat dlouhy nazev //inicializuji retezec (zapisu ukoncujici 0 na dulezita mista, kde jsou potreba) dir->dirEntry[i].longName[13] = 0; dir->dirEntry[i].longName[26] = 0; dir->dirEntry[i].longName[29] = 0; } //vynuluji aktualni pocet zaznamu v adresari dir->size = 0; //projdu vsechny clustery daneho adresare do { //overim, zda sektor neni vadny if (cluster==0x0FFFFFF7) return ERR_BAD_CLUSTER; //overim, zda sektor existuje if (cluster>bootSector->maxCluster && cluster<=0x0FFFFFF6) return ERR_CLUSTER_NOT_EXISTS; //zjistim si adresu prvniho sektoru v danem clusteru first_sector = bootSector->firstDataSector + (cluster-2)*bootSector->sectorsCluster; //projdu vsechny sektory v danem clusteru for (sector=first_sector; sector < first_sector + bootSector->sectorsCluster; sector++) { //prectu sector if ((err = sdReadSector(sector,pole)) != ERR_OK) return err; //pocatecni inicializace. Slozka nema vic souboru, nez kolik jsem jich nacetl dir->moreFiles = 0; //projdu vsechny zaznamy v danem sektoru i=0; do { i32 = i*32; //pole[i*32]=0x00 ... konec zaznamu //pole[i*32]=0xE5 ... smazany soubor //pole[i*32+0x0B]=0x0F ... priznak dlouheho nazvu souboru. if (pole[i32]!=0x00 && pole[i32]!=0xE5) { if (pos>0) { //pokud jsem jeste nevynechal dostatek zaznamu, tak dekrementuji tuto promennou a nebudu tento zaznam ukladat if (pole[i32+0x0B]!=0x0F) pos--; //dekrementuji ale pouze pokud prave pracuji s kratkym nazvem souboru. Ten je povinny pro kazdy soubor } else { //pokud jsem jiz precetl dostatecny pocet zaznamu, tak koncim if (FS_DIR_SIZE==dir->size) { dir->moreFiles = 1; //poznacim si, ze slozka ma jeste vic souboru, nez kolik jsem jich nacetl return ERR_OK; } //dale zvlast zpracovavam dlouhy a kratky nazev souboru if (pole[i32+0x0B]==0x0F) { //dlouhy nazev souboru //nastavim priznak, ze soubor ma ulozen dlouhy nazev dir->dirEntry[dir->size].useLongName = 1; //zjistim poradove cislo casti nazvu longn = (pole[i32] & 0xF) - 1; longn13 = longn*13; //ulozim si nazev souboru do pameti if (longn<3) { //posledni tri znaky nazvu souboru dir->dirEntry[dir->size].longName[0+longn13] = pole[i32+0x01]; dir->dirEntry[dir->size].longName[1+longn13] = pole[i32+0x03]; dir->dirEntry[dir->size].longName[2+longn13] = pole[i32+0x05]; } if (longn<2) { //prvnich 2*13 znaku z nazvu souboru dir->dirEntry[dir->size].longName[3+longn13] = pole[i32+0x07]; dir->dirEntry[dir->size].longName[4+longn13] = pole[i32+0x09]; dir->dirEntry[dir->size].longName[5+longn13] = pole[i32+0x0E]; dir->dirEntry[dir->size].longName[6+longn13] = pole[i32+0x10]; dir->dirEntry[dir->size].longName[7+longn13] = pole[i32+0x12]; dir->dirEntry[dir->size].longName[8+longn13] = pole[i32+0x14]; dir->dirEntry[dir->size].longName[9+longn13] = pole[i32+0x16]; dir->dirEntry[dir->size].longName[10+longn13] = pole[i32+0x18]; dir->dirEntry[dir->size].longName[11+longn13] = pole[i32+0x1C]; dir->dirEntry[dir->size].longName[12+longn13] = pole[i32+0x1E]; } } else { //kratky nazev souboru memcpy(dir->dirEntry[dir->size].name,pole+i32,8); //prekopiruju si ho do pameti longn = 8; do { //jedu zprava a odmazavam zbytecne mezery a davam misto nich 0 dir->dirEntry[dir->size].name[longn]=0; longn--; } while (dir->dirEntry[dir->size].name[longn] == ' '); //jakmile narazim na prvni znak, ktery neni mezera, tak koncim //pripona souboru memcpy(dir->dirEntry[dir->size].ext,pole+8+i32,3); dir->dirEntry[dir->size].ext[3]=0; //atributy dir->dirEntry[dir->size].attr = pole[0x0B+i32]; //adresa souboru/adresare, kam ukazuje tento zaznam dir->dirEntry[dir->size].cluster = ((unsigned long)pole[0x14+1+i32]<<24) | ((unsigned long)pole[0x14+0+i32]<<16) | (pole[0x1A+1+i32]<<8) | (pole[0x1A+0+i32]); //velikost souboru/adresare. U adresare je vzdy 0 dir->dirEntry[dir->size].size = ((unsigned long)pole[0x1C+3+i32]<<24) | ((unsigned long)pole[0x1C+2+i32]<<16) | (pole[0x1C+1+i32]<<8) | (pole[0x1C+0+i32]); dir->size++; } } } i++; } while (i<16 && pole[i32]!=0); } //prectu z FAT tabulky cislo nasledujiciho clusteru if ((err = FAT32getNextAddrOfCluster(bootSector,cluster, &cluster)) != ERR_OK) return err; //pokud je adresa nasledujiciho clusteru >= 2 a mensi nez maximalni povolena hodnota clusteru, tak opakuji } while(cluster >= 0x02 && cluster <= bootSector->maxCluster); return ERR_OK; }
zx-simi
trunk/zx_simi_os/fat32.c
C
oos
12,178
/* ========================================================================== */ /* */ /* sdcard.c */ /* (c) 2001 Petr Simon */ /* */ /* Obsluha SD/MMC pametove karty */ /* */ /* ========================================================================== */ #include <stdio.h> #include <spectrum.h> #include <stdlib.h> #include "sdcard.h" #include "error.h" #include "dma.h" void sdReadCmd(unsigned long addr) { outp(SD_REG0,0x11); //CMD17 outp(SD_REG1,(addr >> 24) & 0xFF); //adresa MSB outp(SD_REG2,(addr >> 16) & 0xFF); //adresa outp(SD_REG3,(addr >> 8) & 0xFF); //adresa outp(SD_REG4,addr & 0xFF); //adresa LSB outp(SD_REG5,0x01); //potvrdim provedeni prikazu // printf("CMD17 addr=%lx\n",addr); } unsigned char sdReadByte() { unsigned char data; // outp(SD_REG5,0x02); //reknu sdkarte, aby precetla jeden bajt data = inp(0x07F7); return data; } /** * Precte datovy blok o velikosti 512 bajtu ze zadane adresy * * /param addr 32bitova adresa * /param *array ukazatel na pole. Je ocekavano pole o velikosti 512 bajtu */ errc sdReadSector(unsigned long sector,unsigned char *array) { unsigned int CRC,i; unsigned char data; //odeslu karte prikaz CMD17 (cteni) //je potreba prevest adresu sektoru na adresu v bajtech. Sektor ma 512 bajtu, takze lze vypocitat pomoci posunu doleva o 9 bitu sdReadCmd(sector<<9); //cekam na prvni data token i = 0; do { data = sdReadByte(); i++; } while (data!=0xFE && i<16); //pokud jsem po 9 pokusech neobdrzel startovaci token, koncim s chybou if (i==16) return ERR_SD_START_TOKEN; //konfiguracni registr dmaSetConfig(DMA_INC_DST | DMA_IORQ_SRC); dmaSetDestAddr(swAddr2hwAddr((unsigned long)array)); dmaSetSrcAddr(0x07F7); dmaTransfer(512); /* //prectu blok dat o delce 512 bajtu for (i=0;i<512;i++) { array[i] = sdReadByte(); } */ //prectu CRC CRC = sdReadByte() << 8 | sdReadByte(); // printf("CRC:%x\n",CRC); return ERR_OK; }
zx-simi
trunk/zx_simi_os/sdcard.c
C
oos
2,650
/* ========================================================================== */ /* */ /* filesystem.c */ /* (c) 2011 Petr Simon */ /* */ /* Knihovna pro praci se souborovym systemem */ /* */ /* ========================================================================== */ #include <stdio.h> #include "filesystem.h" #include "sdcard.h" #include "fat32.h" static tPartitionTableEntry pTable; static tFAT32BootSector bootSector; /** * Precte MBR a nastavi datove struktury s partition tabulkou. * Inicializuje datove struktury odpovidajiciho souboroveho systemu */ errc fsStart(tFileSystemDir *dir) { unsigned char pole[512]; errc err; //prectu prvni sektro obsahujici MBR if ((err = sdReadSector(0,pole)) != ERR_OK) return err; if (pole[0x1FE]!=0x55 || pole[0x1FF]!=0xAA) return ERR_MBR; pTable.fileSystem=pole[0x01BE + 0x04]; pTable.firstSector=((unsigned long)pole[0x01BE + 0x08 + 3]<<24) | ((unsigned long)pole[0x01BE + 0x08 + 2]<<16) | (pole[0x01BE + 0x08 + 1]<<8) | pole[0x01BE + 0x08]; pTable.size=((unsigned long)pole[0x01BE + 0x0C + 3]<<24) | ((unsigned long)pole[0x01BE + 0x0C + 2]<<16) | (pole[0x01BE + 0x0C + 1]<<8) | pole[0x01BE + 0x0C]; // printf("file system: %x\n",pTable.fileSystem); // printf("first sector: %lx\n",pTable.firstSector); // printf("first size: %lx\n",pTable.size); //inicializuji datove struktury soouboroveho systemu switch(pTable.fileSystem) { case 0x0B: //FAT32 if ((err = FAT32readBootSector(&bootSector, pTable.firstSector)) != ERR_OK) return err; dir->dirCluster = bootSector.rootCluster; break; default: //Neznamy souborovy system return ERR_UNKNOWN_FS; } return ERR_OK; } /** * Precte obsah adresare * * \param pos pocet zaznamu, ktere se maji preskocit */ errc fsDir(unsigned int pos, tFileSystemDir *dir) { errc err; switch(pTable.fileSystem) { case 0x0B: //FAT32 //pokud je cislo clusteru rovno nule, pak nastavim root jako aktualni adresar if (dir->dirCluster == 0) dir->dirCluster = bootSector.rootCluster; if ((err = FAT32readDir(&bootSector, pos,dir)) != ERR_OK) return err; break; default: //Neznamy souborovy system return ERR_UNKNOWN_FS; } return ERR_OK; } errc fsReadFile(unsigned long fileCluster, unsigned long sectorNumber, unsigned char *data) { errc err; err = FAT32readFile(&bootSector, fileCluster, sectorNumber, data); return err; }
zx-simi
trunk/zx_simi_os/filesystem.c
C
oos
3,028
del *.ROM *.o *.BIN *.TAP zcc -vn -Wall -c textgui.c zcc -vn -Wall -c dma.c zcc -vn -Wall -c sdcard.c zcc -vn -Wall -c fat32.c zcc -vn -Wall -c filesystem.c zcc -vn -Wall -c task.c zcc -vn -Wall -c keyboard.c zcc -vn -Wall -c file_z80.c zcc -vn -Wall -c file_sna.c zcc -vn -Wall -c file_rom.c zcc -vn -Wall -c file_tap.c zcc -vn -Wall -c file_tzx.c zcc +zx -create-app -vn -Wall -lndos dma.o sdcard.o fat32.o filesystem.o task.o keyboard.o textgui.o file_z80.o file_sna.o file_rom.o file_tap.o file_tzx.o zxsimi.c
zx-simi
trunk/zx_simi_os/make.bat
Batchfile
oos
532
#ifndef _TEXTGUI_H_ #define _TEXTGUI_H_ /* extern unsigned char imgError0[8]; extern unsigned char imgError1[8]; extern unsigned char imgError2[8]; extern unsigned char imgError3[8]; extern unsigned char imgWarning0[8]; extern unsigned char imgWarning1[8]; extern unsigned char imgWarning2[8]; extern unsigned char imgWarning3[8]; */ extern unsigned char imgTitleTriangle[8]; #define set32columnMode() puts_cons("\1\32"); extern void setBackgroundColor(unsigned char inkColor); extern void setTextColor(unsigned char inkColor); extern void setBright(unsigned char bright); extern void gotoXY(unsigned char x,unsigned char y); #define setScreenAttr(x,y,attr) *zx_cyx2aaddr(y,x) = attr; #define drawCharLine(x,y,line,data) *(zx_cyx2saddr(y,x)+line*0x100) = data; extern void drawChar(unsigned char x,unsigned char y,unsigned char *img); extern void drawWindow(unsigned char x, unsigned char y, unsigned char width, unsigned char height,char *title); extern void drawProgressBar(unsigned char x, unsigned char y, unsigned char width, unsigned long max, unsigned long current); #endif
zx-simi
trunk/zx_simi_os/textgui.h
C
oos
1,129
#include <stdlib.h> #include <stdio.h> #include "error.h" #include "filesystem.h" #include "dma.h" #include "task.h" #include "file_sna.h" #define SNA_HW48K 0 #define SNA_HW128K 1 errc loadFileSna(tFileSystemDirEntry *dir) { unsigned long addr, sector, targetAddr; unsigned char data[512]; unsigned char pole[256]; unsigned int memInd; unsigned char *ind; errc err; unsigned char hw; unsigned char bank,bank_n; //prectu prvni sektor if ((err = fsReadFile(dir->cluster, 0, data)) != ERR_OK) return err; sector = 1; if (dir->size > 49179) hw = SNA_HW128K; else hw = SNA_HW48K; ind = pole; //interrupt control vector ind += taskSetI(ind,data[0]); //BC' DE' HL' ind += taskSetL(ind,data[1]); ind += taskSetH(ind,data[2]); ind += taskSetE(ind,data[3]); ind += taskSetD(ind,data[4]); ind += taskSetC(ind,data[5]); ind += taskSetB(ind,data[6]); ind += taskSetEXX(ind); //stinovy registr AF' ind += taskSetAF(ind,data[7],data[8]); ind += taskSetEXAF(ind); //BC DE HL IY IX ind += taskSetL(ind,data[9]); ind += taskSetH(ind,data[10]); ind += taskSetE(ind,data[11]); ind += taskSetD(ind,data[12]); ind += taskSetC(ind,data[13]); ind += taskSetB(ind,data[14]); ind += taskSetIY(ind,data[15],data[16]); //BORDER ind += taskSetBORDER(ind,data[26]); //IFF ind += taskSetIFF(ind,data[19] & 4); //zajima me IFF2, ktery je na 2. bitu. Vzhledem k tomu, ze hned provedu RETN, IFF1 se stejne prepise //R ind += taskSetR(ind,data[20]); //AF ind += taskSetAF(ind,data[21],data[22]); //IX ind += taskSetIX(ind,data[17],data[18]); //SP ind += taskSetSP(ind,data[23],data[24]); //IM ind += taskSetIM(ind,data[25]); if (hw==SNA_HW48K) { //pokud je to 48K obraz, tak pridam instrukci RETN a vyberu ROM1 ind += taskSetRETN(ind); //budu vyuzivat ROM1 taskOut7FFD(0x10); } //prenesu snapshot do pameti. //je to trochu komplikovanejsi, protoze na zacatku snapsotu byla hlavicka, takze je vse posunute o 27 bajtu. for (addr=27; addr<49179; addr+=512) { //vyberu spravnou banku if (addr==27) { targetAddr = TASK_RAM5; } else if (addr==27+0x4000) { targetAddr = TASK_RAM2; } else if (addr==27+0x8000) { targetAddr = TASK_RAM0; } //prenesu data z nacteneho sektoru od adresy 27. Je to posunute, protoze na zacatku sna souboru byla hlavicka o velikosti 27 bajtu. dmaSetSrcAddr(swAddr2hwAddr(((unsigned long)data)+27)); dmaSetDestAddr(targetAddr); dmaSetConfig(DMA_INC_DST | DMA_INC_SRC); dmaTransfer(512-27); targetAddr += (512-27); //nactu novy sektor if ((err = fsReadFile(dir->cluster, sector, data)) != ERR_OK) return err; sector++; //ted prenesu prvnich 27 bajtu sektoru, cimz jsem v teto iteraci cyklu penesl celkem 512 bajtu. dmaSetSrcAddr(swAddr2hwAddr(((unsigned long)data))); dmaSetDestAddr(targetAddr); dmaSetConfig(DMA_INC_DST | DMA_INC_SRC); dmaTransfer(27); targetAddr += 27; } //pokud je to 128K snapshot, tak musim zpracovat zbytek obrazu if (hw==SNA_HW128K) { //nastaveni PC ind += taskSetPC(ind, data[27], data[28]); //pripravim registr 7FFD (adresuje horni cast pameti) taskOut7FFD(data[29]); bank_n = (data[29] & 0x7); //pokud byla ve sna souboru na nejvyssi adrese ulozena jina banka nez 0, tak musim tuto banku presunout na spravne misto, aby se banka 0 uvolnila pro nasledne ukladani dat if (bank_n>0) { dmaSetSrcAddr(TASK_RAM0); dmaSetDestAddr(TASK_RAM_BASE_ADDR+((unsigned long)0x4000)*bank_n); dmaSetConfig(DMA_INC_DST | DMA_INC_SRC); dmaTransfer(0x4000); } bank = 0; //prenesu snapshot do pameti. //je to trochu komplikovanejsi, protoze na zacatku snapsotu byla hlavicka, takze je vse posunute o 27 bajtu. for (addr=31+0xC000; addr<(dir->size); addr+=512) { if ((addr & 0x3FFF)==31) { if (bank==2) bank++; if (bank==5) bank++; if (bank==bank_n) bank++; if (bank==2) bank++; if (bank==5) bank++; targetAddr = TASK_RAM_BASE_ADDR+((unsigned long)0x4000)*bank; bank++; } //prenesu data z nacteneho sektoru od adresy 27. Je to posunute, protoze na zacatku sna souboru byla hlavicka o velikosti 27 bajtu. dmaSetSrcAddr(swAddr2hwAddr(((unsigned long)data)+31)); dmaSetDestAddr(targetAddr); dmaSetConfig(DMA_INC_DST | DMA_INC_SRC); dmaTransfer(512-31); targetAddr += (512-31); //nactu novy sektor if ((err = fsReadFile(dir->cluster, sector, data)) != ERR_OK) return err; sector++; //ted prenesu prvnich 27 bajtu sektoru, cimz jsem v teto iteraci cyklu penesl celkem 512 bajtu. dmaSetSrcAddr(swAddr2hwAddr(((unsigned long)data))); dmaSetDestAddr(targetAddr); dmaSetConfig(DMA_INC_DST | DMA_INC_SRC); dmaTransfer(31); targetAddr += 31; } } //jeste zkratim o jeden bajt pole. ind--; //spustim program taskRun(ind,pole); return ERR_OK; }
zx-simi
trunk/zx_simi_os/file_sna.c
C
oos
5,816
#include "error.h" #include "filesystem.h" extern errc tapLoadFile(tFileSystemDirEntry *dir);
zx-simi
trunk/zx_simi_os/file_tap.h
C
oos
99
#include <stdlib.h> #include <stdio.h> #include <string.h> #include "textgui.h" #include "error.h" #include "filesystem.h" #include "dma.h" #include "task.h" #include "file_tzx.h" //stavy konecneho automatu, ktery pracovava TZX soubor typedef enum { TZX_HEADER = 0, TZX_DATA_BLOCK, TZX_ID_10, TZX_ID_11, TZX_ID_12, TZX_ID_13, TZX_ID_14, TZX_ID_15, TZX_ID_18, TZX_ID_19, TZX_ID_20, TZX_ID_21, TZX_ID_2A, TZX_ID_2B, TZX_ID_30, TZX_ID_31, TZX_ID_32, TZX_ID_33, TZX_ID_35, TZX_SKIP, TZX_TAPE_DATA } tzxState; errc tzxLoadFile(tFileSystemDirEntry *dir) { unsigned long addr, targetAddr, block_length; unsigned char pole[3]; unsigned char *ind; unsigned char data[512]; unsigned char state,offset; unsigned int min; unsigned int memInd, sector; errc err; targetAddr = 0x80000; sector=0; state = TZX_HEADER; addr = 0; //prenesu snapshot do pameti. (dir->size) while (addr < (dir->size)) { //vypocitam si index do pole s daty. Pole je velke 512 bajtu memInd = addr & 0x1FF; //prectu odpovidajici sektor v souboru if (memInd == 0) { if ((err = fsReadFile(dir->cluster, sector, data)) != ERR_OK) return err; sector++; dmaSetDestAddr(targetAddr); dmaSetConfig(DMA_INC_DST | DMA_INC_SRC); } switch(state) { case TZX_HEADER: //HEADER if (memcmp(data,"ZXTape!",7)!=0) return ERR_TZX_HEADER; //signature if (data[7]!=26) return ERR_TZX_HEADER; //end of file marker if (data[8]!=1) return ERR_TZX_VERSION; //end of file marker addr += 10; state = TZX_DATA_BLOCK; break; case TZX_DATA_BLOCK://DATA BLOCK switch (data[memInd]) { case 0x10: state = TZX_ID_10; break; case 0x11: state = TZX_ID_11; break; case 0x12: state = TZX_ID_12; break; case 0x13: state = TZX_ID_13; break; case 0x14: state = TZX_ID_14; break; case 0x15: state = TZX_ID_15; break; case 0x18: state = TZX_ID_18; break; case 0x19: state = TZX_ID_19; break; case 0x20: state = TZX_ID_20; break; case 0x21: state = TZX_ID_21; break; case 0x22: state = TZX_DATA_BLOCK; break; //nema zadne telo case 0x2A: state = TZX_ID_2A; break; case 0x2B: state = TZX_ID_2B; break; case 0x30: state = TZX_ID_30; break; case 0x31: state = TZX_ID_31; break; case 0x32: state = TZX_ID_32; break; case 0x33: state = TZX_ID_33; break; case 0x35: state = TZX_ID_35; break; case 0x5A: block_length=9; state = TZX_SKIP; break; // skip block default: return ERR_TZX_UNKNOWN_DATA_BLOCK; } addr++; offset = 0; break; case TZX_ID_10: //Standard speed data block if (offset==2) block_length = data[memInd]; if (offset==3) { block_length |= (((unsigned long)data[memInd]) << 8); state = TZX_TAPE_DATA; } offset++; addr++; break; case TZX_ID_11: //Turbo speed data block if (offset==15) block_length = data[memInd]; if (offset==16) block_length |= (((unsigned long)data[memInd]) << 8); if (offset==17) { block_length |= (((unsigned long)data[memInd]) << 16); state = TZX_TAPE_DATA; } offset++; addr++; break; case TZX_ID_12: //Pure tone if (offset==3) state = TZX_DATA_BLOCK; offset++; addr++; break; case TZX_ID_13: //Pulse sequence block_length = data[memInd]*2; addr++; if (block_length != 0) state = TZX_SKIP; else state = TZX_DATA_BLOCK; break; case TZX_ID_14: //Pure data block if (offset==7) block_length = data[memInd]; if (offset==8) block_length |= (((unsigned long)data[memInd]) << 8); if (offset==9) { block_length |= (((unsigned long)data[memInd]) << 16); state = TZX_TAPE_DATA; } offset++; addr++; break; case TZX_ID_15: //Direct recording block if (offset==5) block_length = data[memInd]; if (offset==6) block_length |= (((unsigned long)data[memInd]) << 8); if (offset==7) { block_length |= (((unsigned long)data[memInd]) << 16); state = TZX_SKIP; } offset++; addr++; break; case TZX_ID_18: //CSW Recording case TZX_ID_19: //Generalized Data Block case TZX_ID_2A: //stop tape at 48k case TZX_ID_2B: //set signal if (offset==0) block_length = data[memInd]; if (offset==1) block_length |= (((unsigned long)data[memInd]) << 8); if (offset==2) block_length |= (((unsigned long)data[memInd]) << 16); if (offset==3) { block_length |= (((unsigned long)data[memInd]) << 24); if (block_length != 0) state = TZX_SKIP; else state = TZX_DATA_BLOCK; } offset++; addr++; break; case TZX_ID_20: //Pause (silence) or 'Stop the Tape' command if (offset==1) state = TZX_DATA_BLOCK; offset++; addr++; break; case TZX_ID_21: //Group start case TZX_ID_30: //Text description block_length = data[memInd]; if (block_length!=0) state = TZX_SKIP; else state = TZX_DATA_BLOCK; addr++; break; case TZX_ID_31: //message if (offset==1) { block_length = data[memInd]; if (block_length!=0) state = TZX_SKIP; else state = TZX_DATA_BLOCK; } addr++; offset++; break; case TZX_ID_32: //archive info if (offset==0) block_length = data[memInd]; if (offset==1) { block_length |= (((unsigned long)data[memInd]) << 8); if (block_length != 0) state = TZX_SKIP; else state = TZX_DATA_BLOCK; } offset++; addr++; break; case TZX_ID_33: //hardware info block_length = data[memInd]*3; if (block_length != 0) state = TZX_SKIP; else state = TZX_DATA_BLOCK; addr++; break; case TZX_ID_35: //Custom info block if (offset==16) block_length = data[memInd]; if (offset==17) block_length |= (((unsigned long)data[memInd]) << 8); if (offset==18) block_length |= (((unsigned long)data[memInd]) << 16); if (offset==19) { block_length |= (((unsigned long)data[memInd]) << 24); if (block_length != 0) state = TZX_SKIP; else state = TZX_DATA_BLOCK; } offset++; addr++; break; case TZX_TAPE_DATA: //TAPE DATA min = 512 - memInd; min = (block_length > min ? min : block_length); //nastavim DMA radic dmaSetSrcAddr(swAddr2hwAddr(((unsigned long)data)+memInd)); dmaTransfer(min); targetAddr += min; block_length -= min; addr += min; if (block_length==0) state = TZX_DATA_BLOCK; break; case TZX_SKIP: //preskoci zadany pocet bajtu addr++; block_length--; if (block_length==0) state = TZX_DATA_BLOCK; break; } } //pripravim ukazatel DMA na zacatek tape dat. ROMka pak muze cist kazetu pekne od zacatku dmaSetSrcAddr(0x80000); dmaSetConfig(DMA_INC_SRC); //spustim aplikaci ind = pole; ind += taskSetPC(ind,0,0); ind--; taskRun(ind,pole); return ERR_OK; }
zx-simi
trunk/zx_simi_os/file_tzx.c
C
oos
9,460
#include <stdlib.h> #include <stdio.h> #include "filesystem.h" #include "dma.h" #include "task.h" #include "file_z80.h" #include "error.h" #define Z80_HW48K 0 #define Z80_HW128K 1 void z80storeByte(unsigned long *targetAddr, unsigned int *dest, unsigned char data) { //vyberu spravnou banku if (*dest == 0) { *targetAddr = TASK_RAM5; dmaSetDestAddr(*targetAddr); } else if (*dest == 0x4000) { *targetAddr = TASK_RAM2; dmaSetDestAddr(*targetAddr); } else if (*dest == 0x8000) { *targetAddr = TASK_RAM0; dmaSetDestAddr(*targetAddr); } dmaSendByte(data); *dest += 1; *targetAddr += 1; } errc z80dataBlock(tFileSystemDirEntry *dir, unsigned long *sector, unsigned char *data, unsigned int *memIndParam, unsigned char hw) { errc err; unsigned long targetAddr; unsigned char state,lastByte,compression,b0,b1,b2; unsigned int length,maxLength; unsigned int memInd; //pro vetsi rychlost si ulozim hodnotu na adrese *memIndParam do lokalni promenne memInd = *memIndParam; //prvni bajt hlavicky b0 = data[memInd]; memInd = (memInd + 1) & 0x1FF; if (memInd == 0) { if ((err = fsReadFile(dir->cluster, *sector, data)) != ERR_OK) return err; *sector = *sector + 1; } //druhy bajt hlavicky b1 = data[memInd]; memInd = (memInd + 1) & 0x1FF; if (memInd == 0) { if ((err = fsReadFile(dir->cluster, *sector, data)) != ERR_OK) return err; *sector = *sector + 1; } //treti bajt hlavicky b2 = data[memInd]; memInd = (memInd + 1) & 0x1FF; //zjistim delku bloku a soucasne i informaci, zda je blok komprimovan if (b0==0xFF && b1==0xFF) { //neni komprese maxLength = 0x4000; compression=0; } else { //komprese maxLength = (b0 | b1<<8); compression=1; } if (hw==Z80_HW48K) { if (b2==4) { targetAddr = TASK_RAM2; } else if (b2==5) { targetAddr = TASK_RAM0; } else if (b2==8) { targetAddr = TASK_RAM5; } } else { targetAddr = TASK_RAM_BASE_ADDR + (((unsigned long)(b2-3)) << 14); } dmaSetDestAddr(targetAddr); dmaSetConfig(DMA_INC_DST); state = 0; for (length=0; length<maxLength; length++) { //prectu odpovidajici sektor v souboru if (memInd == 0) { if ((err = fsReadFile(dir->cluster, *sector, data)) != ERR_OK) return err; *sector = *sector + 1; dmaSetDestAddr(targetAddr); dmaSetConfig(DMA_INC_DST); dmaSetDestAddr(targetAddr); } switch(state) { case 0: if (compression!=0 && data[memInd]==0xED) { state = 1; } else { dmaSendByte(data[memInd]); targetAddr += 1; } break; case 1: if (data[memInd]==0xED) { state = 2; } else { dmaSendByte(0xED); dmaSendByte(data[memInd]); targetAddr += 2; state = 0; } break; case 2: lastByte = data[memInd]; state = 3; break; case 3: dmaSetSrcAddr(swAddr2hwAddr(((unsigned int)data)+memInd)); dmaTransfer(lastByte); targetAddr += lastByte; state = 0; break; } memInd = (memInd + 1) & 0x1FF; } *memIndParam = memInd; return ERR_OK; } errc z80version1(tFileSystemDirEntry *dir, unsigned long sector, unsigned char *data) { errc err; unsigned long addr, targetAddr; unsigned int memInd, dest; unsigned char state,lastByte,i,compression; if ((data[12] & 0x20) == 0) compression = 0; else compression=1; dest = 0; state = 0; //prenesu snapshot do pameti. (dir->size) for (addr=30; addr<(dir->size); addr++) { //vypocitam si index do pole s daty. Pole je velke 512 bajtu memInd = addr & 0x1FF; //prectu odpovidajici sektor v souboru if (memInd == 0) { if ((err = fsReadFile(dir->cluster, sector, data)) != ERR_OK) return err; sector++; dmaSetDestAddr(targetAddr); dmaSetConfig(DMA_INC_DST); } switch(state) { case 0: if (compression!=0 && data[memInd]==0xED) { state = 1; } else if (compression!=0 && data[memInd]==0x00) { state = 4; } else { z80storeByte(&targetAddr,&dest,data[memInd]); } break; case 1: if (data[memInd]==0xED) { state = 2; } else if (data[memInd]==0x00) { z80storeByte(&targetAddr,&dest,0xED); state = 4; } else { z80storeByte(&targetAddr,&dest,0xED); z80storeByte(&targetAddr,&dest,data[memInd]); state = 0; } break; case 2: lastByte = data[memInd]; state = 3; break; case 3: for (i=0;i<lastByte;i++) z80storeByte(&targetAddr,&dest,data[memInd]); state = 0; break; case 4: if (data[memInd]==0xED) { state = 5; } else { z80storeByte(&targetAddr,&dest,0x00); z80storeByte(&targetAddr,&dest,data[memInd]); state = 0; } break; case 5: if (data[memInd]==0xED) { state = 6; } else { z80storeByte(&targetAddr,&dest,0x00); z80storeByte(&targetAddr,&dest,0xED); z80storeByte(&targetAddr,&dest,data[memInd]); state = 0; } break; case 6: if (data[memInd]==0x00) { state = 7; } else { z80storeByte(&targetAddr,&dest,0x00); lastByte = data[memInd]; state = 3; } break; } } return ERR_OK; } errc loadFileZ80(tFileSystemDirEntry *dir) { unsigned long addr; unsigned long sector; unsigned char data[512]; unsigned char pole[256]; unsigned int memInd; unsigned char *ind; unsigned char *uk; unsigned char hw,pages,i; errc err; //prectu prvni sektor if ((err = fsReadFile(dir->cluster, 0, data)) != ERR_OK) return err; sector = 1; ind = pole; //interrupt control vector ind += taskSetI(ind,data[10]); //BC' DE' HL' ind += taskSetL(ind,data[19]); ind += taskSetH(ind,data[20]); ind += taskSetE(ind,data[17]); ind += taskSetD(ind,data[18]); ind += taskSetC(ind,data[15]); ind += taskSetB(ind,data[16]); ind += taskSetEXX(ind); //stinovy registr AF' ind += taskSetAF(ind,data[22],data[21]); ind += taskSetEXAF(ind); //BC DE HL IY ind += taskSetL(ind,data[4]); ind += taskSetH(ind,data[5]); ind += taskSetE(ind,data[13]); ind += taskSetD(ind,data[14]); ind += taskSetC(ind,data[2]); ind += taskSetB(ind,data[3]); ind += taskSetIY(ind,data[23],data[24]); //BORDER if (data[12]==255) data[12] = 1; //kvuli kompatibilite. Pokud je to 255, pak se to ma interpretovat jako 1 ind += taskSetBORDER(ind,(data[12]>>1) & 0x7); //IFF ind += taskSetIFF(ind,data[27]); //R ind += taskSetR(ind,data[11]); //AF ind += taskSetAF(ind,data[1],data[0]); //IX ind += taskSetIX(ind,data[25],data[26]); //SP ind += taskSetSP(ind,data[8],data[9]); //IM ind += taskSetIM(ind,data[29]&3); if (data[6]!=0 || data[7]!=0) { //PC != 0, takze se jedna o obraz verze 1 //PC ind += taskSetPC(ind, data[6],data[7]); taskOut7FFD(0x10); //pro ZX 48K vyeru ROM1 //nactu verzi 1 if ((err = z80version1(dir,sector,data)) != ERR_OK) return err; } else if (data[30]==0x17 && data[31]==0) { //Z80 verze 2 //PC ind += taskSetPC(ind, data[0x20],data[0x21]); //pripravim si hodnotu, ktera se pak posle na port 7FFD (strankovani pameti) if (hw==Z80_HW128K) taskOut7FFD(data[35]); else taskOut7FFD(0x10); //pro ZX 48K vyeru ROM1 //datovy blok zacina na adrese 55 memInd = 55; switch (data[34]) { case 0: case 1: hw = Z80_HW48K; pages = 3; break; case 3: case 4: hw = Z80_HW128K; pages = 8; break; } for (i=0;i<pages;i++) z80dataBlock(dir, &sector, data, &memInd, hw); } else if ((data[30]==0x36 || data[30]==0x37) && data[31]==0) { //Z80 verze 3 //PC ind += taskSetPC(ind, data[0x20],data[0x21]); //zjistim zacatek datoveho bloku if (data[30]==0x36) memInd = 86; else memInd = 87; switch (data[34]) { case 0: case 1: case 3: hw = Z80_HW48K; pages = 3; break; case 4: case 5: case 6: hw = Z80_HW128K; pages = 8; break; } //pripravim si hodnotu, ktera se pak posle na port 7FFD (strankovani pameti) if (hw==Z80_HW128K) taskOut7FFD(data[35]); else taskOut7FFD(0x10); //pro ZX 48K vyeru ROM1 for (i=0;i<pages;i++) z80dataBlock(dir, &sector, data, &memInd, hw); } ind--; taskRun(ind,pole); return ERR_OK; }
zx-simi
trunk/zx_simi_os/file_z80.c
C
oos
10,919
#include <stdlib.h> #include <stdio.h> #include "textgui.h" #include "error.h" #include "filesystem.h" #include "dma.h" #include "task.h" #include "file_tap.h" errc tapLoadFile(tFileSystemDirEntry *dir) { unsigned long addr, targetAddr; unsigned char pole[3]; unsigned char *ind; unsigned char data[512]; unsigned char state; unsigned int block_length, min; unsigned int memInd, sector; errc err; targetAddr = 0x80000; sector=0; state = 0; addr = 0; //prenesu snapshot do pameti. (dir->size) while (addr < (dir->size)) { //vypocitam si index do pole s daty. Pole je velke 512 bajtu memInd = addr & 0x1FF; //prectu odpovidajici sektor v souboru if (memInd == 0) { if ((err = fsReadFile(dir->cluster, sector, data)) != ERR_OK) return err; sector++; dmaSetDestAddr(targetAddr); dmaSetConfig(DMA_INC_DST | DMA_INC_SRC); } switch(state) { //DATA BLOCK case 0: //DATA LENGTH lsb block_length = data[memInd]; addr++; state = 1; break; case 1: //DATA LENGTH msb block_length |= (((unsigned int)data[memInd]) << 8); addr++; state = 2; break; //TAPE DATA case 2: //TAPE DATA min = 512 - memInd; min = (block_length > min ? min : block_length); //nastavim DMA radic dmaSetSrcAddr(swAddr2hwAddr(((unsigned long)data)+memInd)); dmaTransfer(min); targetAddr += min; block_length -= min; addr += min; if (block_length==0) state = 0; break; } } //pripravim ukazatel DMA na zacatek tape dat. ROMka pak muze cist kazetu pekne od zacatku dmaSetSrcAddr(0x80000); dmaSetConfig(DMA_INC_SRC); //spustim aplikaci ind = pole; ind += taskSetPC(ind,0,0); ind--; taskRun(ind,pole); return ERR_OK; }
zx-simi
trunk/zx_simi_os/file_tap.c
C
oos
2,234
/* ========================================================================== */ /* */ /* keyboard.c */ /* (c) 2011 Petr Simon */ /* */ /* Obsluha klavesnice */ /* */ /* ========================================================================== */ #include <input.h> #include "keyboard.h" #include <stdio.h> #include <spectrum.h> #include <stdlib.h> unsigned char keyState = 0; /** * Ceka na stisk klavesy * * @return ASCII kod stisknute klavesy */ unsigned int waitForKey() { unsigned int key; //ceka, dokud neni stisknuta klavesa do { key = in_Inkey(); } while (key==0); return key; } /** * Ceka na uvolneni klaves */ void waitForNoKey() { unsigned int key,a; a=0; //ceka, dokud uzivatel neuvolni vsechny stisknute klavesy do { key = in_Inkey(); a++; } while (key!=0 && a<(keyState==0 ? 400 : 80)); if (key!=0) keyState=1; else keyState=0; }
zx-simi
trunk/zx_simi_os/keyboard.c
C
oos
1,390
del *.bin *.exe rem ------------------------------------------------- rem preklad TAP exporteru gcc tap_extractor.c -o tap_extractor.exe rem ------------------------------------------------- rem Exrakce souboru TAP s operacnim systemem ZX Simi tap_extractor.exe ..\zx_simi_os\a.tap tmp.bin rem ------------------------------------------------- rem Vytvoreni celeho ROM souboru pro FLASH pamet copy /B ..\rom\ZXS128_LOAD.ROM +tmp.bin flash.bin rem ------------------------------------------------- rem Vysledny soubor flash.bin naprogramujte do FLASH pameti
zx-simi
trunk/flash/run.bat
Batchfile
oos
583
#include <stdio.h> int main(int argc, char * argv[]) { FILE * pFile, *oFile; int c,length,i; if (argc != 3) return 1; pFile = fopen (argv[1], "rb"); if (pFile == NULL) perror ("Error opening file"); oFile = fopen (argv[2], "wb"); if (oFile == NULL) perror ("Error opening output file"); else { do { c = getc (pFile); length = c; c = getc(pFile); length += (c<<8); if (c==EOF) break; printf("length: %d\n",length); for (i=0;i<length;i++) { c = getc (pFile); fputc(c,oFile); } } while (c != EOF); fclose (pFile); fclose (oFile); } return 0; }
zx-simi
trunk/flash/tap_extractor.c
C
oos
732
<?php /** * Loads the WordPress environment and template. * * @package WordPress */ if ( !isset($wp_did_header) ) { $wp_did_header = true; require_once( dirname(__FILE__) . '/wp-load.php' ); wp(); require_once( ABSPATH . WPINC . '/template-loader.php' ); }
zyblog
trunk/zyblog/wp-blog-header.php
PHP
asf20
271
<?php /** * Handle Trackbacks and Pingbacks sent to WordPress * * @package WordPress */ if (empty($wp)) { require_once('./wp-load.php'); wp( array( 'tb' => '1' ) ); } /** * trackback_response() - Respond with error or success XML message * * @param int|bool $error Whether there was an error * @param string $error_message Error message if an error occurred */ function trackback_response($error = 0, $error_message = '') { header('Content-Type: text/xml; charset=' . get_option('blog_charset') ); if ($error) { echo '<?xml version="1.0" encoding="utf-8"?'.">\n"; echo "<response>\n"; echo "<error>1</error>\n"; echo "<message>$error_message</message>\n"; echo "</response>"; die(); } else { echo '<?xml version="1.0" encoding="utf-8"?'.">\n"; echo "<response>\n"; echo "<error>0</error>\n"; echo "</response>"; } } // trackback is done by a POST $request_array = 'HTTP_POST_VARS'; if ( !isset($_GET['tb_id']) || !$_GET['tb_id'] ) { $tb_id = explode('/', $_SERVER['REQUEST_URI']); $tb_id = intval( $tb_id[ count($tb_id) - 1 ] ); } $tb_url = isset($_POST['url']) ? $_POST['url'] : ''; $charset = isset($_POST['charset']) ? $_POST['charset'] : ''; // These three are stripslashed here so that they can be properly escaped after mb_convert_encoding() $title = isset($_POST['title']) ? stripslashes($_POST['title']) : ''; $excerpt = isset($_POST['excerpt']) ? stripslashes($_POST['excerpt']) : ''; $blog_name = isset($_POST['blog_name']) ? stripslashes($_POST['blog_name']) : ''; if ($charset) $charset = str_replace( array(',', ' '), '', strtoupper( trim($charset) ) ); else $charset = 'ASCII, UTF-8, ISO-8859-1, JIS, EUC-JP, SJIS'; // No valid uses for UTF-7 if ( false !== strpos($charset, 'UTF-7') ) die; if ( function_exists('mb_convert_encoding') ) { // For international trackbacks $title = mb_convert_encoding($title, get_option('blog_charset'), $charset); $excerpt = mb_convert_encoding($excerpt, get_option('blog_charset'), $charset); $blog_name = mb_convert_encoding($blog_name, get_option('blog_charset'), $charset); } // Now that mb_convert_encoding() has been given a swing, we need to escape these three $title = $wpdb->escape($title); $excerpt = $wpdb->escape($excerpt); $blog_name = $wpdb->escape($blog_name); if ( is_single() || is_page() ) $tb_id = $posts[0]->ID; if ( !isset($tb_id) || !intval( $tb_id ) ) trackback_response(1, 'I really need an ID for this to work.'); if (empty($title) && empty($tb_url) && empty($blog_name)) { // If it doesn't look like a trackback at all... wp_redirect(get_permalink($tb_id)); exit; } if ( !empty($tb_url) && !empty($title) ) { header('Content-Type: text/xml; charset=' . get_option('blog_charset') ); if ( !pings_open($tb_id) ) trackback_response(1, 'Sorry, trackbacks are closed for this item.'); $title = wp_html_excerpt( $title, 250 ).'...'; $excerpt = wp_html_excerpt( $excerpt, 252 ).'...'; $comment_post_ID = (int) $tb_id; $comment_author = $blog_name; $comment_author_email = ''; $comment_author_url = $tb_url; $comment_content = "<strong>$title</strong>\n\n$excerpt"; $comment_type = 'trackback'; $dupe = $wpdb->get_results( $wpdb->prepare("SELECT * FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_author_url = %s", $comment_post_ID, $comment_author_url) ); if ( $dupe ) trackback_response(1, 'We already have a ping from that URL for this post.'); $commentdata = compact('comment_post_ID', 'comment_author', 'comment_author_email', 'comment_author_url', 'comment_content', 'comment_type'); wp_new_comment($commentdata); do_action('trackback_post', $wpdb->insert_id); trackback_response(0); }
zyblog
trunk/zyblog/wp-trackback.php
PHP
asf20
3,700
<?php /** * BackPress Scripts enqueue. * * These classes were refactored from the WordPress WP_Scripts and WordPress * script enqueue API. * * @package BackPress * @since r74 */ /** * BackPress enqueued dependiences class. * * @package BackPress * @uses _WP_Dependency * @since r74 */ class WP_Dependencies { var $registered = array(); var $queue = array(); var $to_do = array(); var $done = array(); var $args = array(); var $groups = array(); var $group = 0; /** * Do the dependencies * * Process the items passed to it or the queue. Processes all dependencies. * * @param mixed $handles (optional) items to be processed. (void) processes queue, (string) process that item, (array of strings) process those items * @return array Items that have been processed */ function do_items( $handles = false, $group = false ) { // Print the queue if nothing is passed. If a string is passed, print that script. If an array is passed, print those scripts. $handles = false === $handles ? $this->queue : (array) $handles; $this->all_deps( $handles ); foreach( $this->to_do as $key => $handle ) { if ( !in_array($handle, $this->done, true) && isset($this->registered[$handle]) ) { if ( ! $this->registered[$handle]->src ) { // Defines a group. $this->done[] = $handle; continue; } if ( $this->do_item( $handle, $group ) ) $this->done[] = $handle; unset( $this->to_do[$key] ); } } return $this->done; } function do_item( $handle ) { return isset($this->registered[$handle]); } /** * Determines dependencies * * Recursively builds array of items to process taking dependencies into account. Does NOT catch infinite loops. * * * @param mixed $handles Accepts (string) dep name or (array of strings) dep names * @param bool $recursion Used internally when function calls itself */ function all_deps( $handles, $recursion = false, $group = false ) { if ( !$handles = (array) $handles ) return false; foreach ( $handles as $handle ) { $handle_parts = explode('?', $handle); $handle = $handle_parts[0]; $queued = in_array($handle, $this->to_do, true); if ( in_array($handle, $this->done, true) ) // Already done continue; $moved = $this->set_group( $handle, $recursion, $group ); if ( $queued && !$moved ) // already queued and in the right group continue; $keep_going = true; if ( !isset($this->registered[$handle]) ) $keep_going = false; // Script doesn't exist elseif ( $this->registered[$handle]->deps && array_diff($this->registered[$handle]->deps, array_keys($this->registered)) ) $keep_going = false; // Script requires deps which don't exist (not a necessary check. efficiency?) elseif ( $this->registered[$handle]->deps && !$this->all_deps( $this->registered[$handle]->deps, true, $group ) ) $keep_going = false; // Script requires deps which don't exist if ( !$keep_going ) { // Either script or its deps don't exist. if ( $recursion ) return false; // Abort this branch. else continue; // We're at the top level. Move on to the next one. } if ( $queued ) // Already grobbed it and its deps continue; if ( isset($handle_parts[1]) ) $this->args[$handle] = $handle_parts[1]; $this->to_do[] = $handle; } return true; } /** * Adds item * * Adds the item only if no item of that name already exists * * @param string $handle Script name * @param string $src Script url * @param array $deps (optional) Array of script names on which this script depends * @param string $ver (optional) Script version (used for cache busting) * @return array Hierarchical array of dependencies */ function add( $handle, $src, $deps = array(), $ver = false, $args = null ) { if ( isset($this->registered[$handle]) ) return false; $this->registered[$handle] = new _WP_Dependency( $handle, $src, $deps, $ver, $args ); return true; } /** * Adds extra data * * Adds data only if script has already been added. * * @param string $handle Script name * @param string $key * @param mixed $value * @return bool success */ function add_data( $handle, $key, $value ) { if ( !isset( $this->registered[$handle] ) ) return false; return $this->registered[$handle]->add_data( $key, $value ); } /** * Get extra data * * Gets data associated with a certain handle. * * @since WP 3.3 * * @param string $handle Script name * @param string $key * @return mixed */ function get_data( $handle, $key ) { if ( !isset( $this->registered[$handle] ) ) return false; if ( !isset( $this->registered[$handle]->extra[$key] ) ) return false; return $this->registered[$handle]->extra[$key]; } function remove( $handles ) { foreach ( (array) $handles as $handle ) unset($this->registered[$handle]); } function enqueue( $handles ) { foreach ( (array) $handles as $handle ) { $handle = explode('?', $handle); if ( !in_array($handle[0], $this->queue) && isset($this->registered[$handle[0]]) ) { $this->queue[] = $handle[0]; if ( isset($handle[1]) ) $this->args[$handle[0]] = $handle[1]; } } } function dequeue( $handles ) { foreach ( (array) $handles as $handle ) { $handle = explode('?', $handle); $key = array_search($handle[0], $this->queue); if ( false !== $key ) { unset($this->queue[$key]); unset($this->args[$handle[0]]); } } } function query( $handle, $list = 'registered' ) { switch ( $list ) { case 'registered' : case 'scripts': // back compat if ( isset( $this->registered[ $handle ] ) ) return $this->registered[ $handle ]; return false; case 'enqueued' : case 'queue' : return in_array( $handle, $this->queue ); case 'to_do' : case 'to_print': // back compat return in_array( $handle, $this->to_do ); case 'done' : case 'printed': // back compat return in_array( $handle, $this->done ); } return false; } function set_group( $handle, $recursion, $group ) { $group = (int) $group; if ( $recursion ) $group = min($this->group, $group); else $this->group = $group; if ( isset($this->groups[$handle]) && $this->groups[$handle] <= $group ) return false; $this->groups[$handle] = $group; return true; } } class _WP_Dependency { var $handle; var $src; var $deps = array(); var $ver = false; var $args = null; var $extra = array(); function __construct() { @list( $this->handle, $this->src, $this->deps, $this->ver, $this->args ) = func_get_args(); if ( ! is_array($this->deps) ) $this->deps = array(); } function add_data( $name, $data ) { if ( !is_scalar($name) ) return false; $this->extra[$name] = $data; return true; } }
zyblog
trunk/zyblog/wp-includes/class.wp-dependencies.php
PHP
asf20
6,779
<?php /** * Sets up the default filters and actions for Multisite. * * If you need to remove a default hook, this file will give you the priority * for which to use to remove the hook. * * Not all of the Multisite default hooks are found in ms-default-filters.php * * @package WordPress * @subpackage Multisite * @see default-filters.php * @since 3.0.0 */ // Users add_filter( 'wpmu_validate_user_signup', 'signup_nonce_check' ); add_action( 'init', 'maybe_add_existing_user_to_blog' ); add_action( 'wpmu_new_user', 'newuser_notify_siteadmin' ); add_action( 'wpmu_activate_user', 'add_new_user_to_blog', 10, 3 ); add_action( 'sanitize_user', 'strtolower' ); // Blogs add_filter( 'wpmu_validate_blog_signup', 'signup_nonce_check' ); add_action( 'wpmu_new_blog', 'wpmu_log_new_registrations', 10, 2 ); add_action( 'wpmu_new_blog', 'newblog_notify_siteadmin', 10, 2 ); // Register Nonce add_action( 'signup_hidden_fields', 'signup_nonce_fields' ); // Template add_action( 'template_redirect', 'maybe_redirect_404' ); add_filter( 'allowed_redirect_hosts', 'redirect_this_site' ); // Administration add_filter( 'term_id_filter', 'global_terms', 10, 2 ); add_action( 'publish_post', 'update_posts_count' ); add_action( 'delete_post', '_update_blog_date_on_post_delete' ); add_action( 'transition_post_status', '_update_blog_date_on_post_publish', 10, 3 ); add_action( 'admin_init', 'wp_schedule_update_network_counts'); add_action( 'update_network_counts', 'wp_update_network_counts'); // Files add_filter( 'wp_upload_bits', 'upload_is_file_too_big' ); add_filter( 'import_upload_size_limit', 'fix_import_form_size' ); add_filter( 'upload_mimes', 'check_upload_mimes' ); add_filter( 'upload_size_limit', 'upload_size_limit_filter' ); add_action( 'upload_ui_over_quota', 'multisite_over_quota_message' ); // Mail add_action( 'phpmailer_init', 'fix_phpmailer_messageid' ); // Disable somethings by default for multisite add_filter( 'enable_update_services_configuration', '__return_false' ); if ( ! defined('POST_BY_EMAIL') || ! POST_BY_EMAIL ) // back compat constant. add_filter( 'enable_post_by_email_configuration', '__return_false' ); if ( ! defined('EDIT_ANY_USER') || ! EDIT_ANY_USER ) // back compat constant. add_filter( 'enable_edit_any_user_configuration', '__return_false' ); add_filter( 'force_filtered_html_on_import', '__return_true' ); // WP_HOME and WP_SITEURL should not have any effect in MS remove_filter( 'option_siteurl', '_config_wp_siteurl' ); remove_filter( 'option_home', '_config_wp_home' ); // If the network upgrade hasn't run yet, assume ms-files.php rewriting is used. add_filter( 'default_site_option_ms_files_rewriting', '__return_true' );
zyblog
trunk/zyblog/wp-includes/ms-default-filters.php
PHP
asf20
2,694
<?php /*~ class.phpmailer.php .---------------------------------------------------------------------------. | Software: PHPMailer - PHP email class | | Version: 5.2.1 | | Site: https://code.google.com/a/apache-extras.org/p/phpmailer/ | | ------------------------------------------------------------------------- | | Admin: Jim Jagielski (project admininistrator) | | Authors: Andy Prevost (codeworxtech) codeworxtech@users.sourceforge.net | | : Marcus Bointon (coolbru) coolbru@users.sourceforge.net | | : Jim Jagielski (jimjag) jimjag@gmail.com | | Founder: Brent R. Matzelle (original founder) | | Copyright (c) 2010-2012, Jim Jagielski. All Rights Reserved. | | Copyright (c) 2004-2009, Andy Prevost. All Rights Reserved. | | Copyright (c) 2001-2003, Brent R. Matzelle | | ------------------------------------------------------------------------- | | License: Distributed under the Lesser General Public License (LGPL) | | http://www.gnu.org/copyleft/lesser.html | | This program is distributed in the hope that it will be useful - WITHOUT | | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or | | FITNESS FOR A PARTICULAR PURPOSE. | '---------------------------------------------------------------------------' */ /** * PHPMailer - PHP email transport class * NOTE: Requires PHP version 5 or later * @package PHPMailer * @author Andy Prevost * @author Marcus Bointon * @author Jim Jagielski * @copyright 2010 - 2012 Jim Jagielski * @copyright 2004 - 2009 Andy Prevost * @version $Id: class.phpmailer.php 450 2010-06-23 16:46:33Z coolbru $ * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License */ if (version_compare(PHP_VERSION, '5.0.0', '<') ) exit("Sorry, this version of PHPMailer will only run on PHP version 5 or greater!\n"); class PHPMailer { ///////////////////////////////////////////////// // PROPERTIES, PUBLIC ///////////////////////////////////////////////// /** * Email priority (1 = High, 3 = Normal, 5 = low). * @var int */ public $Priority = 3; /** * Sets the CharSet of the message. * @var string */ public $CharSet = 'iso-8859-1'; /** * Sets the Content-type of the message. * @var string */ public $ContentType = 'text/plain'; /** * Sets the Encoding of the message. Options for this are * "8bit", "7bit", "binary", "base64", and "quoted-printable". * @var string */ public $Encoding = '8bit'; /** * Holds the most recent mailer error message. * @var string */ public $ErrorInfo = ''; /** * Sets the From email address for the message. * @var string */ public $From = 'root@localhost'; /** * Sets the From name of the message. * @var string */ public $FromName = 'Root User'; /** * Sets the Sender email (Return-Path) of the message. If not empty, * will be sent via -f to sendmail or as 'MAIL FROM' in smtp mode. * @var string */ public $Sender = ''; /** * Sets the Subject of the message. * @var string */ public $Subject = ''; /** * Sets the Body of the message. This can be either an HTML or text body. * If HTML then run IsHTML(true). * @var string */ public $Body = ''; /** * Sets the text-only body of the message. This automatically sets the * email to multipart/alternative. This body can be read by mail * clients that do not have HTML email capability such as mutt. Clients * that can read HTML will view the normal Body. * @var string */ public $AltBody = ''; /** * Stores the complete compiled MIME message body. * @var string * @access protected */ protected $MIMEBody = ''; /** * Stores the complete compiled MIME message headers. * @var string * @access protected */ protected $MIMEHeader = ''; /** * Stores the complete sent MIME message (Body and Headers) * @var string * @access protected */ protected $SentMIMEMessage = ''; /** * Sets word wrapping on the body of the message to a given number of * characters. * @var int */ public $WordWrap = 0; /** * Method to send mail: ("mail", "sendmail", or "smtp"). * @var string */ public $Mailer = 'mail'; /** * Sets the path of the sendmail program. * @var string */ public $Sendmail = '/usr/sbin/sendmail'; /** * Path to PHPMailer plugins. Useful if the SMTP class * is in a different directory than the PHP include path. * @var string */ public $PluginDir = ''; /** * Sets the email address that a reading confirmation will be sent. * @var string */ public $ConfirmReadingTo = ''; /** * Sets the hostname to use in Message-Id and Received headers * and as default HELO string. If empty, the value returned * by SERVER_NAME is used or 'localhost.localdomain'. * @var string */ public $Hostname = ''; /** * Sets the message ID to be used in the Message-Id header. * If empty, a unique id will be generated. * @var string */ public $MessageID = ''; ///////////////////////////////////////////////// // PROPERTIES FOR SMTP ///////////////////////////////////////////////// /** * Sets the SMTP hosts. All hosts must be separated by a * semicolon. You can also specify a different port * for each host by using this format: [hostname:port] * (e.g. "smtp1.example.com:25;smtp2.example.com"). * Hosts will be tried in order. * @var string */ public $Host = 'localhost'; /** * Sets the default SMTP server port. * @var int */ public $Port = 25; /** * Sets the SMTP HELO of the message (Default is $Hostname). * @var string */ public $Helo = ''; /** * Sets connection prefix. * Options are "", "ssl" or "tls" * @var string */ public $SMTPSecure = ''; /** * Sets SMTP authentication. Utilizes the Username and Password variables. * @var bool */ public $SMTPAuth = false; /** * Sets SMTP username. * @var string */ public $Username = ''; /** * Sets SMTP password. * @var string */ public $Password = ''; /** * Sets the SMTP server timeout in seconds. * This function will not work with the win32 version. * @var int */ public $Timeout = 10; /** * Sets SMTP class debugging on or off. * @var bool */ public $SMTPDebug = false; /** * Prevents the SMTP connection from being closed after each mail * sending. If this is set to true then to close the connection * requires an explicit call to SmtpClose(). * @var bool */ public $SMTPKeepAlive = false; /** * Provides the ability to have the TO field process individual * emails, instead of sending to entire TO addresses * @var bool */ public $SingleTo = false; /** * If SingleTo is true, this provides the array to hold the email addresses * @var bool */ public $SingleToArray = array(); /** * Provides the ability to change the line ending * @var string */ public $LE = "\n"; /** * Used with DKIM DNS Resource Record * @var string */ public $DKIM_selector = 'phpmailer'; /** * Used with DKIM DNS Resource Record * optional, in format of email address 'you@yourdomain.com' * @var string */ public $DKIM_identity = ''; /** * Used with DKIM DNS Resource Record * @var string */ public $DKIM_passphrase = ''; /** * Used with DKIM DNS Resource Record * optional, in format of email address 'you@yourdomain.com' * @var string */ public $DKIM_domain = ''; /** * Used with DKIM DNS Resource Record * optional, in format of email address 'you@yourdomain.com' * @var string */ public $DKIM_private = ''; /** * Callback Action function name * the function that handles the result of the send email action. Parameters: * bool $result result of the send action * string $to email address of the recipient * string $cc cc email addresses * string $bcc bcc email addresses * string $subject the subject * string $body the email body * @var string */ public $action_function = ''; //'callbackAction'; /** * Sets the PHPMailer Version number * @var string */ public $Version = '5.2.1'; /** * What to use in the X-Mailer header * @var string */ public $XMailer = ''; ///////////////////////////////////////////////// // PROPERTIES, PRIVATE AND PROTECTED ///////////////////////////////////////////////// protected $smtp = NULL; protected $to = array(); protected $cc = array(); protected $bcc = array(); protected $ReplyTo = array(); protected $all_recipients = array(); protected $attachment = array(); protected $CustomHeader = array(); protected $message_type = ''; protected $boundary = array(); protected $language = array(); protected $error_count = 0; protected $sign_cert_file = ''; protected $sign_key_file = ''; protected $sign_key_pass = ''; protected $exceptions = false; ///////////////////////////////////////////////// // CONSTANTS ///////////////////////////////////////////////// const STOP_MESSAGE = 0; // message only, continue processing const STOP_CONTINUE = 1; // message?, likely ok to continue processing const STOP_CRITICAL = 2; // message, plus full stop, critical error reached ///////////////////////////////////////////////// // METHODS, VARIABLES ///////////////////////////////////////////////// /** * Constructor * @param boolean $exceptions Should we throw external exceptions? */ public function __construct($exceptions = false) { $this->exceptions = ($exceptions == true); } /** * Sets message type to HTML. * @param bool $ishtml * @return void */ public function IsHTML($ishtml = true) { if ($ishtml) { $this->ContentType = 'text/html'; } else { $this->ContentType = 'text/plain'; } } /** * Sets Mailer to send message using SMTP. * @return void */ public function IsSMTP() { $this->Mailer = 'smtp'; } /** * Sets Mailer to send message using PHP mail() function. * @return void */ public function IsMail() { $this->Mailer = 'mail'; } /** * Sets Mailer to send message using the $Sendmail program. * @return void */ public function IsSendmail() { if (!stristr(ini_get('sendmail_path'), 'sendmail')) { $this->Sendmail = '/var/qmail/bin/sendmail'; } $this->Mailer = 'sendmail'; } /** * Sets Mailer to send message using the qmail MTA. * @return void */ public function IsQmail() { if (stristr(ini_get('sendmail_path'), 'qmail')) { $this->Sendmail = '/var/qmail/bin/sendmail'; } $this->Mailer = 'sendmail'; } ///////////////////////////////////////////////// // METHODS, RECIPIENTS ///////////////////////////////////////////////// /** * Adds a "To" address. * @param string $address * @param string $name * @return boolean true on success, false if address already used */ public function AddAddress($address, $name = '') { return $this->AddAnAddress('to', $address, $name); } /** * Adds a "Cc" address. * Note: this function works with the SMTP mailer on win32, not with the "mail" mailer. * @param string $address * @param string $name * @return boolean true on success, false if address already used */ public function AddCC($address, $name = '') { return $this->AddAnAddress('cc', $address, $name); } /** * Adds a "Bcc" address. * Note: this function works with the SMTP mailer on win32, not with the "mail" mailer. * @param string $address * @param string $name * @return boolean true on success, false if address already used */ public function AddBCC($address, $name = '') { return $this->AddAnAddress('bcc', $address, $name); } /** * Adds a "Reply-to" address. * @param string $address * @param string $name * @return boolean */ public function AddReplyTo($address, $name = '') { return $this->AddAnAddress('Reply-To', $address, $name); } /** * Adds an address to one of the recipient arrays * Addresses that have been added already return false, but do not throw exceptions * @param string $kind One of 'to', 'cc', 'bcc', 'ReplyTo' * @param string $address The email address to send to * @param string $name * @return boolean true on success, false if address already used or invalid in some way * @access protected */ protected function AddAnAddress($kind, $address, $name = '') { if (!preg_match('/^(to|cc|bcc|Reply-To)$/', $kind)) { $this->SetError($this->Lang('Invalid recipient array').': '.$kind); if ($this->exceptions) { throw new phpmailerException('Invalid recipient array: ' . $kind); } if ($this->SMTPDebug) { echo $this->Lang('Invalid recipient array').': '.$kind; } return false; } $address = trim($address); $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim if (!self::ValidateAddress($address)) { $this->SetError($this->Lang('invalid_address').': '. $address); if ($this->exceptions) { throw new phpmailerException($this->Lang('invalid_address').': '.$address); } if ($this->SMTPDebug) { echo $this->Lang('invalid_address').': '.$address; } return false; } if ($kind != 'Reply-To') { if (!isset($this->all_recipients[strtolower($address)])) { array_push($this->$kind, array($address, $name)); $this->all_recipients[strtolower($address)] = true; return true; } } else { if (!array_key_exists(strtolower($address), $this->ReplyTo)) { $this->ReplyTo[strtolower($address)] = array($address, $name); return true; } } return false; } /** * Set the From and FromName properties * @param string $address * @param string $name * @return boolean */ public function SetFrom($address, $name = '', $auto = 1) { $address = trim($address); $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim if (!self::ValidateAddress($address)) { $this->SetError($this->Lang('invalid_address').': '. $address); if ($this->exceptions) { throw new phpmailerException($this->Lang('invalid_address').': '.$address); } if ($this->SMTPDebug) { echo $this->Lang('invalid_address').': '.$address; } return false; } $this->From = $address; $this->FromName = $name; if ($auto) { if (empty($this->ReplyTo)) { $this->AddAnAddress('Reply-To', $address, $name); } if (empty($this->Sender)) { $this->Sender = $address; } } return true; } /** * Check that a string looks roughly like an email address should * Static so it can be used without instantiation * Tries to use PHP built-in validator in the filter extension (from PHP 5.2), falls back to a reasonably competent regex validator * Conforms approximately to RFC2822 * @link http://www.hexillion.com/samples/#Regex Original pattern found here * @param string $address The email address to check * @return boolean * @static * @access public */ public static function ValidateAddress($address) { if (function_exists('filter_var')) { //Introduced in PHP 5.2 if(filter_var($address, FILTER_VALIDATE_EMAIL) === FALSE) { return false; } else { return true; } } else { return preg_match('/^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!\.)){0,61}[a-zA-Z0-9_-]?\.)+[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!$)){0,61}[a-zA-Z0-9_]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/', $address); } } ///////////////////////////////////////////////// // METHODS, MAIL SENDING ///////////////////////////////////////////////// /** * Creates message and assigns Mailer. If the message is * not sent successfully then it returns false. Use the ErrorInfo * variable to view description of the error. * @return bool */ public function Send() { try { if(!$this->PreSend()) return false; return $this->PostSend(); } catch (phpmailerException $e) { $this->SentMIMEMessage = ''; $this->SetError($e->getMessage()); if ($this->exceptions) { throw $e; } return false; } } protected function PreSend() { try { $mailHeader = ""; if ((count($this->to) + count($this->cc) + count($this->bcc)) < 1) { throw new phpmailerException($this->Lang('provide_address'), self::STOP_CRITICAL); } // Set whether the message is multipart/alternative if(!empty($this->AltBody)) { $this->ContentType = 'multipart/alternative'; } $this->error_count = 0; // reset errors $this->SetMessageType(); //Refuse to send an empty message if (empty($this->Body)) { throw new phpmailerException($this->Lang('empty_message'), self::STOP_CRITICAL); } $this->MIMEHeader = $this->CreateHeader(); $this->MIMEBody = $this->CreateBody(); // To capture the complete message when using mail(), create // an extra header list which CreateHeader() doesn't fold in if ($this->Mailer == 'mail') { if (count($this->to) > 0) { $mailHeader .= $this->AddrAppend("To", $this->to); } else { $mailHeader .= $this->HeaderLine("To", "undisclosed-recipients:;"); } $mailHeader .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader(trim($this->Subject)))); // if(count($this->cc) > 0) { // $mailHeader .= $this->AddrAppend("Cc", $this->cc); // } } // digitally sign with DKIM if enabled if ($this->DKIM_domain && $this->DKIM_private) { $header_dkim = $this->DKIM_Add($this->MIMEHeader, $this->EncodeHeader($this->SecureHeader($this->Subject)), $this->MIMEBody); $this->MIMEHeader = str_replace("\r\n", "\n", $header_dkim) . $this->MIMEHeader; } $this->SentMIMEMessage = sprintf("%s%s\r\n\r\n%s",$this->MIMEHeader,$mailHeader,$this->MIMEBody); return true; } catch (phpmailerException $e) { $this->SetError($e->getMessage()); if ($this->exceptions) { throw $e; } return false; } } protected function PostSend() { try { // Choose the mailer and send through it switch($this->Mailer) { case 'sendmail': return $this->SendmailSend($this->MIMEHeader, $this->MIMEBody); case 'smtp': return $this->SmtpSend($this->MIMEHeader, $this->MIMEBody); case 'mail': return $this->MailSend($this->MIMEHeader, $this->MIMEBody); default: return $this->MailSend($this->MIMEHeader, $this->MIMEBody); } } catch (phpmailerException $e) { $this->SetError($e->getMessage()); if ($this->exceptions) { throw $e; } if ($this->SMTPDebug) { echo $e->getMessage()."\n"; } return false; } } /** * Sends mail using the $Sendmail program. * @param string $header The message headers * @param string $body The message body * @access protected * @return bool */ protected function SendmailSend($header, $body) { if ($this->Sender != '') { $sendmail = sprintf("%s -oi -f %s -t", escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender)); } else { $sendmail = sprintf("%s -oi -t", escapeshellcmd($this->Sendmail)); } if ($this->SingleTo === true) { foreach ($this->SingleToArray as $key => $val) { if(!@$mail = popen($sendmail, 'w')) { throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL); } fputs($mail, "To: " . $val . "\n"); fputs($mail, $header); fputs($mail, $body); $result = pclose($mail); // implement call back function if it exists $isSent = ($result == 0) ? 1 : 0; $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body); if($result != 0) { throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL); } } } else { if(!@$mail = popen($sendmail, 'w')) { throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL); } fputs($mail, $header); fputs($mail, $body); $result = pclose($mail); // implement call back function if it exists $isSent = ($result == 0) ? 1 : 0; $this->doCallback($isSent, $this->to, $this->cc, $this->bcc, $this->Subject, $body); if($result != 0) { throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL); } } return true; } /** * Sends mail using the PHP mail() function. * @param string $header The message headers * @param string $body The message body * @access protected * @return bool */ protected function MailSend($header, $body) { $toArr = array(); foreach($this->to as $t) { $toArr[] = $this->AddrFormat($t); } $to = implode(', ', $toArr); if (empty($this->Sender)) { $params = "-oi "; } else { $params = sprintf("-oi -f %s", $this->Sender); } if ($this->Sender != '' and !ini_get('safe_mode')) { $old_from = ini_get('sendmail_from'); ini_set('sendmail_from', $this->Sender); if ($this->SingleTo === true && count($toArr) > 1) { foreach ($toArr as $key => $val) { $rt = @mail($val, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params); // implement call back function if it exists $isSent = ($rt == 1) ? 1 : 0; $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body); } } else { $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params); // implement call back function if it exists $isSent = ($rt == 1) ? 1 : 0; $this->doCallback($isSent, $to, $this->cc, $this->bcc, $this->Subject, $body); } } else { if ($this->SingleTo === true && count($toArr) > 1) { foreach ($toArr as $key => $val) { $rt = @mail($val, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header); // implement call back function if it exists $isSent = ($rt == 1) ? 1 : 0; $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body); } } else { $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header); // implement call back function if it exists $isSent = ($rt == 1) ? 1 : 0; $this->doCallback($isSent, $to, $this->cc, $this->bcc, $this->Subject, $body); } } if (isset($old_from)) { ini_set('sendmail_from', $old_from); } if(!$rt) { throw new phpmailerException($this->Lang('instantiate'), self::STOP_CRITICAL); } return true; } /** * Sends mail via SMTP using PhpSMTP * Returns false if there is a bad MAIL FROM, RCPT, or DATA input. * @param string $header The message headers * @param string $body The message body * @uses SMTP * @access protected * @return bool */ protected function SmtpSend($header, $body) { require_once $this->PluginDir . 'class-smtp.php'; $bad_rcpt = array(); if(!$this->SmtpConnect()) { throw new phpmailerException($this->Lang('smtp_connect_failed'), self::STOP_CRITICAL); } $smtp_from = ($this->Sender == '') ? $this->From : $this->Sender; if(!$this->smtp->Mail($smtp_from)) { throw new phpmailerException($this->Lang('from_failed') . $smtp_from, self::STOP_CRITICAL); } // Attempt to send attach all recipients foreach($this->to as $to) { if (!$this->smtp->Recipient($to[0])) { $bad_rcpt[] = $to[0]; // implement call back function if it exists $isSent = 0; $this->doCallback($isSent, $to[0], '', '', $this->Subject, $body); } else { // implement call back function if it exists $isSent = 1; $this->doCallback($isSent, $to[0], '', '', $this->Subject, $body); } } foreach($this->cc as $cc) { if (!$this->smtp->Recipient($cc[0])) { $bad_rcpt[] = $cc[0]; // implement call back function if it exists $isSent = 0; $this->doCallback($isSent, '', $cc[0], '', $this->Subject, $body); } else { // implement call back function if it exists $isSent = 1; $this->doCallback($isSent, '', $cc[0], '', $this->Subject, $body); } } foreach($this->bcc as $bcc) { if (!$this->smtp->Recipient($bcc[0])) { $bad_rcpt[] = $bcc[0]; // implement call back function if it exists $isSent = 0; $this->doCallback($isSent, '', '', $bcc[0], $this->Subject, $body); } else { // implement call back function if it exists $isSent = 1; $this->doCallback($isSent, '', '', $bcc[0], $this->Subject, $body); } } if (count($bad_rcpt) > 0 ) { //Create error message for any bad addresses $badaddresses = implode(', ', $bad_rcpt); throw new phpmailerException($this->Lang('recipients_failed') . $badaddresses); } if(!$this->smtp->Data($header . $body)) { throw new phpmailerException($this->Lang('data_not_accepted'), self::STOP_CRITICAL); } if($this->SMTPKeepAlive == true) { $this->smtp->Reset(); } return true; } /** * Initiates a connection to an SMTP server. * Returns false if the operation failed. * @uses SMTP * @access public * @return bool */ public function SmtpConnect() { if(is_null($this->smtp)) { $this->smtp = new SMTP(); } $this->smtp->do_debug = $this->SMTPDebug; $hosts = explode(';', $this->Host); $index = 0; $connection = $this->smtp->Connected(); // Retry while there is no connection try { while($index < count($hosts) && !$connection) { $hostinfo = array(); if (preg_match('/^(.+):([0-9]+)$/', $hosts[$index], $hostinfo)) { $host = $hostinfo[1]; $port = $hostinfo[2]; } else { $host = $hosts[$index]; $port = $this->Port; } $tls = ($this->SMTPSecure == 'tls'); $ssl = ($this->SMTPSecure == 'ssl'); if ($this->smtp->Connect(($ssl ? 'ssl://':'').$host, $port, $this->Timeout)) { $hello = ($this->Helo != '' ? $this->Helo : $this->ServerHostname()); $this->smtp->Hello($hello); if ($tls) { if (!$this->smtp->StartTLS()) { throw new phpmailerException($this->Lang('tls')); } //We must resend HELO after tls negotiation $this->smtp->Hello($hello); } $connection = true; if ($this->SMTPAuth) { if (!$this->smtp->Authenticate($this->Username, $this->Password)) { throw new phpmailerException($this->Lang('authenticate')); } } } $index++; if (!$connection) { throw new phpmailerException($this->Lang('connect_host')); } } } catch (phpmailerException $e) { $this->smtp->Reset(); if ($this->exceptions) { throw $e; } } return true; } /** * Closes the active SMTP session if one exists. * @return void */ public function SmtpClose() { if(!is_null($this->smtp)) { if($this->smtp->Connected()) { $this->smtp->Quit(); $this->smtp->Close(); } } } /** * Sets the language for all class error messages. * Returns false if it cannot load the language file. The default language is English. * @param string $langcode ISO 639-1 2-character language code (e.g. Portuguese: "br") * @param string $lang_path Path to the language file directory * @access public */ function SetLanguage($langcode = 'en', $lang_path = 'language/') { //Define full set of translatable strings $PHPMAILER_LANG = array( 'provide_address' => 'You must provide at least one recipient email address.', 'mailer_not_supported' => ' mailer is not supported.', 'execute' => 'Could not execute: ', 'instantiate' => 'Could not instantiate mail function.', 'authenticate' => 'SMTP Error: Could not authenticate.', 'from_failed' => 'The following From address failed: ', 'recipients_failed' => 'SMTP Error: The following recipients failed: ', 'data_not_accepted' => 'SMTP Error: Data not accepted.', 'connect_host' => 'SMTP Error: Could not connect to SMTP host.', 'file_access' => 'Could not access file: ', 'file_open' => 'File Error: Could not open file: ', 'encoding' => 'Unknown encoding: ', 'signing' => 'Signing Error: ', 'smtp_error' => 'SMTP server error: ', 'empty_message' => 'Message body empty', 'invalid_address' => 'Invalid address', 'variable_set' => 'Cannot set or reset variable: ' ); //Overwrite language-specific strings. This way we'll never have missing translations - no more "language string failed to load"! $l = true; if ($langcode != 'en') { //There is no English translation file $l = @include $lang_path.'phpmailer.lang-'.$langcode.'.php'; } $this->language = $PHPMAILER_LANG; return ($l == true); //Returns false if language not found } /** * Return the current array of language strings * @return array */ public function GetTranslations() { return $this->language; } ///////////////////////////////////////////////// // METHODS, MESSAGE CREATION ///////////////////////////////////////////////// /** * Creates recipient headers. * @access public * @return string */ public function AddrAppend($type, $addr) { $addr_str = $type . ': '; $addresses = array(); foreach ($addr as $a) { $addresses[] = $this->AddrFormat($a); } $addr_str .= implode(', ', $addresses); $addr_str .= $this->LE; return $addr_str; } /** * Formats an address correctly. * @access public * @return string */ public function AddrFormat($addr) { if (empty($addr[1])) { return $this->SecureHeader($addr[0]); } else { return $this->EncodeHeader($this->SecureHeader($addr[1]), 'phrase') . " <" . $this->SecureHeader($addr[0]) . ">"; } } /** * Wraps message for use with mailers that do not * automatically perform wrapping and for quoted-printable. * Original written by philippe. * @param string $message The message to wrap * @param integer $length The line length to wrap to * @param boolean $qp_mode Whether to run in Quoted-Printable mode * @access public * @return string */ public function WrapText($message, $length, $qp_mode = false) { $soft_break = ($qp_mode) ? sprintf(" =%s", $this->LE) : $this->LE; // If utf-8 encoding is used, we will need to make sure we don't // split multibyte characters when we wrap $is_utf8 = (strtolower($this->CharSet) == "utf-8"); $message = $this->FixEOL($message); if (substr($message, -1) == $this->LE) { $message = substr($message, 0, -1); } $line = explode($this->LE, $message); $message = ''; for ($i = 0 ;$i < count($line); $i++) { $line_part = explode(' ', $line[$i]); $buf = ''; for ($e = 0; $e<count($line_part); $e++) { $word = $line_part[$e]; if ($qp_mode and (strlen($word) > $length)) { $space_left = $length - strlen($buf) - 1; if ($e != 0) { if ($space_left > 20) { $len = $space_left; if ($is_utf8) { $len = $this->UTF8CharBoundary($word, $len); } elseif (substr($word, $len - 1, 1) == "=") { $len--; } elseif (substr($word, $len - 2, 1) == "=") { $len -= 2; } $part = substr($word, 0, $len); $word = substr($word, $len); $buf .= ' ' . $part; $message .= $buf . sprintf("=%s", $this->LE); } else { $message .= $buf . $soft_break; } $buf = ''; } while (strlen($word) > 0) { $len = $length; if ($is_utf8) { $len = $this->UTF8CharBoundary($word, $len); } elseif (substr($word, $len - 1, 1) == "=") { $len--; } elseif (substr($word, $len - 2, 1) == "=") { $len -= 2; } $part = substr($word, 0, $len); $word = substr($word, $len); if (strlen($word) > 0) { $message .= $part . sprintf("=%s", $this->LE); } else { $buf = $part; } } } else { $buf_o = $buf; $buf .= ($e == 0) ? $word : (' ' . $word); if (strlen($buf) > $length and $buf_o != '') { $message .= $buf_o . $soft_break; $buf = $word; } } } $message .= $buf . $this->LE; } return $message; } /** * Finds last character boundary prior to maxLength in a utf-8 * quoted (printable) encoded string. * Original written by Colin Brown. * @access public * @param string $encodedText utf-8 QP text * @param int $maxLength find last character boundary prior to this length * @return int */ public function UTF8CharBoundary($encodedText, $maxLength) { $foundSplitPos = false; $lookBack = 3; while (!$foundSplitPos) { $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack); $encodedCharPos = strpos($lastChunk, "="); if ($encodedCharPos !== false) { // Found start of encoded character byte within $lookBack block. // Check the encoded byte value (the 2 chars after the '=') $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2); $dec = hexdec($hex); if ($dec < 128) { // Single byte character. // If the encoded char was found at pos 0, it will fit // otherwise reduce maxLength to start of the encoded char $maxLength = ($encodedCharPos == 0) ? $maxLength : $maxLength - ($lookBack - $encodedCharPos); $foundSplitPos = true; } elseif ($dec >= 192) { // First byte of a multi byte character // Reduce maxLength to split at start of character $maxLength = $maxLength - ($lookBack - $encodedCharPos); $foundSplitPos = true; } elseif ($dec < 192) { // Middle byte of a multi byte character, look further back $lookBack += 3; } } else { // No encoded character found $foundSplitPos = true; } } return $maxLength; } /** * Set the body wrapping. * @access public * @return void */ public function SetWordWrap() { if($this->WordWrap < 1) { return; } switch($this->message_type) { case 'alt': case 'alt_inline': case 'alt_attach': case 'alt_inline_attach': $this->AltBody = $this->WrapText($this->AltBody, $this->WordWrap); break; default: $this->Body = $this->WrapText($this->Body, $this->WordWrap); break; } } /** * Assembles message header. * @access public * @return string The assembled header */ public function CreateHeader() { $result = ''; // Set the boundaries $uniq_id = md5(uniqid(time())); $this->boundary[1] = 'b1_' . $uniq_id; $this->boundary[2] = 'b2_' . $uniq_id; $this->boundary[3] = 'b3_' . $uniq_id; $result .= $this->HeaderLine('Date', self::RFCDate()); if($this->Sender == '') { $result .= $this->HeaderLine('Return-Path', trim($this->From)); } else { $result .= $this->HeaderLine('Return-Path', trim($this->Sender)); } // To be created automatically by mail() if($this->Mailer != 'mail') { if ($this->SingleTo === true) { foreach($this->to as $t) { $this->SingleToArray[] = $this->AddrFormat($t); } } else { if(count($this->to) > 0) { $result .= $this->AddrAppend('To', $this->to); } elseif (count($this->cc) == 0) { $result .= $this->HeaderLine('To', 'undisclosed-recipients:;'); } } } $from = array(); $from[0][0] = trim($this->From); $from[0][1] = $this->FromName; $result .= $this->AddrAppend('From', $from); // sendmail and mail() extract Cc from the header before sending if(count($this->cc) > 0) { $result .= $this->AddrAppend('Cc', $this->cc); } // sendmail and mail() extract Bcc from the header before sending if((($this->Mailer == 'sendmail') || ($this->Mailer == 'mail')) && (count($this->bcc) > 0)) { $result .= $this->AddrAppend('Bcc', $this->bcc); } if(count($this->ReplyTo) > 0) { $result .= $this->AddrAppend('Reply-To', $this->ReplyTo); } // mail() sets the subject itself if($this->Mailer != 'mail') { $result .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader($this->Subject))); } if($this->MessageID != '') { $result .= $this->HeaderLine('Message-ID', $this->MessageID); } else { $result .= sprintf("Message-ID: <%s@%s>%s", $uniq_id, $this->ServerHostname(), $this->LE); } $result .= $this->HeaderLine('X-Priority', $this->Priority); if($this->XMailer) { $result .= $this->HeaderLine('X-Mailer', $this->XMailer); } else { $result .= $this->HeaderLine('X-Mailer', 'PHPMailer '.$this->Version.' (http://code.google.com/a/apache-extras.org/p/phpmailer/)'); } if($this->ConfirmReadingTo != '') { $result .= $this->HeaderLine('Disposition-Notification-To', '<' . trim($this->ConfirmReadingTo) . '>'); } // Add custom headers for($index = 0; $index < count($this->CustomHeader); $index++) { $result .= $this->HeaderLine(trim($this->CustomHeader[$index][0]), $this->EncodeHeader(trim($this->CustomHeader[$index][1]))); } if (!$this->sign_key_file) { $result .= $this->HeaderLine('MIME-Version', '1.0'); $result .= $this->GetMailMIME(); } return $result; } /** * Returns the message MIME. * @access public * @return string */ public function GetMailMIME() { $result = ''; switch($this->message_type) { case 'plain': $result .= $this->HeaderLine('Content-Transfer-Encoding', $this->Encoding); $result .= $this->TextLine('Content-Type: '.$this->ContentType.'; charset="'.$this->CharSet.'"'); break; case 'inline': $result .= $this->HeaderLine('Content-Type', 'multipart/related;'); $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"'); break; case 'attach': case 'inline_attach': case 'alt_attach': case 'alt_inline_attach': $result .= $this->HeaderLine('Content-Type', 'multipart/mixed;'); $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"'); break; case 'alt': case 'alt_inline': $result .= $this->HeaderLine('Content-Type', 'multipart/alternative;'); $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"'); break; } if($this->Mailer != 'mail') { $result .= $this->LE.$this->LE; } return $result; } /** * Returns the MIME message (headers and body). Only really valid post PreSend(). * @access public * @return string */ public function GetSentMIMEMessage() { return $this->SentMIMEMessage; } /** * Assembles the message body. Returns an empty string on failure. * @access public * @return string The assembled message body */ public function CreateBody() { $body = ''; if ($this->sign_key_file) { $body .= $this->GetMailMIME(); } $this->SetWordWrap(); switch($this->message_type) { case 'plain': $body .= $this->EncodeString($this->Body, $this->Encoding); break; case 'inline': $body .= $this->GetBoundary($this->boundary[1], '', '', ''); $body .= $this->EncodeString($this->Body, $this->Encoding); $body .= $this->LE.$this->LE; $body .= $this->AttachAll("inline", $this->boundary[1]); break; case 'attach': $body .= $this->GetBoundary($this->boundary[1], '', '', ''); $body .= $this->EncodeString($this->Body, $this->Encoding); $body .= $this->LE.$this->LE; $body .= $this->AttachAll("attachment", $this->boundary[1]); break; case 'inline_attach': $body .= $this->TextLine("--" . $this->boundary[1]); $body .= $this->HeaderLine('Content-Type', 'multipart/related;'); $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"'); $body .= $this->LE; $body .= $this->GetBoundary($this->boundary[2], '', '', ''); $body .= $this->EncodeString($this->Body, $this->Encoding); $body .= $this->LE.$this->LE; $body .= $this->AttachAll("inline", $this->boundary[2]); $body .= $this->LE; $body .= $this->AttachAll("attachment", $this->boundary[1]); break; case 'alt': $body .= $this->GetBoundary($this->boundary[1], '', 'text/plain', ''); $body .= $this->EncodeString($this->AltBody, $this->Encoding); $body .= $this->LE.$this->LE; $body .= $this->GetBoundary($this->boundary[1], '', 'text/html', ''); $body .= $this->EncodeString($this->Body, $this->Encoding); $body .= $this->LE.$this->LE; $body .= $this->EndBoundary($this->boundary[1]); break; case 'alt_inline': $body .= $this->GetBoundary($this->boundary[1], '', 'text/plain', ''); $body .= $this->EncodeString($this->AltBody, $this->Encoding); $body .= $this->LE.$this->LE; $body .= $this->TextLine("--" . $this->boundary[1]); $body .= $this->HeaderLine('Content-Type', 'multipart/related;'); $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"'); $body .= $this->LE; $body .= $this->GetBoundary($this->boundary[2], '', 'text/html', ''); $body .= $this->EncodeString($this->Body, $this->Encoding); $body .= $this->LE.$this->LE; $body .= $this->AttachAll("inline", $this->boundary[2]); $body .= $this->LE; $body .= $this->EndBoundary($this->boundary[1]); break; case 'alt_attach': $body .= $this->TextLine("--" . $this->boundary[1]); $body .= $this->HeaderLine('Content-Type', 'multipart/alternative;'); $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"'); $body .= $this->LE; $body .= $this->GetBoundary($this->boundary[2], '', 'text/plain', ''); $body .= $this->EncodeString($this->AltBody, $this->Encoding); $body .= $this->LE.$this->LE; $body .= $this->GetBoundary($this->boundary[2], '', 'text/html', ''); $body .= $this->EncodeString($this->Body, $this->Encoding); $body .= $this->LE.$this->LE; $body .= $this->EndBoundary($this->boundary[2]); $body .= $this->LE; $body .= $this->AttachAll("attachment", $this->boundary[1]); break; case 'alt_inline_attach': $body .= $this->TextLine("--" . $this->boundary[1]); $body .= $this->HeaderLine('Content-Type', 'multipart/alternative;'); $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"'); $body .= $this->LE; $body .= $this->GetBoundary($this->boundary[2], '', 'text/plain', ''); $body .= $this->EncodeString($this->AltBody, $this->Encoding); $body .= $this->LE.$this->LE; $body .= $this->TextLine("--" . $this->boundary[2]); $body .= $this->HeaderLine('Content-Type', 'multipart/related;'); $body .= $this->TextLine("\tboundary=\"" . $this->boundary[3] . '"'); $body .= $this->LE; $body .= $this->GetBoundary($this->boundary[3], '', 'text/html', ''); $body .= $this->EncodeString($this->Body, $this->Encoding); $body .= $this->LE.$this->LE; $body .= $this->AttachAll("inline", $this->boundary[3]); $body .= $this->LE; $body .= $this->EndBoundary($this->boundary[2]); $body .= $this->LE; $body .= $this->AttachAll("attachment", $this->boundary[1]); break; } if ($this->IsError()) { $body = ''; } elseif ($this->sign_key_file) { try { $file = tempnam('', 'mail'); file_put_contents($file, $body); //TODO check this worked $signed = tempnam("", "signed"); if (@openssl_pkcs7_sign($file, $signed, "file://".$this->sign_cert_file, array("file://".$this->sign_key_file, $this->sign_key_pass), NULL)) { @unlink($file); $body = file_get_contents($signed); @unlink($signed); } else { @unlink($file); @unlink($signed); throw new phpmailerException($this->Lang("signing").openssl_error_string()); } } catch (phpmailerException $e) { $body = ''; if ($this->exceptions) { throw $e; } } } return $body; } /** * Returns the start of a message boundary. * @access protected * @return string */ protected function GetBoundary($boundary, $charSet, $contentType, $encoding) { $result = ''; if($charSet == '') { $charSet = $this->CharSet; } if($contentType == '') { $contentType = $this->ContentType; } if($encoding == '') { $encoding = $this->Encoding; } $result .= $this->TextLine('--' . $boundary); $result .= sprintf("Content-Type: %s; charset=\"%s\"", $contentType, $charSet); $result .= $this->LE; $result .= $this->HeaderLine('Content-Transfer-Encoding', $encoding); $result .= $this->LE; return $result; } /** * Returns the end of a message boundary. * @access protected * @return string */ protected function EndBoundary($boundary) { return $this->LE . '--' . $boundary . '--' . $this->LE; } /** * Sets the message type. * @access protected * @return void */ protected function SetMessageType() { $this->message_type = array(); if($this->AlternativeExists()) $this->message_type[] = "alt"; if($this->InlineImageExists()) $this->message_type[] = "inline"; if($this->AttachmentExists()) $this->message_type[] = "attach"; $this->message_type = implode("_", $this->message_type); if($this->message_type == "") $this->message_type = "plain"; } /** * Returns a formatted header line. * @access public * @return string */ public function HeaderLine($name, $value) { return $name . ': ' . $value . $this->LE; } /** * Returns a formatted mail line. * @access public * @return string */ public function TextLine($value) { return $value . $this->LE; } ///////////////////////////////////////////////// // CLASS METHODS, ATTACHMENTS ///////////////////////////////////////////////// /** * Adds an attachment from a path on the filesystem. * Returns false if the file could not be found * or accessed. * @param string $path Path to the attachment. * @param string $name Overrides the attachment name. * @param string $encoding File encoding (see $Encoding). * @param string $type File extension (MIME) type. * @return bool */ public function AddAttachment($path, $name = '', $encoding = 'base64', $type = 'application/octet-stream') { try { if ( !@is_file($path) ) { throw new phpmailerException($this->Lang('file_access') . $path, self::STOP_CONTINUE); } $filename = basename($path); if ( $name == '' ) { $name = $filename; } $this->attachment[] = array( 0 => $path, 1 => $filename, 2 => $name, 3 => $encoding, 4 => $type, 5 => false, // isStringAttachment 6 => 'attachment', 7 => 0 ); } catch (phpmailerException $e) { $this->SetError($e->getMessage()); if ($this->exceptions) { throw $e; } if ($this->SMTPDebug) { echo $e->getMessage()."\n"; } if ( $e->getCode() == self::STOP_CRITICAL ) { return false; } } return true; } /** * Return the current array of attachments * @return array */ public function GetAttachments() { return $this->attachment; } /** * Attaches all fs, string, and binary attachments to the message. * Returns an empty string on failure. * @access protected * @return string */ protected function AttachAll($disposition_type, $boundary) { // Return text of body $mime = array(); $cidUniq = array(); $incl = array(); // Add all attachments foreach ($this->attachment as $attachment) { // CHECK IF IT IS A VALID DISPOSITION_FILTER if($attachment[6] == $disposition_type) { // Check for string attachment $bString = $attachment[5]; if ($bString) { $string = $attachment[0]; } else { $path = $attachment[0]; } $inclhash = md5(serialize($attachment)); if (in_array($inclhash, $incl)) { continue; } $incl[] = $inclhash; $filename = $attachment[1]; $name = $attachment[2]; $encoding = $attachment[3]; $type = $attachment[4]; $disposition = $attachment[6]; $cid = $attachment[7]; if ( $disposition == 'inline' && isset($cidUniq[$cid]) ) { continue; } $cidUniq[$cid] = true; $mime[] = sprintf("--%s%s", $boundary, $this->LE); $mime[] = sprintf("Content-Type: %s; name=\"%s\"%s", $type, $this->EncodeHeader($this->SecureHeader($name)), $this->LE); $mime[] = sprintf("Content-Transfer-Encoding: %s%s", $encoding, $this->LE); if($disposition == 'inline') { $mime[] = sprintf("Content-ID: <%s>%s", $cid, $this->LE); } $mime[] = sprintf("Content-Disposition: %s; filename=\"%s\"%s", $disposition, $this->EncodeHeader($this->SecureHeader($name)), $this->LE.$this->LE); // Encode as string attachment if($bString) { $mime[] = $this->EncodeString($string, $encoding); if($this->IsError()) { return ''; } $mime[] = $this->LE.$this->LE; } else { $mime[] = $this->EncodeFile($path, $encoding); if($this->IsError()) { return ''; } $mime[] = $this->LE.$this->LE; } } } $mime[] = sprintf("--%s--%s", $boundary, $this->LE); return implode("", $mime); } /** * Encodes attachment in requested format. * Returns an empty string on failure. * @param string $path The full path to the file * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable' * @see EncodeFile() * @access protected * @return string */ protected function EncodeFile($path, $encoding = 'base64') { try { if (!is_readable($path)) { throw new phpmailerException($this->Lang('file_open') . $path, self::STOP_CONTINUE); } if (function_exists('get_magic_quotes')) { function get_magic_quotes() { return false; } } $magic_quotes = get_magic_quotes_runtime(); if ($magic_quotes) { if (version_compare(PHP_VERSION, '5.3.0', '<')) { set_magic_quotes_runtime(0); } else { ini_set('magic_quotes_runtime', 0); } } $file_buffer = file_get_contents($path); $file_buffer = $this->EncodeString($file_buffer, $encoding); if ($magic_quotes) { if (version_compare(PHP_VERSION, '5.3.0', '<')) { set_magic_quotes_runtime($magic_quotes); } else { ini_set('magic_quotes_runtime', $magic_quotes); } } return $file_buffer; } catch (Exception $e) { $this->SetError($e->getMessage()); return ''; } } /** * Encodes string to requested format. * Returns an empty string on failure. * @param string $str The text to encode * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable' * @access public * @return string */ public function EncodeString($str, $encoding = 'base64') { $encoded = ''; switch(strtolower($encoding)) { case 'base64': $encoded = chunk_split(base64_encode($str), 76, $this->LE); break; case '7bit': case '8bit': $encoded = $this->FixEOL($str); //Make sure it ends with a line break if (substr($encoded, -(strlen($this->LE))) != $this->LE) $encoded .= $this->LE; break; case 'binary': $encoded = $str; break; case 'quoted-printable': $encoded = $this->EncodeQP($str); break; default: $this->SetError($this->Lang('encoding') . $encoding); break; } return $encoded; } /** * Encode a header string to best (shortest) of Q, B, quoted or none. * @access public * @return string */ public function EncodeHeader($str, $position = 'text') { $x = 0; switch (strtolower($position)) { case 'phrase': if (!preg_match('/[\200-\377]/', $str)) { // Can't use addslashes as we don't know what value has magic_quotes_sybase $encoded = addcslashes($str, "\0..\37\177\\\""); if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) { return ($encoded); } else { return ("\"$encoded\""); } } $x = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches); break; case 'comment': $x = preg_match_all('/[()"]/', $str, $matches); // Fall-through case 'text': default: $x += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches); break; } if ($x == 0) { return ($str); } $maxlen = 75 - 7 - strlen($this->CharSet); // Try to select the encoding which should produce the shortest output if (strlen($str)/3 < $x) { $encoding = 'B'; if (function_exists('mb_strlen') && $this->HasMultiBytes($str)) { // Use a custom function which correctly encodes and wraps long // multibyte strings without breaking lines within a character $encoded = $this->Base64EncodeWrapMB($str); } else { $encoded = base64_encode($str); $maxlen -= $maxlen % 4; $encoded = trim(chunk_split($encoded, $maxlen, "\n")); } } else { $encoding = 'Q'; $encoded = $this->EncodeQ($str, $position); $encoded = $this->WrapText($encoded, $maxlen, true); $encoded = str_replace('='.$this->LE, "\n", trim($encoded)); } $encoded = preg_replace('/^(.*)$/m', " =?".$this->CharSet."?$encoding?\\1?=", $encoded); $encoded = trim(str_replace("\n", $this->LE, $encoded)); return $encoded; } /** * Checks if a string contains multibyte characters. * @access public * @param string $str multi-byte text to wrap encode * @return bool */ public function HasMultiBytes($str) { if (function_exists('mb_strlen')) { return (strlen($str) > mb_strlen($str, $this->CharSet)); } else { // Assume no multibytes (we can't handle without mbstring functions anyway) return false; } } /** * Correctly encodes and wraps long multibyte strings for mail headers * without breaking lines within a character. * Adapted from a function by paravoid at http://uk.php.net/manual/en/function.mb-encode-mimeheader.php * @access public * @param string $str multi-byte text to wrap encode * @return string */ public function Base64EncodeWrapMB($str) { $start = "=?".$this->CharSet."?B?"; $end = "?="; $encoded = ""; $mb_length = mb_strlen($str, $this->CharSet); // Each line must have length <= 75, including $start and $end $length = 75 - strlen($start) - strlen($end); // Average multi-byte ratio $ratio = $mb_length / strlen($str); // Base64 has a 4:3 ratio $offset = $avgLength = floor($length * $ratio * .75); for ($i = 0; $i < $mb_length; $i += $offset) { $lookBack = 0; do { $offset = $avgLength - $lookBack; $chunk = mb_substr($str, $i, $offset, $this->CharSet); $chunk = base64_encode($chunk); $lookBack++; } while (strlen($chunk) > $length); $encoded .= $chunk . $this->LE; } // Chomp the last linefeed $encoded = substr($encoded, 0, -strlen($this->LE)); return $encoded; } /** * Encode string to quoted-printable. * Only uses standard PHP, slow, but will always work * @access public * @param string $string the text to encode * @param integer $line_max Number of chars allowed on a line before wrapping * @return string */ public function EncodeQPphp( $input = '', $line_max = 76, $space_conv = false) { $hex = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'); $lines = preg_split('/(?:\r\n|\r|\n)/', $input); $eol = "\r\n"; $escape = '='; $output = ''; while( list(, $line) = each($lines) ) { $linlen = strlen($line); $newline = ''; for($i = 0; $i < $linlen; $i++) { $c = substr( $line, $i, 1 ); $dec = ord( $c ); if ( ( $i == 0 ) && ( $dec == 46 ) ) { // convert first point in the line into =2E $c = '=2E'; } if ( $dec == 32 ) { if ( $i == ( $linlen - 1 ) ) { // convert space at eol only $c = '=20'; } else if ( $space_conv ) { $c = '=20'; } } elseif ( ($dec == 61) || ($dec < 32 ) || ($dec > 126) ) { // always encode "\t", which is *not* required $h2 = floor($dec/16); $h1 = floor($dec%16); $c = $escape.$hex[$h2].$hex[$h1]; } if ( (strlen($newline) + strlen($c)) >= $line_max ) { // CRLF is not counted $output .= $newline.$escape.$eol; // soft line break; " =\r\n" is okay $newline = ''; // check if newline first character will be point or not if ( $dec == 46 ) { $c = '=2E'; } } $newline .= $c; } // end of for $output .= $newline.$eol; } // end of while return $output; } /** * Encode string to RFC2045 (6.7) quoted-printable format * Uses a PHP5 stream filter to do the encoding about 64x faster than the old version * Also results in same content as you started with after decoding * @see EncodeQPphp() * @access public * @param string $string the text to encode * @param integer $line_max Number of chars allowed on a line before wrapping * @param boolean $space_conv Dummy param for compatibility with existing EncodeQP function * @return string * @author Marcus Bointon */ public function EncodeQP($string, $line_max = 76, $space_conv = false) { if (function_exists('quoted_printable_encode')) { //Use native function if it's available (>= PHP5.3) return quoted_printable_encode($string); } $filters = stream_get_filters(); if (!in_array('convert.*', $filters)) { //Got convert stream filter? return $this->EncodeQPphp($string, $line_max, $space_conv); //Fall back to old implementation } $fp = fopen('php://temp/', 'r+'); $string = preg_replace('/\r\n?/', $this->LE, $string); //Normalise line breaks $params = array('line-length' => $line_max, 'line-break-chars' => $this->LE); $s = stream_filter_append($fp, 'convert.quoted-printable-encode', STREAM_FILTER_READ, $params); fputs($fp, $string); rewind($fp); $out = stream_get_contents($fp); stream_filter_remove($s); $out = preg_replace('/^\./m', '=2E', $out); //Encode . if it is first char on a line, workaround for bug in Exchange fclose($fp); return $out; } /** * Encode string to q encoding. * @link http://tools.ietf.org/html/rfc2047 * @param string $str the text to encode * @param string $position Where the text is going to be used, see the RFC for what that means * @access public * @return string */ public function EncodeQ($str, $position = 'text') { // There should not be any EOL in the string $encoded = preg_replace('/[\r\n]*/', '', $str); switch (strtolower($position)) { case 'phrase': $encoded = preg_replace("/([^A-Za-z0-9!*+\/ -])/e", "'='.sprintf('%02X', ord('\\1'))", $encoded); break; case 'comment': $encoded = preg_replace("/([\(\)\"])/e", "'='.sprintf('%02X', ord('\\1'))", $encoded); case 'text': default: // Replace every high ascii, control =, ? and _ characters //TODO using /e (equivalent to eval()) is probably not a good idea $encoded = preg_replace('/([\000-\011\013\014\016-\037\075\077\137\177-\377])/e', "'='.sprintf('%02X', ord(stripslashes('\\1')))", $encoded); break; } // Replace every spaces to _ (more readable than =20) $encoded = str_replace(' ', '_', $encoded); return $encoded; } /** * Adds a string or binary attachment (non-filesystem) to the list. * This method can be used to attach ascii or binary data, * such as a BLOB record from a database. * @param string $string String attachment data. * @param string $filename Name of the attachment. * @param string $encoding File encoding (see $Encoding). * @param string $type File extension (MIME) type. * @return void */ public function AddStringAttachment($string, $filename, $encoding = 'base64', $type = 'application/octet-stream') { // Append to $attachment array $this->attachment[] = array( 0 => $string, 1 => $filename, 2 => basename($filename), 3 => $encoding, 4 => $type, 5 => true, // isStringAttachment 6 => 'attachment', 7 => 0 ); } /** * Adds an embedded attachment. This can include images, sounds, and * just about any other document. Make sure to set the $type to an * image type. For JPEG images use "image/jpeg" and for GIF images * use "image/gif". * @param string $path Path to the attachment. * @param string $cid Content ID of the attachment. Use this to identify * the Id for accessing the image in an HTML form. * @param string $name Overrides the attachment name. * @param string $encoding File encoding (see $Encoding). * @param string $type File extension (MIME) type. * @return bool */ public function AddEmbeddedImage($path, $cid, $name = '', $encoding = 'base64', $type = 'application/octet-stream') { if ( !@is_file($path) ) { $this->SetError($this->Lang('file_access') . $path); return false; } $filename = basename($path); if ( $name == '' ) { $name = $filename; } // Append to $attachment array $this->attachment[] = array( 0 => $path, 1 => $filename, 2 => $name, 3 => $encoding, 4 => $type, 5 => false, // isStringAttachment 6 => 'inline', 7 => $cid ); return true; } public function AddStringEmbeddedImage($string, $cid, $filename = '', $encoding = 'base64', $type = 'application/octet-stream') { // Append to $attachment array $this->attachment[] = array( 0 => $string, 1 => $filename, 2 => basename($filename), 3 => $encoding, 4 => $type, 5 => true, // isStringAttachment 6 => 'inline', 7 => $cid ); } /** * Returns true if an inline attachment is present. * @access public * @return bool */ public function InlineImageExists() { foreach($this->attachment as $attachment) { if ($attachment[6] == 'inline') { return true; } } return false; } public function AttachmentExists() { foreach($this->attachment as $attachment) { if ($attachment[6] == 'attachment') { return true; } } return false; } public function AlternativeExists() { return strlen($this->AltBody)>0; } ///////////////////////////////////////////////// // CLASS METHODS, MESSAGE RESET ///////////////////////////////////////////////// /** * Clears all recipients assigned in the TO array. Returns void. * @return void */ public function ClearAddresses() { foreach($this->to as $to) { unset($this->all_recipients[strtolower($to[0])]); } $this->to = array(); } /** * Clears all recipients assigned in the CC array. Returns void. * @return void */ public function ClearCCs() { foreach($this->cc as $cc) { unset($this->all_recipients[strtolower($cc[0])]); } $this->cc = array(); } /** * Clears all recipients assigned in the BCC array. Returns void. * @return void */ public function ClearBCCs() { foreach($this->bcc as $bcc) { unset($this->all_recipients[strtolower($bcc[0])]); } $this->bcc = array(); } /** * Clears all recipients assigned in the ReplyTo array. Returns void. * @return void */ public function ClearReplyTos() { $this->ReplyTo = array(); } /** * Clears all recipients assigned in the TO, CC and BCC * array. Returns void. * @return void */ public function ClearAllRecipients() { $this->to = array(); $this->cc = array(); $this->bcc = array(); $this->all_recipients = array(); } /** * Clears all previously set filesystem, string, and binary * attachments. Returns void. * @return void */ public function ClearAttachments() { $this->attachment = array(); } /** * Clears all custom headers. Returns void. * @return void */ public function ClearCustomHeaders() { $this->CustomHeader = array(); } ///////////////////////////////////////////////// // CLASS METHODS, MISCELLANEOUS ///////////////////////////////////////////////// /** * Adds the error message to the error container. * @access protected * @return void */ protected function SetError($msg) { $this->error_count++; if ($this->Mailer == 'smtp' and !is_null($this->smtp)) { $lasterror = $this->smtp->getError(); if (!empty($lasterror) and array_key_exists('smtp_msg', $lasterror)) { $msg .= '<p>' . $this->Lang('smtp_error') . $lasterror['smtp_msg'] . "</p>\n"; } } $this->ErrorInfo = $msg; } /** * Returns the proper RFC 822 formatted date. * @access public * @return string * @static */ public static function RFCDate() { $tz = date('Z'); $tzs = ($tz < 0) ? '-' : '+'; $tz = abs($tz); $tz = (int)($tz/3600)*100 + ($tz%3600)/60; $result = sprintf("%s %s%04d", date('D, j M Y H:i:s'), $tzs, $tz); return $result; } /** * Returns the server hostname or 'localhost.localdomain' if unknown. * @access protected * @return string */ protected function ServerHostname() { if (!empty($this->Hostname)) { $result = $this->Hostname; } elseif (isset($_SERVER['SERVER_NAME'])) { $result = $_SERVER['SERVER_NAME']; } else { $result = 'localhost.localdomain'; } return $result; } /** * Returns a message in the appropriate language. * @access protected * @return string */ protected function Lang($key) { if(count($this->language) < 1) { $this->SetLanguage('en'); // set the default language } if(isset($this->language[$key])) { return $this->language[$key]; } else { return 'Language string failed to load: ' . $key; } } /** * Returns true if an error occurred. * @access public * @return bool */ public function IsError() { return ($this->error_count > 0); } /** * Changes every end of line from CR or LF to CRLF. * @access public * @return string */ public function FixEOL($str) { $str = str_replace("\r\n", "\n", $str); $str = str_replace("\r", "\n", $str); $str = str_replace("\n", $this->LE, $str); return $str; } /** * Adds a custom header. * @access public * @return void */ public function AddCustomHeader($custom_header) { $this->CustomHeader[] = explode(':', $custom_header, 2); } /** * Evaluates the message and returns modifications for inline images and backgrounds * @access public * @return $message */ public function MsgHTML($message, $basedir = '') { preg_match_all("/(src|background)=[\"'](.*)[\"']/Ui", $message, $images); if(isset($images[2])) { foreach($images[2] as $i => $url) { // do not change urls for absolute images (thanks to corvuscorax) if (!preg_match('#^[A-z]+://#', $url)) { $filename = basename($url); $directory = dirname($url); ($directory == '.') ? $directory='': ''; $cid = 'cid:' . md5($filename); $ext = pathinfo($filename, PATHINFO_EXTENSION); $mimeType = self::_mime_types($ext); if ( strlen($basedir) > 1 && substr($basedir, -1) != '/') { $basedir .= '/'; } if ( strlen($directory) > 1 && substr($directory, -1) != '/') { $directory .= '/'; } if ( $this->AddEmbeddedImage($basedir.$directory.$filename, md5($filename), $filename, 'base64', $mimeType) ) { $message = preg_replace("/".$images[1][$i]."=[\"']".preg_quote($url, '/')."[\"']/Ui", $images[1][$i]."=\"".$cid."\"", $message); } } } } $this->IsHTML(true); $this->Body = $message; if (empty($this->AltBody)) { $textMsg = trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/s', '', $message))); if (!empty($textMsg)) { $this->AltBody = html_entity_decode($textMsg, ENT_QUOTES, $this->CharSet); } } if (empty($this->AltBody)) { $this->AltBody = 'To view this email message, open it in a program that understands HTML!' . "\n\n"; } return $message; } /** * Gets the MIME type of the embedded or inline image * @param string File extension * @access public * @return string MIME type of ext * @static */ public static function _mime_types($ext = '') { $mimes = array( 'hqx' => 'application/mac-binhex40', 'cpt' => 'application/mac-compactpro', 'doc' => 'application/msword', 'bin' => 'application/macbinary', 'dms' => 'application/octet-stream', 'lha' => 'application/octet-stream', 'lzh' => 'application/octet-stream', 'exe' => 'application/octet-stream', 'class' => 'application/octet-stream', 'psd' => 'application/octet-stream', 'so' => 'application/octet-stream', 'sea' => 'application/octet-stream', 'dll' => 'application/octet-stream', 'oda' => 'application/oda', 'pdf' => 'application/pdf', 'ai' => 'application/postscript', 'eps' => 'application/postscript', 'ps' => 'application/postscript', 'smi' => 'application/smil', 'smil' => 'application/smil', 'mif' => 'application/vnd.mif', 'xls' => 'application/vnd.ms-excel', 'ppt' => 'application/vnd.ms-powerpoint', 'wbxml' => 'application/vnd.wap.wbxml', 'wmlc' => 'application/vnd.wap.wmlc', 'dcr' => 'application/x-director', 'dir' => 'application/x-director', 'dxr' => 'application/x-director', 'dvi' => 'application/x-dvi', 'gtar' => 'application/x-gtar', 'php' => 'application/x-httpd-php', 'php4' => 'application/x-httpd-php', 'php3' => 'application/x-httpd-php', 'phtml' => 'application/x-httpd-php', 'phps' => 'application/x-httpd-php-source', 'js' => 'application/x-javascript', 'swf' => 'application/x-shockwave-flash', 'sit' => 'application/x-stuffit', 'tar' => 'application/x-tar', 'tgz' => 'application/x-tar', 'xhtml' => 'application/xhtml+xml', 'xht' => 'application/xhtml+xml', 'zip' => 'application/zip', 'mid' => 'audio/midi', 'midi' => 'audio/midi', 'mpga' => 'audio/mpeg', 'mp2' => 'audio/mpeg', 'mp3' => 'audio/mpeg', 'aif' => 'audio/x-aiff', 'aiff' => 'audio/x-aiff', 'aifc' => 'audio/x-aiff', 'ram' => 'audio/x-pn-realaudio', 'rm' => 'audio/x-pn-realaudio', 'rpm' => 'audio/x-pn-realaudio-plugin', 'ra' => 'audio/x-realaudio', 'rv' => 'video/vnd.rn-realvideo', 'wav' => 'audio/x-wav', 'bmp' => 'image/bmp', 'gif' => 'image/gif', 'jpeg' => 'image/jpeg', 'jpg' => 'image/jpeg', 'jpe' => 'image/jpeg', 'png' => 'image/png', 'tiff' => 'image/tiff', 'tif' => 'image/tiff', 'css' => 'text/css', 'html' => 'text/html', 'htm' => 'text/html', 'shtml' => 'text/html', 'txt' => 'text/plain', 'text' => 'text/plain', 'log' => 'text/plain', 'rtx' => 'text/richtext', 'rtf' => 'text/rtf', 'xml' => 'text/xml', 'xsl' => 'text/xml', 'mpeg' => 'video/mpeg', 'mpg' => 'video/mpeg', 'mpe' => 'video/mpeg', 'qt' => 'video/quicktime', 'mov' => 'video/quicktime', 'avi' => 'video/x-msvideo', 'movie' => 'video/x-sgi-movie', 'doc' => 'application/msword', 'word' => 'application/msword', 'xl' => 'application/excel', 'eml' => 'message/rfc822' ); return (!isset($mimes[strtolower($ext)])) ? 'application/octet-stream' : $mimes[strtolower($ext)]; } /** * Set (or reset) Class Objects (variables) * * Usage Example: * $page->set('X-Priority', '3'); * * @access public * @param string $name Parameter Name * @param mixed $value Parameter Value * NOTE: will not work with arrays, there are no arrays to set/reset * @todo Should this not be using __set() magic function? */ public function set($name, $value = '') { try { if (isset($this->$name) ) { $this->$name = $value; } else { throw new phpmailerException($this->Lang('variable_set') . $name, self::STOP_CRITICAL); } } catch (Exception $e) { $this->SetError($e->getMessage()); if ($e->getCode() == self::STOP_CRITICAL) { return false; } } return true; } /** * Strips newlines to prevent header injection. * @access public * @param string $str String * @return string */ public function SecureHeader($str) { $str = str_replace("\r", '', $str); $str = str_replace("\n", '', $str); return trim($str); } /** * Set the private key file and password to sign the message. * * @access public * @param string $key_filename Parameter File Name * @param string $key_pass Password for private key */ public function Sign($cert_filename, $key_filename, $key_pass) { $this->sign_cert_file = $cert_filename; $this->sign_key_file = $key_filename; $this->sign_key_pass = $key_pass; } /** * Set the private key file and password to sign the message. * * @access public * @param string $key_filename Parameter File Name * @param string $key_pass Password for private key */ public function DKIM_QP($txt) { $tmp = ''; $line = ''; for ($i = 0; $i < strlen($txt); $i++) { $ord = ord($txt[$i]); if ( ((0x21 <= $ord) && ($ord <= 0x3A)) || $ord == 0x3C || ((0x3E <= $ord) && ($ord <= 0x7E)) ) { $line .= $txt[$i]; } else { $line .= "=".sprintf("%02X", $ord); } } return $line; } /** * Generate DKIM signature * * @access public * @param string $s Header */ public function DKIM_Sign($s) { $privKeyStr = file_get_contents($this->DKIM_private); if ($this->DKIM_passphrase != '') { $privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase); } else { $privKey = $privKeyStr; } if (openssl_sign($s, $signature, $privKey)) { return base64_encode($signature); } } /** * Generate DKIM Canonicalization Header * * @access public * @param string $s Header */ public function DKIM_HeaderC($s) { $s = preg_replace("/\r\n\s+/", " ", $s); $lines = explode("\r\n", $s); foreach ($lines as $key => $line) { list($heading, $value) = explode(":", $line, 2); $heading = strtolower($heading); $value = preg_replace("/\s+/", " ", $value) ; // Compress useless spaces $lines[$key] = $heading.":".trim($value) ; // Don't forget to remove WSP around the value } $s = implode("\r\n", $lines); return $s; } /** * Generate DKIM Canonicalization Body * * @access public * @param string $body Message Body */ public function DKIM_BodyC($body) { if ($body == '') return "\r\n"; // stabilize line endings $body = str_replace("\r\n", "\n", $body); $body = str_replace("\n", "\r\n", $body); // END stabilize line endings while (substr($body, strlen($body) - 4, 4) == "\r\n\r\n") { $body = substr($body, 0, strlen($body) - 2); } return $body; } /** * Create the DKIM header, body, as new header * * @access public * @param string $headers_line Header lines * @param string $subject Subject * @param string $body Body */ public function DKIM_Add($headers_line, $subject, $body) { $DKIMsignatureType = 'rsa-sha1'; // Signature & hash algorithms $DKIMcanonicalization = 'relaxed/simple'; // Canonicalization of header/body $DKIMquery = 'dns/txt'; // Query method $DKIMtime = time() ; // Signature Timestamp = seconds since 00:00:00 - Jan 1, 1970 (UTC time zone) $subject_header = "Subject: $subject"; $headers = explode($this->LE, $headers_line); foreach($headers as $header) { if (strpos($header, 'From:') === 0) { $from_header = $header; } elseif (strpos($header, 'To:') === 0) { $to_header = $header; } } $from = str_replace('|', '=7C', $this->DKIM_QP($from_header)); $to = str_replace('|', '=7C', $this->DKIM_QP($to_header)); $subject = str_replace('|', '=7C', $this->DKIM_QP($subject_header)) ; // Copied header fields (dkim-quoted-printable $body = $this->DKIM_BodyC($body); $DKIMlen = strlen($body) ; // Length of body $DKIMb64 = base64_encode(pack("H*", sha1($body))) ; // Base64 of packed binary SHA-1 hash of body $ident = ($this->DKIM_identity == '')? '' : " i=" . $this->DKIM_identity . ";"; $dkimhdrs = "DKIM-Signature: v=1; a=" . $DKIMsignatureType . "; q=" . $DKIMquery . "; l=" . $DKIMlen . "; s=" . $this->DKIM_selector . ";\r\n". "\tt=" . $DKIMtime . "; c=" . $DKIMcanonicalization . ";\r\n". "\th=From:To:Subject;\r\n". "\td=" . $this->DKIM_domain . ";" . $ident . "\r\n". "\tz=$from\r\n". "\t|$to\r\n". "\t|$subject;\r\n". "\tbh=" . $DKIMb64 . ";\r\n". "\tb="; $toSign = $this->DKIM_HeaderC($from_header . "\r\n" . $to_header . "\r\n" . $subject_header . "\r\n" . $dkimhdrs); $signed = $this->DKIM_Sign($toSign); return "X-PHPMAILER-DKIM: phpmailer.worxware.com\r\n".$dkimhdrs.$signed."\r\n"; } protected function doCallback($isSent, $to, $cc, $bcc, $subject, $body) { if (!empty($this->action_function) && function_exists($this->action_function)) { $params = array($isSent, $to, $cc, $bcc, $subject, $body); call_user_func_array($this->action_function, $params); } } } class phpmailerException extends Exception { public function errorMessage() { $errorMsg = '<strong>' . $this->getMessage() . "</strong><br />\n"; return $errorMsg; } } ?>
zyblog
trunk/zyblog/wp-includes/class-phpmailer.php
PHP
asf20
81,728
<?php /** * The plugin API is located in this file, which allows for creating actions * and filters and hooking functions, and methods. The functions or methods will * then be run when the action or filter is called. * * The API callback examples reference functions, but can be methods of classes. * To hook methods, you'll need to pass an array one of two ways. * * Any of the syntaxes explained in the PHP documentation for the * {@link http://us2.php.net/manual/en/language.pseudo-types.php#language.types.callback 'callback'} * type are valid. * * Also see the {@link http://codex.wordpress.org/Plugin_API Plugin API} for * more information and examples on how to use a lot of these functions. * * @package WordPress * @subpackage Plugin * @since 1.5 */ /** * Hooks a function or method to a specific filter action. * * Filters are the hooks that WordPress launches to modify text of various types * before adding it to the database or sending it to the browser screen. Plugins * can specify that one or more of its PHP functions is executed to * modify specific types of text at these times, using the Filter API. * * To use the API, the following code should be used to bind a callback to the * filter. * * <code> * function example_hook($example) { echo $example; } * add_filter('example_filter', 'example_hook'); * </code> * * In WordPress 1.5.1+, hooked functions can take extra arguments that are set * when the matching do_action() or apply_filters() call is run. The * $accepted_args allow for calling functions only when the number of args * match. Hooked functions can take extra arguments that are set when the * matching do_action() or apply_filters() call is run. For example, the action * comment_id_not_found will pass any functions that hook onto it the ID of the * requested comment. * * <strong>Note:</strong> the function will return true no matter if the * function was hooked fails or not. There are no checks for whether the * function exists beforehand and no checks to whether the <tt>$function_to_add * is even a string. It is up to you to take care and this is done for * optimization purposes, so everything is as quick as possible. * * @package WordPress * @subpackage Plugin * @since 0.71 * @global array $wp_filter Stores all of the filters added in the form of * wp_filter['tag']['array of priorities']['array of functions serialized']['array of ['array (functions, accepted_args)']'] * @global array $merged_filters Tracks the tags that need to be merged for later. If the hook is added, it doesn't need to run through that process. * * @param string $tag The name of the filter to hook the $function_to_add to. * @param callback $function_to_add The name of the function to be called when the filter is applied. * @param int $priority optional. Used to specify the order in which the functions associated with a particular action are executed (default: 10). Lower numbers correspond with earlier execution, and functions with the same priority are executed in the order in which they were added to the action. * @param int $accepted_args optional. The number of arguments the function accept (default 1). * @return boolean true */ function add_filter($tag, $function_to_add, $priority = 10, $accepted_args = 1) { global $wp_filter, $merged_filters; $idx = _wp_filter_build_unique_id($tag, $function_to_add, $priority); $wp_filter[$tag][$priority][$idx] = array('function' => $function_to_add, 'accepted_args' => $accepted_args); unset( $merged_filters[ $tag ] ); return true; } /** * Check if any filter has been registered for a hook. * * @package WordPress * @subpackage Plugin * @since 2.5 * @global array $wp_filter Stores all of the filters * * @param string $tag The name of the filter hook. * @param callback $function_to_check optional. * @return mixed If $function_to_check is omitted, returns boolean for whether the hook has anything registered. * When checking a specific function, the priority of that hook is returned, or false if the function is not attached. * When using the $function_to_check argument, this function may return a non-boolean value that evaluates to false * (e.g.) 0, so use the === operator for testing the return value. */ function has_filter($tag, $function_to_check = false) { global $wp_filter; $has = !empty($wp_filter[$tag]); if ( false === $function_to_check || false == $has ) return $has; if ( !$idx = _wp_filter_build_unique_id($tag, $function_to_check, false) ) return false; foreach ( (array) array_keys($wp_filter[$tag]) as $priority ) { if ( isset($wp_filter[$tag][$priority][$idx]) ) return $priority; } return false; } /** * Call the functions added to a filter hook. * * The callback functions attached to filter hook $tag are invoked by calling * this function. This function can be used to create a new filter hook by * simply calling this function with the name of the new hook specified using * the $tag parameter. * * The function allows for additional arguments to be added and passed to hooks. * <code> * function example_hook($string, $arg1, $arg2) * { * //Do stuff * return $string; * } * $value = apply_filters('example_filter', 'filter me', 'arg1', 'arg2'); * </code> * * @package WordPress * @subpackage Plugin * @since 0.71 * @global array $wp_filter Stores all of the filters * @global array $merged_filters Merges the filter hooks using this function. * @global array $wp_current_filter stores the list of current filters with the current one last * * @param string $tag The name of the filter hook. * @param mixed $value The value on which the filters hooked to <tt>$tag</tt> are applied on. * @param mixed $var,... Additional variables passed to the functions hooked to <tt>$tag</tt>. * @return mixed The filtered value after all hooked functions are applied to it. */ function apply_filters($tag, $value) { global $wp_filter, $merged_filters, $wp_current_filter; $args = array(); // Do 'all' actions first if ( isset($wp_filter['all']) ) { $wp_current_filter[] = $tag; $args = func_get_args(); _wp_call_all_hook($args); } if ( !isset($wp_filter[$tag]) ) { if ( isset($wp_filter['all']) ) array_pop($wp_current_filter); return $value; } if ( !isset($wp_filter['all']) ) $wp_current_filter[] = $tag; // Sort if ( !isset( $merged_filters[ $tag ] ) ) { ksort($wp_filter[$tag]); $merged_filters[ $tag ] = true; } reset( $wp_filter[ $tag ] ); if ( empty($args) ) $args = func_get_args(); do { foreach( (array) current($wp_filter[$tag]) as $the_ ) if ( !is_null($the_['function']) ){ $args[1] = $value; $value = call_user_func_array($the_['function'], array_slice($args, 1, (int) $the_['accepted_args'])); } } while ( next($wp_filter[$tag]) !== false ); array_pop( $wp_current_filter ); return $value; } /** * Execute functions hooked on a specific filter hook, specifying arguments in an array. * * @see apply_filters() This function is identical, but the arguments passed to the * functions hooked to <tt>$tag</tt> are supplied using an array. * * @package WordPress * @subpackage Plugin * @since 3.0.0 * @global array $wp_filter Stores all of the filters * @global array $merged_filters Merges the filter hooks using this function. * @global array $wp_current_filter stores the list of current filters with the current one last * * @param string $tag The name of the filter hook. * @param array $args The arguments supplied to the functions hooked to <tt>$tag</tt> * @return mixed The filtered value after all hooked functions are applied to it. */ function apply_filters_ref_array($tag, $args) { global $wp_filter, $merged_filters, $wp_current_filter; // Do 'all' actions first if ( isset($wp_filter['all']) ) { $wp_current_filter[] = $tag; $all_args = func_get_args(); _wp_call_all_hook($all_args); } if ( !isset($wp_filter[$tag]) ) { if ( isset($wp_filter['all']) ) array_pop($wp_current_filter); return $args[0]; } if ( !isset($wp_filter['all']) ) $wp_current_filter[] = $tag; // Sort if ( !isset( $merged_filters[ $tag ] ) ) { ksort($wp_filter[$tag]); $merged_filters[ $tag ] = true; } reset( $wp_filter[ $tag ] ); do { foreach( (array) current($wp_filter[$tag]) as $the_ ) if ( !is_null($the_['function']) ) $args[0] = call_user_func_array($the_['function'], array_slice($args, 0, (int) $the_['accepted_args'])); } while ( next($wp_filter[$tag]) !== false ); array_pop( $wp_current_filter ); return $args[0]; } /** * Removes a function from a specified filter hook. * * This function removes a function attached to a specified filter hook. This * method can be used to remove default functions attached to a specific filter * hook and possibly replace them with a substitute. * * To remove a hook, the $function_to_remove and $priority arguments must match * when the hook was added. This goes for both filters and actions. No warning * will be given on removal failure. * * @package WordPress * @subpackage Plugin * @since 1.2 * * @param string $tag The filter hook to which the function to be removed is hooked. * @param callback $function_to_remove The name of the function which should be removed. * @param int $priority optional. The priority of the function (default: 10). * @param int $accepted_args optional. The number of arguments the function accepts (default: 1). * @return boolean Whether the function existed before it was removed. */ function remove_filter( $tag, $function_to_remove, $priority = 10 ) { $function_to_remove = _wp_filter_build_unique_id($tag, $function_to_remove, $priority); $r = isset($GLOBALS['wp_filter'][$tag][$priority][$function_to_remove]); if ( true === $r) { unset($GLOBALS['wp_filter'][$tag][$priority][$function_to_remove]); if ( empty($GLOBALS['wp_filter'][$tag][$priority]) ) unset($GLOBALS['wp_filter'][$tag][$priority]); unset($GLOBALS['merged_filters'][$tag]); } return $r; } /** * Remove all of the hooks from a filter. * * @since 2.7 * * @param string $tag The filter to remove hooks from. * @param int $priority The priority number to remove. * @return bool True when finished. */ function remove_all_filters($tag, $priority = false) { global $wp_filter, $merged_filters; if( isset($wp_filter[$tag]) ) { if( false !== $priority && isset($wp_filter[$tag][$priority]) ) unset($wp_filter[$tag][$priority]); else unset($wp_filter[$tag]); } if( isset($merged_filters[$tag]) ) unset($merged_filters[$tag]); return true; } /** * Retrieve the name of the current filter or action. * * @package WordPress * @subpackage Plugin * @since 2.5 * * @return string Hook name of the current filter or action. */ function current_filter() { global $wp_current_filter; return end( $wp_current_filter ); } /** * Hooks a function on to a specific action. * * Actions are the hooks that the WordPress core launches at specific points * during execution, or when specific events occur. Plugins can specify that * one or more of its PHP functions are executed at these points, using the * Action API. * * @uses add_filter() Adds an action. Parameter list and functionality are the same. * * @package WordPress * @subpackage Plugin * @since 1.2 * * @param string $tag The name of the action to which the $function_to_add is hooked. * @param callback $function_to_add The name of the function you wish to be called. * @param int $priority optional. Used to specify the order in which the functions associated with a particular action are executed (default: 10). Lower numbers correspond with earlier execution, and functions with the same priority are executed in the order in which they were added to the action. * @param int $accepted_args optional. The number of arguments the function accept (default 1). */ function add_action($tag, $function_to_add, $priority = 10, $accepted_args = 1) { return add_filter($tag, $function_to_add, $priority, $accepted_args); } /** * Execute functions hooked on a specific action hook. * * This function invokes all functions attached to action hook $tag. It is * possible to create new action hooks by simply calling this function, * specifying the name of the new hook using the <tt>$tag</tt> parameter. * * You can pass extra arguments to the hooks, much like you can with * apply_filters(). * * @see apply_filters() This function works similar with the exception that * nothing is returned and only the functions or methods are called. * * @package WordPress * @subpackage Plugin * @since 1.2 * @global array $wp_filter Stores all of the filters * @global array $wp_actions Increments the amount of times action was triggered. * * @param string $tag The name of the action to be executed. * @param mixed $arg,... Optional additional arguments which are passed on to the functions hooked to the action. * @return null Will return null if $tag does not exist in $wp_filter array */ function do_action($tag, $arg = '') { global $wp_filter, $wp_actions, $merged_filters, $wp_current_filter; if ( ! isset($wp_actions) ) $wp_actions = array(); if ( ! isset($wp_actions[$tag]) ) $wp_actions[$tag] = 1; else ++$wp_actions[$tag]; // Do 'all' actions first if ( isset($wp_filter['all']) ) { $wp_current_filter[] = $tag; $all_args = func_get_args(); _wp_call_all_hook($all_args); } if ( !isset($wp_filter[$tag]) ) { if ( isset($wp_filter['all']) ) array_pop($wp_current_filter); return; } if ( !isset($wp_filter['all']) ) $wp_current_filter[] = $tag; $args = array(); if ( is_array($arg) && 1 == count($arg) && isset($arg[0]) && is_object($arg[0]) ) // array(&$this) $args[] =& $arg[0]; else $args[] = $arg; for ( $a = 2; $a < func_num_args(); $a++ ) $args[] = func_get_arg($a); // Sort if ( !isset( $merged_filters[ $tag ] ) ) { ksort($wp_filter[$tag]); $merged_filters[ $tag ] = true; } reset( $wp_filter[ $tag ] ); do { foreach ( (array) current($wp_filter[$tag]) as $the_ ) if ( !is_null($the_['function']) ) call_user_func_array($the_['function'], array_slice($args, 0, (int) $the_['accepted_args'])); } while ( next($wp_filter[$tag]) !== false ); array_pop($wp_current_filter); } /** * Retrieve the number of times an action is fired. * * @package WordPress * @subpackage Plugin * @since 2.1 * @global array $wp_actions Increments the amount of times action was triggered. * * @param string $tag The name of the action hook. * @return int The number of times action hook <tt>$tag</tt> is fired */ function did_action($tag) { global $wp_actions; if ( ! isset( $wp_actions ) || ! isset( $wp_actions[$tag] ) ) return 0; return $wp_actions[$tag]; } /** * Execute functions hooked on a specific action hook, specifying arguments in an array. * * @see do_action() This function is identical, but the arguments passed to the * functions hooked to <tt>$tag</tt> are supplied using an array. * * @package WordPress * @subpackage Plugin * @since 2.1 * @global array $wp_filter Stores all of the filters * @global array $wp_actions Increments the amount of times action was triggered. * * @param string $tag The name of the action to be executed. * @param array $args The arguments supplied to the functions hooked to <tt>$tag</tt> * @return null Will return null if $tag does not exist in $wp_filter array */ function do_action_ref_array($tag, $args) { global $wp_filter, $wp_actions, $merged_filters, $wp_current_filter; if ( ! isset($wp_actions) ) $wp_actions = array(); if ( ! isset($wp_actions[$tag]) ) $wp_actions[$tag] = 1; else ++$wp_actions[$tag]; // Do 'all' actions first if ( isset($wp_filter['all']) ) { $wp_current_filter[] = $tag; $all_args = func_get_args(); _wp_call_all_hook($all_args); } if ( !isset($wp_filter[$tag]) ) { if ( isset($wp_filter['all']) ) array_pop($wp_current_filter); return; } if ( !isset($wp_filter['all']) ) $wp_current_filter[] = $tag; // Sort if ( !isset( $merged_filters[ $tag ] ) ) { ksort($wp_filter[$tag]); $merged_filters[ $tag ] = true; } reset( $wp_filter[ $tag ] ); do { foreach( (array) current($wp_filter[$tag]) as $the_ ) if ( !is_null($the_['function']) ) call_user_func_array($the_['function'], array_slice($args, 0, (int) $the_['accepted_args'])); } while ( next($wp_filter[$tag]) !== false ); array_pop($wp_current_filter); } /** * Check if any action has been registered for a hook. * * @package WordPress * @subpackage Plugin * @since 2.5 * @see has_filter() has_action() is an alias of has_filter(). * * @param string $tag The name of the action hook. * @param callback $function_to_check optional. * @return mixed If $function_to_check is omitted, returns boolean for whether the hook has anything registered. * When checking a specific function, the priority of that hook is returned, or false if the function is not attached. * When using the $function_to_check argument, this function may return a non-boolean value that evaluates to false * (e.g.) 0, so use the === operator for testing the return value. */ function has_action($tag, $function_to_check = false) { return has_filter($tag, $function_to_check); } /** * Removes a function from a specified action hook. * * This function removes a function attached to a specified action hook. This * method can be used to remove default functions attached to a specific filter * hook and possibly replace them with a substitute. * * @package WordPress * @subpackage Plugin * @since 1.2 * * @param string $tag The action hook to which the function to be removed is hooked. * @param callback $function_to_remove The name of the function which should be removed. * @param int $priority optional The priority of the function (default: 10). * @return boolean Whether the function is removed. */ function remove_action( $tag, $function_to_remove, $priority = 10 ) { return remove_filter( $tag, $function_to_remove, $priority ); } /** * Remove all of the hooks from an action. * * @since 2.7 * * @param string $tag The action to remove hooks from. * @param int $priority The priority number to remove them from. * @return bool True when finished. */ function remove_all_actions($tag, $priority = false) { return remove_all_filters($tag, $priority); } // // Functions for handling plugins. // /** * Gets the basename of a plugin. * * This method extracts the name of a plugin from its filename. * * @package WordPress * @subpackage Plugin * @since 1.5 * * @access private * * @param string $file The filename of plugin. * @return string The name of a plugin. * @uses WP_PLUGIN_DIR */ function plugin_basename($file) { $file = str_replace('\\','/',$file); // sanitize for Win32 installs $file = preg_replace('|/+|','/', $file); // remove any duplicate slash $plugin_dir = str_replace('\\','/',WP_PLUGIN_DIR); // sanitize for Win32 installs $plugin_dir = preg_replace('|/+|','/', $plugin_dir); // remove any duplicate slash $mu_plugin_dir = str_replace('\\','/',WPMU_PLUGIN_DIR); // sanitize for Win32 installs $mu_plugin_dir = preg_replace('|/+|','/', $mu_plugin_dir); // remove any duplicate slash $file = preg_replace('#^' . preg_quote($plugin_dir, '#') . '/|^' . preg_quote($mu_plugin_dir, '#') . '/#','',$file); // get relative path from plugins dir $file = trim($file, '/'); return $file; } /** * Gets the filesystem directory path (with trailing slash) for the plugin __FILE__ passed in * @package WordPress * @subpackage Plugin * @since 2.8 * * @param string $file The filename of the plugin (__FILE__) * @return string the filesystem path of the directory that contains the plugin */ function plugin_dir_path( $file ) { return trailingslashit( dirname( $file ) ); } /** * Gets the URL directory path (with trailing slash) for the plugin __FILE__ passed in * @package WordPress * @subpackage Plugin * @since 2.8 * * @param string $file The filename of the plugin (__FILE__) * @return string the URL path of the directory that contains the plugin */ function plugin_dir_url( $file ) { return trailingslashit( plugins_url( '', $file ) ); } /** * Set the activation hook for a plugin. * * When a plugin is activated, the action 'activate_PLUGINNAME' hook is * activated. In the name of this hook, PLUGINNAME is replaced with the name of * the plugin, including the optional subdirectory. For example, when the plugin * is located in wp-content/plugin/sampleplugin/sample.php, then the name of * this hook will become 'activate_sampleplugin/sample.php'. When the plugin * consists of only one file and is (as by default) located at * wp-content/plugin/sample.php the name of this hook will be * 'activate_sample.php'. * * @package WordPress * @subpackage Plugin * @since 2.0 * * @param string $file The filename of the plugin including the path. * @param callback $function the function hooked to the 'activate_PLUGIN' action. */ function register_activation_hook($file, $function) { $file = plugin_basename($file); add_action('activate_' . $file, $function); } /** * Set the deactivation hook for a plugin. * * When a plugin is deactivated, the action 'deactivate_PLUGINNAME' hook is * deactivated. In the name of this hook, PLUGINNAME is replaced with the name * of the plugin, including the optional subdirectory. For example, when the * plugin is located in wp-content/plugin/sampleplugin/sample.php, then * the name of this hook will become 'activate_sampleplugin/sample.php'. * * When the plugin consists of only one file and is (as by default) located at * wp-content/plugin/sample.php the name of this hook will be * 'activate_sample.php'. * * @package WordPress * @subpackage Plugin * @since 2.0 * * @param string $file The filename of the plugin including the path. * @param callback $function the function hooked to the 'activate_PLUGIN' action. */ function register_deactivation_hook($file, $function) { $file = plugin_basename($file); add_action('deactivate_' . $file, $function); } /** * Set the uninstallation hook for a plugin. * * Registers the uninstall hook that will be called when the user clicks on the * uninstall link that calls for the plugin to uninstall itself. The link won't * be active unless the plugin hooks into the action. * * The plugin should not run arbitrary code outside of functions, when * registering the uninstall hook. In order to run using the hook, the plugin * will have to be included, which means that any code laying outside of a * function will be run during the uninstall process. The plugin should not * hinder the uninstall process. * * If the plugin can not be written without running code within the plugin, then * the plugin should create a file named 'uninstall.php' in the base plugin * folder. This file will be called, if it exists, during the uninstall process * bypassing the uninstall hook. The plugin, when using the 'uninstall.php' * should always check for the 'WP_UNINSTALL_PLUGIN' constant, before * executing. * * @since 2.7 * * @param string $file * @param callback $callback The callback to run when the hook is called. Must be a static method or function. */ function register_uninstall_hook( $file, $callback ) { if ( is_array( $callback ) && is_object( $callback[0] ) ) { _doing_it_wrong( __FUNCTION__, __( 'Only a static class method or function can be used in an uninstall hook.' ), '3.1' ); return; } // The option should not be autoloaded, because it is not needed in most // cases. Emphasis should be put on using the 'uninstall.php' way of // uninstalling the plugin. $uninstallable_plugins = (array) get_option('uninstall_plugins'); $uninstallable_plugins[plugin_basename($file)] = $callback; update_option('uninstall_plugins', $uninstallable_plugins); } /** * Calls the 'all' hook, which will process the functions hooked into it. * * The 'all' hook passes all of the arguments or parameters that were used for * the hook, which this function was called for. * * This function is used internally for apply_filters(), do_action(), and * do_action_ref_array() and is not meant to be used from outside those * functions. This function does not check for the existence of the all hook, so * it will fail unless the all hook exists prior to this function call. * * @package WordPress * @subpackage Plugin * @since 2.5 * @access private * * @uses $wp_filter Used to process all of the functions in the 'all' hook * * @param array $args The collected parameters from the hook that was called. * @param string $hook Optional. The hook name that was used to call the 'all' hook. */ function _wp_call_all_hook($args) { global $wp_filter; reset( $wp_filter['all'] ); do { foreach( (array) current($wp_filter['all']) as $the_ ) if ( !is_null($the_['function']) ) call_user_func_array($the_['function'], $args); } while ( next($wp_filter['all']) !== false ); } /** * Build Unique ID for storage and retrieval. * * The old way to serialize the callback caused issues and this function is the * solution. It works by checking for objects and creating an a new property in * the class to keep track of the object and new objects of the same class that * need to be added. * * It also allows for the removal of actions and filters for objects after they * change class properties. It is possible to include the property $wp_filter_id * in your class and set it to "null" or a number to bypass the workaround. * However this will prevent you from adding new classes and any new classes * will overwrite the previous hook by the same class. * * Functions and static method callbacks are just returned as strings and * shouldn't have any speed penalty. * * @package WordPress * @subpackage Plugin * @access private * @since 2.2.3 * @link http://trac.wordpress.org/ticket/3875 * * @global array $wp_filter Storage for all of the filters and actions * @param string $tag Used in counting how many hooks were applied * @param callback $function Used for creating unique id * @param int|bool $priority Used in counting how many hooks were applied. If === false and $function is an object reference, we return the unique id only if it already has one, false otherwise. * @return string|bool Unique ID for usage as array key or false if $priority === false and $function is an object reference, and it does not already have a unique id. */ function _wp_filter_build_unique_id($tag, $function, $priority) { global $wp_filter; static $filter_id_count = 0; if ( is_string($function) ) return $function; if ( is_object($function) ) { // Closures are currently implemented as objects $function = array( $function, '' ); } else { $function = (array) $function; } if (is_object($function[0]) ) { // Object Class Calling if ( function_exists('spl_object_hash') ) { return spl_object_hash($function[0]) . $function[1]; } else { $obj_idx = get_class($function[0]).$function[1]; if ( !isset($function[0]->wp_filter_id) ) { if ( false === $priority ) return false; $obj_idx .= isset($wp_filter[$tag][$priority]) ? count((array)$wp_filter[$tag][$priority]) : $filter_id_count; $function[0]->wp_filter_id = $filter_id_count; ++$filter_id_count; } else { $obj_idx .= $function[0]->wp_filter_id; } return $obj_idx; } } else if ( is_string($function[0]) ) { // Static Calling return $function[0].$function[1]; } }
zyblog
trunk/zyblog/wp-includes/plugin.php
PHP
asf20
27,592
<?php /** * Category Template Tags and API. * * @package WordPress * @subpackage Template */ /** * Retrieve category link URL. * * @since 1.0.0 * @see get_term_link() * * @param int|object $category Category ID or object. * @return string Link on success, empty string if category does not exist. */ function get_category_link( $category ) { if ( ! is_object( $category ) ) $category = (int) $category; $category = get_term_link( $category, 'category' ); if ( is_wp_error( $category ) ) return ''; return $category; } /** * Retrieve category parents with separator. * * @since 1.2.0 * * @param int $id Category ID. * @param bool $link Optional, default is false. Whether to format with link. * @param string $separator Optional, default is '/'. How to separate categories. * @param bool $nicename Optional, default is false. Whether to use nice name for display. * @param array $visited Optional. Already linked to categories to prevent duplicates. * @return string */ function get_category_parents( $id, $link = false, $separator = '/', $nicename = false, $visited = array() ) { $chain = ''; $parent = get_category( $id ); if ( is_wp_error( $parent ) ) return $parent; if ( $nicename ) $name = $parent->slug; else $name = $parent->name; if ( $parent->parent && ( $parent->parent != $parent->term_id ) && !in_array( $parent->parent, $visited ) ) { $visited[] = $parent->parent; $chain .= get_category_parents( $parent->parent, $link, $separator, $nicename, $visited ); } if ( $link ) $chain .= '<a href="' . esc_url( get_category_link( $parent->term_id ) ) . '" title="' . esc_attr( sprintf( __( "View all posts in %s" ), $parent->name ) ) . '">'.$name.'</a>' . $separator; else $chain .= $name.$separator; return $chain; } /** * Retrieve post categories. * * @since 0.71 * @uses $post * * @param int $id Optional, default to current post ID. The post ID. * @return array */ function get_the_category( $id = false ) { $categories = get_the_terms( $id, 'category' ); if ( ! $categories || is_wp_error( $categories ) ) $categories = array(); $categories = array_values( $categories ); foreach ( array_keys( $categories ) as $key ) { _make_cat_compat( $categories[$key] ); } // Filter name is plural because we return alot of categories (possibly more than #13237) not just one return apply_filters( 'get_the_categories', $categories ); } /** * Sort categories by name. * * Used by usort() as a callback, should not be used directly. Can actually be * used to sort any term object. * * @since 2.3.0 * @access private * * @param object $a * @param object $b * @return int */ function _usort_terms_by_name( $a, $b ) { return strcmp( $a->name, $b->name ); } /** * Sort categories by ID. * * Used by usort() as a callback, should not be used directly. Can actually be * used to sort any term object. * * @since 2.3.0 * @access private * * @param object $a * @param object $b * @return int */ function _usort_terms_by_ID( $a, $b ) { if ( $a->term_id > $b->term_id ) return 1; elseif ( $a->term_id < $b->term_id ) return -1; else return 0; } /** * Retrieve category name based on category ID. * * @since 0.71 * * @param int $cat_ID Category ID. * @return string Category name. */ function get_the_category_by_ID( $cat_ID ) { $cat_ID = (int) $cat_ID; $category = get_category( $cat_ID ); if ( is_wp_error( $category ) ) return $category; return $category->name; } /** * Retrieve category list in either HTML list or custom format. * * @since 1.5.1 * * @param string $separator Optional, default is empty string. Separator for between the categories. * @param string $parents Optional. How to display the parents. * @param int $post_id Optional. Post ID to retrieve categories. * @return string */ function get_the_category_list( $separator = '', $parents='', $post_id = false ) { global $wp_rewrite; if ( ! is_object_in_taxonomy( get_post_type( $post_id ), 'category' ) ) return apply_filters( 'the_category', '', $separator, $parents ); $categories = get_the_category( $post_id ); if ( empty( $categories ) ) return apply_filters( 'the_category', __( 'Uncategorized' ), $separator, $parents ); $rel = ( is_object( $wp_rewrite ) && $wp_rewrite->using_permalinks() ) ? 'rel="category tag"' : 'rel="category"'; $thelist = ''; if ( '' == $separator ) { $thelist .= '<ul class="post-categories">'; foreach ( $categories as $category ) { $thelist .= "\n\t<li>"; switch ( strtolower( $parents ) ) { case 'multiple': if ( $category->parent ) $thelist .= get_category_parents( $category->parent, true, $separator ); $thelist .= '<a href="' . esc_url( get_category_link( $category->term_id ) ) . '" title="' . esc_attr( sprintf( __( "View all posts in %s" ), $category->name ) ) . '" ' . $rel . '>' . $category->name.'</a></li>'; break; case 'single': $thelist .= '<a href="' . esc_url( get_category_link( $category->term_id ) ) . '" title="' . esc_attr( sprintf( __( "View all posts in %s" ), $category->name ) ) . '" ' . $rel . '>'; if ( $category->parent ) $thelist .= get_category_parents( $category->parent, false, $separator ); $thelist .= $category->name.'</a></li>'; break; case '': default: $thelist .= '<a href="' . esc_url( get_category_link( $category->term_id ) ) . '" title="' . esc_attr( sprintf( __( "View all posts in %s" ), $category->name ) ) . '" ' . $rel . '>' . $category->name.'</a></li>'; } } $thelist .= '</ul>'; } else { $i = 0; foreach ( $categories as $category ) { if ( 0 < $i ) $thelist .= $separator; switch ( strtolower( $parents ) ) { case 'multiple': if ( $category->parent ) $thelist .= get_category_parents( $category->parent, true, $separator ); $thelist .= '<a href="' . esc_url( get_category_link( $category->term_id ) ) . '" title="' . esc_attr( sprintf( __( "View all posts in %s" ), $category->name ) ) . '" ' . $rel . '>' . $category->name.'</a>'; break; case 'single': $thelist .= '<a href="' . esc_url( get_category_link( $category->term_id ) ) . '" title="' . esc_attr( sprintf( __( "View all posts in %s" ), $category->name ) ) . '" ' . $rel . '>'; if ( $category->parent ) $thelist .= get_category_parents( $category->parent, false, $separator ); $thelist .= "$category->name</a>"; break; case '': default: $thelist .= '<a href="' . esc_url( get_category_link( $category->term_id ) ) . '" title="' . esc_attr( sprintf( __( "View all posts in %s" ), $category->name ) ) . '" ' . $rel . '>' . $category->name.'</a>'; } ++$i; } } return apply_filters( 'the_category', $thelist, $separator, $parents ); } /** * Check if the current post in within any of the given categories. * * The given categories are checked against the post's categories' term_ids, names and slugs. * Categories given as integers will only be checked against the post's categories' term_ids. * * Prior to v2.5 of WordPress, category names were not supported. * Prior to v2.7, category slugs were not supported. * Prior to v2.7, only one category could be compared: in_category( $single_category ). * Prior to v2.7, this function could only be used in the WordPress Loop. * As of 2.7, the function can be used anywhere if it is provided a post ID or post object. * * @since 1.2.0 * * @param int|string|array $category Category ID, name or slug, or array of said. * @param int|object $post Optional. Post to check instead of the current post. (since 2.7.0) * @return bool True if the current post is in any of the given categories. */ function in_category( $category, $post = null ) { if ( empty( $category ) ) return false; return has_term( $category, 'category', $post ); } /** * Display the category list for the post. * * @since 0.71 * * @param string $separator Optional, default is empty string. Separator for between the categories. * @param string $parents Optional. How to display the parents. * @param int $post_id Optional. Post ID to retrieve categories. */ function the_category( $separator = '', $parents='', $post_id = false ) { echo get_the_category_list( $separator, $parents, $post_id ); } /** * Retrieve category description. * * @since 1.0.0 * * @param int $category Optional. Category ID. Will use global category ID by default. * @return string Category description, available. */ function category_description( $category = 0 ) { return term_description( $category, 'category' ); } /** * Display or retrieve the HTML dropdown list of categories. * * The list of arguments is below: * 'show_option_all' (string) - Text to display for showing all categories. * 'show_option_none' (string) - Text to display for showing no categories. * 'orderby' (string) default is 'ID' - What column to use for ordering the * categories. * 'order' (string) default is 'ASC' - What direction to order categories. * 'show_count' (bool|int) default is 0 - Whether to show how many posts are * in the category. * 'hide_empty' (bool|int) default is 1 - Whether to hide categories that * don't have any posts attached to them. * 'child_of' (int) default is 0 - See {@link get_categories()}. * 'exclude' (string) - See {@link get_categories()}. * 'echo' (bool|int) default is 1 - Whether to display or retrieve content. * 'depth' (int) - The max depth. * 'tab_index' (int) - Tab index for select element. * 'name' (string) - The name attribute value for select element. * 'id' (string) - The ID attribute value for select element. Defaults to name if omitted. * 'class' (string) - The class attribute value for select element. * 'selected' (int) - Which category ID is selected. * 'taxonomy' (string) - The name of the taxonomy to retrieve. Defaults to category. * * The 'hierarchical' argument, which is disabled by default, will override the * depth argument, unless it is true. When the argument is false, it will * display all of the categories. When it is enabled it will use the value in * the 'depth' argument. * * @since 2.1.0 * * @param string|array $args Optional. Override default arguments. * @return string HTML content only if 'echo' argument is 0. */ function wp_dropdown_categories( $args = '' ) { $defaults = array( 'show_option_all' => '', 'show_option_none' => '', 'orderby' => 'id', 'order' => 'ASC', 'show_count' => 0, 'hide_empty' => 1, 'child_of' => 0, 'exclude' => '', 'echo' => 1, 'selected' => 0, 'hierarchical' => 0, 'name' => 'cat', 'id' => '', 'class' => 'postform', 'depth' => 0, 'tab_index' => 0, 'taxonomy' => 'category', 'hide_if_empty' => false ); $defaults['selected'] = ( is_category() ) ? get_query_var( 'cat' ) : 0; // Back compat. if ( isset( $args['type'] ) && 'link' == $args['type'] ) { _deprecated_argument( __FUNCTION__, '3.0', '' ); $args['taxonomy'] = 'link_category'; } $r = wp_parse_args( $args, $defaults ); if ( !isset( $r['pad_counts'] ) && $r['show_count'] && $r['hierarchical'] ) { $r['pad_counts'] = true; } extract( $r ); $tab_index_attribute = ''; if ( (int) $tab_index > 0 ) $tab_index_attribute = " tabindex=\"$tab_index\""; $categories = get_terms( $taxonomy, $r ); $name = esc_attr( $name ); $class = esc_attr( $class ); $id = $id ? esc_attr( $id ) : $name; if ( ! $r['hide_if_empty'] || ! empty($categories) ) $output = "<select name='$name' id='$id' class='$class' $tab_index_attribute>\n"; else $output = ''; if ( empty($categories) && ! $r['hide_if_empty'] && !empty($show_option_none) ) { $show_option_none = apply_filters( 'list_cats', $show_option_none ); $output .= "\t<option value='-1' selected='selected'>$show_option_none</option>\n"; } if ( ! empty( $categories ) ) { if ( $show_option_all ) { $show_option_all = apply_filters( 'list_cats', $show_option_all ); $selected = ( '0' === strval($r['selected']) ) ? " selected='selected'" : ''; $output .= "\t<option value='0'$selected>$show_option_all</option>\n"; } if ( $show_option_none ) { $show_option_none = apply_filters( 'list_cats', $show_option_none ); $selected = ( '-1' === strval($r['selected']) ) ? " selected='selected'" : ''; $output .= "\t<option value='-1'$selected>$show_option_none</option>\n"; } if ( $hierarchical ) $depth = $r['depth']; // Walk the full depth. else $depth = -1; // Flat. $output .= walk_category_dropdown_tree( $categories, $depth, $r ); } if ( ! $r['hide_if_empty'] || ! empty($categories) ) $output .= "</select>\n"; $output = apply_filters( 'wp_dropdown_cats', $output ); if ( $echo ) echo $output; return $output; } /** * Display or retrieve the HTML list of categories. * * The list of arguments is below: * 'show_option_all' (string) - Text to display for showing all categories. * 'orderby' (string) default is 'ID' - What column to use for ordering the * categories. * 'order' (string) default is 'ASC' - What direction to order categories. * 'show_count' (bool|int) default is 0 - Whether to show how many posts are * in the category. * 'hide_empty' (bool|int) default is 1 - Whether to hide categories that * don't have any posts attached to them. * 'use_desc_for_title' (bool|int) default is 1 - Whether to use the * description instead of the category title. * 'feed' - See {@link get_categories()}. * 'feed_type' - See {@link get_categories()}. * 'feed_image' - See {@link get_categories()}. * 'child_of' (int) default is 0 - See {@link get_categories()}. * 'exclude' (string) - See {@link get_categories()}. * 'exclude_tree' (string) - See {@link get_categories()}. * 'echo' (bool|int) default is 1 - Whether to display or retrieve content. * 'current_category' (int) - See {@link get_categories()}. * 'hierarchical' (bool) - See {@link get_categories()}. * 'title_li' (string) - See {@link get_categories()}. * 'depth' (int) - The max depth. * * @since 2.1.0 * * @param string|array $args Optional. Override default arguments. * @return string HTML content only if 'echo' argument is 0. */ function wp_list_categories( $args = '' ) { $defaults = array( 'show_option_all' => '', 'show_option_none' => __('No categories'), 'orderby' => 'name', 'order' => 'ASC', 'style' => 'list', 'show_count' => 0, 'hide_empty' => 1, 'use_desc_for_title' => 1, 'child_of' => 0, 'feed' => '', 'feed_type' => '', 'feed_image' => '', 'exclude' => '', 'exclude_tree' => '', 'current_category' => 0, 'hierarchical' => true, 'title_li' => __( 'Categories' ), 'echo' => 1, 'depth' => 0, 'taxonomy' => 'category' ); $r = wp_parse_args( $args, $defaults ); if ( !isset( $r['pad_counts'] ) && $r['show_count'] && $r['hierarchical'] ) $r['pad_counts'] = true; if ( true == $r['hierarchical'] ) { $r['exclude_tree'] = $r['exclude']; $r['exclude'] = ''; } if ( !isset( $r['class'] ) ) $r['class'] = ( 'category' == $r['taxonomy'] ) ? 'categories' : $r['taxonomy']; extract( $r ); if ( !taxonomy_exists($taxonomy) ) return false; $categories = get_categories( $r ); $output = ''; if ( $title_li && 'list' == $style ) $output = '<li class="' . esc_attr( $class ) . '">' . $title_li . '<ul>'; if ( empty( $categories ) ) { if ( ! empty( $show_option_none ) ) { if ( 'list' == $style ) $output .= '<li>' . $show_option_none . '</li>'; else $output .= $show_option_none; } } else { if ( ! empty( $show_option_all ) ) { $posts_page = ( 'page' == get_option( 'show_on_front' ) && get_option( 'page_for_posts' ) ) ? get_permalink( get_option( 'page_for_posts' ) ) : home_url( '/' ); $posts_page = esc_url( $posts_page ); if ( 'list' == $style ) $output .= "<li><a href='$posts_page'>$show_option_all</a></li>"; else $output .= "<a href='$posts_page'>$show_option_all</a>"; } if ( empty( $r['current_category'] ) && ( is_category() || is_tax() || is_tag() ) ) { $current_term_object = get_queried_object(); if ( $r['taxonomy'] == $current_term_object->taxonomy ) $r['current_category'] = get_queried_object_id(); } if ( $hierarchical ) $depth = $r['depth']; else $depth = -1; // Flat. $output .= walk_category_tree( $categories, $depth, $r ); } if ( $title_li && 'list' == $style ) $output .= '</ul></li>'; $output = apply_filters( 'wp_list_categories', $output, $args ); if ( $echo ) echo $output; else return $output; } /** * Display tag cloud. * * The text size is set by the 'smallest' and 'largest' arguments, which will * use the 'unit' argument value for the CSS text size unit. The 'format' * argument can be 'flat' (default), 'list', or 'array'. The flat value for the * 'format' argument will separate tags with spaces. The list value for the * 'format' argument will format the tags in a UL HTML list. The array value for * the 'format' argument will return in PHP array type format. * * The 'orderby' argument will accept 'name' or 'count' and defaults to 'name'. * The 'order' is the direction to sort, defaults to 'ASC' and can be 'DESC'. * * The 'number' argument is how many tags to return. By default, the limit will * be to return the top 45 tags in the tag cloud list. * * The 'topic_count_text_callback' argument is a function, which, given the count * of the posts with that tag, returns a text for the tooltip of the tag link. * * The 'exclude' and 'include' arguments are used for the {@link get_tags()} * function. Only one should be used, because only one will be used and the * other ignored, if they are both set. * * @since 2.3.0 * * @param array|string $args Optional. Override default arguments. * @return array Generated tag cloud, only if no failures and 'array' is set for the 'format' argument. */ function wp_tag_cloud( $args = '' ) { $defaults = array( 'smallest' => 8, 'largest' => 22, 'unit' => 'pt', 'number' => 45, 'format' => 'flat', 'separator' => "\n", 'orderby' => 'name', 'order' => 'ASC', 'exclude' => '', 'include' => '', 'link' => 'view', 'taxonomy' => 'post_tag', 'echo' => true ); $args = wp_parse_args( $args, $defaults ); $tags = get_terms( $args['taxonomy'], array_merge( $args, array( 'orderby' => 'count', 'order' => 'DESC' ) ) ); // Always query top tags if ( empty( $tags ) || is_wp_error( $tags ) ) return; foreach ( $tags as $key => $tag ) { if ( 'edit' == $args['link'] ) $link = get_edit_tag_link( $tag->term_id, $tag->taxonomy ); else $link = get_term_link( intval($tag->term_id), $tag->taxonomy ); if ( is_wp_error( $link ) ) return false; $tags[ $key ]->link = $link; $tags[ $key ]->id = $tag->term_id; } $return = wp_generate_tag_cloud( $tags, $args ); // Here's where those top tags get sorted according to $args $return = apply_filters( 'wp_tag_cloud', $return, $args ); if ( 'array' == $args['format'] || empty($args['echo']) ) return $return; echo $return; } /** * Default text for tooltip for tag links * * @param integer $count number of posts with that tag * @return string text for the tooltip of a tag link. */ function default_topic_count_text( $count ) { return sprintf( _n('%s topic', '%s topics', $count), number_format_i18n( $count ) ); } /** * Default topic count scaling for tag links * * @param integer $count number of posts with that tag * @return integer scaled count */ function default_topic_count_scale( $count ) { return round(log10($count + 1) * 100); } /** * Generates a tag cloud (heatmap) from provided data. * * The text size is set by the 'smallest' and 'largest' arguments, which will * use the 'unit' argument value for the CSS text size unit. The 'format' * argument can be 'flat' (default), 'list', or 'array'. The flat value for the * 'format' argument will separate tags with spaces. The list value for the * 'format' argument will format the tags in a UL HTML list. The array value for * the 'format' argument will return in PHP array type format. * * The 'tag_cloud_sort' filter allows you to override the sorting. * Passed to the filter: $tags array and $args array, has to return the $tags array * after sorting it. * * The 'orderby' argument will accept 'name' or 'count' and defaults to 'name'. * The 'order' is the direction to sort, defaults to 'ASC' and can be 'DESC' or * 'RAND'. * * The 'number' argument is how many tags to return. By default, the limit will * be to return the entire tag cloud list. * * The 'topic_count_text_callback' argument is a function, which given the count * of the posts with that tag returns a text for the tooltip of the tag link. * * @todo Complete functionality. * @since 2.3.0 * * @param array $tags List of tags. * @param string|array $args Optional, override default arguments. * @return string */ function wp_generate_tag_cloud( $tags, $args = '' ) { $defaults = array( 'smallest' => 8, 'largest' => 22, 'unit' => 'pt', 'number' => 0, 'format' => 'flat', 'separator' => "\n", 'orderby' => 'name', 'order' => 'ASC', 'topic_count_text_callback' => 'default_topic_count_text', 'topic_count_scale_callback' => 'default_topic_count_scale', 'filter' => 1, ); if ( !isset( $args['topic_count_text_callback'] ) && isset( $args['single_text'] ) && isset( $args['multiple_text'] ) ) { $body = 'return sprintf ( _n(' . var_export($args['single_text'], true) . ', ' . var_export($args['multiple_text'], true) . ', $count), number_format_i18n( $count ));'; $args['topic_count_text_callback'] = create_function('$count', $body); } $args = wp_parse_args( $args, $defaults ); extract( $args ); if ( empty( $tags ) ) return; $tags_sorted = apply_filters( 'tag_cloud_sort', $tags, $args ); if ( $tags_sorted != $tags ) { // the tags have been sorted by a plugin $tags = $tags_sorted; unset($tags_sorted); } else { if ( 'RAND' == $order ) { shuffle($tags); } else { // SQL cannot save you; this is a second (potentially different) sort on a subset of data. if ( 'name' == $orderby ) uasort( $tags, '_wp_object_name_sort_cb' ); else uasort( $tags, '_wp_object_count_sort_cb' ); if ( 'DESC' == $order ) $tags = array_reverse( $tags, true ); } } if ( $number > 0 ) $tags = array_slice($tags, 0, $number); $counts = array(); $real_counts = array(); // For the alt tag foreach ( (array) $tags as $key => $tag ) { $real_counts[ $key ] = $tag->count; $counts[ $key ] = $topic_count_scale_callback($tag->count); } $min_count = min( $counts ); $spread = max( $counts ) - $min_count; if ( $spread <= 0 ) $spread = 1; $font_spread = $largest - $smallest; if ( $font_spread < 0 ) $font_spread = 1; $font_step = $font_spread / $spread; $a = array(); foreach ( $tags as $key => $tag ) { $count = $counts[ $key ]; $real_count = $real_counts[ $key ]; $tag_link = '#' != $tag->link ? esc_url( $tag->link ) : '#'; $tag_id = isset($tags[ $key ]->id) ? $tags[ $key ]->id : $key; $tag_name = $tags[ $key ]->name; $a[] = "<a href='$tag_link' class='tag-link-$tag_id' title='" . esc_attr( call_user_func( $topic_count_text_callback, $real_count ) ) . "' style='font-size: " . str_replace( ',', '.', ( $smallest + ( ( $count - $min_count ) * $font_step ) ) ) . "$unit;'>$tag_name</a>"; } switch ( $format ) : case 'array' : $return =& $a; break; case 'list' : $return = "<ul class='wp-tag-cloud'>\n\t<li>"; $return .= join( "</li>\n\t<li>", $a ); $return .= "</li>\n</ul>\n"; break; default : $return = join( $separator, $a ); break; endswitch; if ( $filter ) return apply_filters( 'wp_generate_tag_cloud', $return, $tags, $args ); else return $return; } /** * Callback for comparing objects based on name * * @since 3.1.0 * @access private */ function _wp_object_name_sort_cb( $a, $b ) { return strnatcasecmp( $a->name, $b->name ); } /** * Callback for comparing objects based on count * * @since 3.1.0 * @access private */ function _wp_object_count_sort_cb( $a, $b ) { return ( $a->count > $b->count ); } // // Helper functions // /** * Retrieve HTML list content for category list. * * @uses Walker_Category to create HTML list content. * @since 2.1.0 * @see Walker_Category::walk() for parameters and return description. */ function walk_category_tree() { $args = func_get_args(); // the user's options are the third parameter if ( empty($args[2]['walker']) || !is_a($args[2]['walker'], 'Walker') ) $walker = new Walker_Category; else $walker = $args[2]['walker']; return call_user_func_array(array( &$walker, 'walk' ), $args ); } /** * Retrieve HTML dropdown (select) content for category list. * * @uses Walker_CategoryDropdown to create HTML dropdown content. * @since 2.1.0 * @see Walker_CategoryDropdown::walk() for parameters and return description. */ function walk_category_dropdown_tree() { $args = func_get_args(); // the user's options are the third parameter if ( empty($args[2]['walker']) || !is_a($args[2]['walker'], 'Walker') ) $walker = new Walker_CategoryDropdown; else $walker = $args[2]['walker']; return call_user_func_array(array( &$walker, 'walk' ), $args ); } /** * Create HTML list of categories. * * @package WordPress * @since 2.1.0 * @uses Walker */ class Walker_Category extends Walker { /** * @see Walker::$tree_type * @since 2.1.0 * @var string */ var $tree_type = 'category'; /** * @see Walker::$db_fields * @since 2.1.0 * @todo Decouple this * @var array */ var $db_fields = array ('parent' => 'parent', 'id' => 'term_id'); /** * @see Walker::start_lvl() * @since 2.1.0 * * @param string $output Passed by reference. Used to append additional content. * @param int $depth Depth of category. Used for tab indentation. * @param array $args Will only append content if style argument value is 'list'. */ function start_lvl( &$output, $depth = 0, $args = array() ) { if ( 'list' != $args['style'] ) return; $indent = str_repeat("\t", $depth); $output .= "$indent<ul class='children'>\n"; } /** * @see Walker::end_lvl() * @since 2.1.0 * * @param string $output Passed by reference. Used to append additional content. * @param int $depth Depth of category. Used for tab indentation. * @param array $args Will only append content if style argument value is 'list'. */ function end_lvl( &$output, $depth = 0, $args = array() ) { if ( 'list' != $args['style'] ) return; $indent = str_repeat("\t", $depth); $output .= "$indent</ul>\n"; } /** * @see Walker::start_el() * @since 2.1.0 * * @param string $output Passed by reference. Used to append additional content. * @param object $category Category data object. * @param int $depth Depth of category in reference to parents. * @param array $args */ function start_el( &$output, $category, $depth = 0, $args = array(), $id = 0 ) { extract($args); $cat_name = esc_attr( $category->name ); $cat_name = apply_filters( 'list_cats', $cat_name, $category ); $link = '<a href="' . esc_url( get_term_link($category) ) . '" '; if ( $use_desc_for_title == 0 || empty($category->description) ) $link .= 'title="' . esc_attr( sprintf(__( 'View all posts filed under %s' ), $cat_name) ) . '"'; else $link .= 'title="' . esc_attr( strip_tags( apply_filters( 'category_description', $category->description, $category ) ) ) . '"'; $link .= '>'; $link .= $cat_name . '</a>'; if ( !empty($feed_image) || !empty($feed) ) { $link .= ' '; if ( empty($feed_image) ) $link .= '('; $link .= '<a href="' . esc_url( get_term_feed_link( $category->term_id, $category->taxonomy, $feed_type ) ) . '"'; if ( empty($feed) ) { $alt = ' alt="' . sprintf(__( 'Feed for all posts filed under %s' ), $cat_name ) . '"'; } else { $title = ' title="' . $feed . '"'; $alt = ' alt="' . $feed . '"'; $name = $feed; $link .= $title; } $link .= '>'; if ( empty($feed_image) ) $link .= $name; else $link .= "<img src='$feed_image'$alt$title" . ' />'; $link .= '</a>'; if ( empty($feed_image) ) $link .= ')'; } if ( !empty($show_count) ) $link .= ' (' . intval($category->count) . ')'; if ( 'list' == $args['style'] ) { $output .= "\t<li"; $class = 'cat-item cat-item-' . $category->term_id; if ( !empty($current_category) ) { $_current_category = get_term( $current_category, $category->taxonomy ); if ( $category->term_id == $current_category ) $class .= ' current-cat'; elseif ( $category->term_id == $_current_category->parent ) $class .= ' current-cat-parent'; } $output .= ' class="' . $class . '"'; $output .= ">$link\n"; } else { $output .= "\t$link<br />\n"; } } /** * @see Walker::end_el() * @since 2.1.0 * * @param string $output Passed by reference. Used to append additional content. * @param object $page Not used. * @param int $depth Depth of category. Not used. * @param array $args Only uses 'list' for whether should append to output. */ function end_el( &$output, $page, $depth = 0, $args = array() ) { if ( 'list' != $args['style'] ) return; $output .= "</li>\n"; } } /** * Create HTML dropdown list of Categories. * * @package WordPress * @since 2.1.0 * @uses Walker */ class Walker_CategoryDropdown extends Walker { /** * @see Walker::$tree_type * @since 2.1.0 * @var string */ var $tree_type = 'category'; /** * @see Walker::$db_fields * @since 2.1.0 * @todo Decouple this * @var array */ var $db_fields = array ('parent' => 'parent', 'id' => 'term_id'); /** * @see Walker::start_el() * @since 2.1.0 * * @param string $output Passed by reference. Used to append additional content. * @param object $category Category data object. * @param int $depth Depth of category. Used for padding. * @param array $args Uses 'selected' and 'show_count' keys, if they exist. */ function start_el( &$output, $category, $depth, $args, $id = 0 ) { $pad = str_repeat('&nbsp;', $depth * 3); $cat_name = apply_filters('list_cats', $category->name, $category); $output .= "\t<option class=\"level-$depth\" value=\"".$category->term_id."\""; if ( $category->term_id == $args['selected'] ) $output .= ' selected="selected"'; $output .= '>'; $output .= $pad.$cat_name; if ( $args['show_count'] ) $output .= '&nbsp;&nbsp;('. $category->count .')'; $output .= "</option>\n"; } } // // Tags // /** * Retrieve the link to the tag. * * @since 2.3.0 * @see get_term_link() * * @param int|object $tag Tag ID or object. * @return string Link on success, empty string if tag does not exist. */ function get_tag_link( $tag ) { if ( ! is_object( $tag ) ) $tag = (int) $tag; $tag = get_term_link( $tag, 'post_tag' ); if ( is_wp_error( $tag ) ) return ''; return $tag; } /** * Retrieve the tags for a post. * * @since 2.3.0 * @uses apply_filters() Calls 'get_the_tags' filter on the list of post tags. * * @param int $id Post ID. * @return array */ function get_the_tags( $id = 0 ) { return apply_filters( 'get_the_tags', get_the_terms( $id, 'post_tag' ) ); } /** * Retrieve the tags for a post formatted as a string. * * @since 2.3.0 * @uses apply_filters() Calls 'the_tags' filter on string list of tags. * * @param string $before Optional. Before tags. * @param string $sep Optional. Between tags. * @param string $after Optional. After tags. * @param int $id Optional. Post ID. Defaults to the current post. * @return string */ function get_the_tag_list( $before = '', $sep = '', $after = '', $id = 0 ) { return apply_filters( 'the_tags', get_the_term_list( $id, 'post_tag', $before, $sep, $after ), $before, $sep, $after, $id ); } /** * Retrieve the tags for a post. * * @since 2.3.0 * * @param string $before Optional. Before list. * @param string $sep Optional. Separate items using this. * @param string $after Optional. After list. * @return string */ function the_tags( $before = null, $sep = ', ', $after = '' ) { if ( null === $before ) $before = __('Tags: '); echo get_the_tag_list($before, $sep, $after); } /** * Retrieve tag description. * * @since 2.8 * * @param int $tag Optional. Tag ID. Will use global tag ID by default. * @return string Tag description, available. */ function tag_description( $tag = 0 ) { return term_description( $tag ); } /** * Retrieve term description. * * @since 2.8 * * @param int $term Optional. Term ID. Will use global term ID by default. * @param string $taxonomy Optional taxonomy name. Defaults to 'post_tag'. * @return string Term description, available. */ function term_description( $term = 0, $taxonomy = 'post_tag' ) { if ( !$term && ( is_tax() || is_tag() || is_category() ) ) { $term = get_queried_object(); $taxonomy = $term->taxonomy; $term = $term->term_id; } $description = get_term_field( 'description', $term, $taxonomy ); return is_wp_error( $description ) ? '' : $description; } /** * Retrieve the terms of the taxonomy that are attached to the post. * * @since 2.5.0 * * @param mixed $post Post ID or object. * @param string $taxonomy Taxonomy name. * @return array|bool False on failure. Array of term objects on success. */ function get_the_terms( $post, $taxonomy ) { if ( ! $post = get_post( $post ) ) return false; $terms = get_object_term_cache( $post->ID, $taxonomy ); if ( false === $terms ) { $terms = wp_get_object_terms( $post->ID, $taxonomy ); wp_cache_add($post->ID, $terms, $taxonomy . '_relationships'); } $terms = apply_filters( 'get_the_terms', $terms, $post->ID, $taxonomy ); if ( empty( $terms ) ) return false; return $terms; } /** * Retrieve a post's terms as a list with specified format. * * @since 2.5.0 * * @param int $id Post ID. * @param string $taxonomy Taxonomy name. * @param string $before Optional. Before list. * @param string $sep Optional. Separate items using this. * @param string $after Optional. After list. * @return string */ function get_the_term_list( $id, $taxonomy, $before = '', $sep = '', $after = '' ) { $terms = get_the_terms( $id, $taxonomy ); if ( is_wp_error( $terms ) ) return $terms; if ( empty( $terms ) ) return false; foreach ( $terms as $term ) { $link = get_term_link( $term, $taxonomy ); if ( is_wp_error( $link ) ) return $link; $term_links[] = '<a href="' . esc_url( $link ) . '" rel="tag">' . $term->name . '</a>'; } $term_links = apply_filters( "term_links-$taxonomy", $term_links ); return $before . join( $sep, $term_links ) . $after; } /** * Display the terms in a list. * * @since 2.5.0 * * @param int $id Post ID. * @param string $taxonomy Taxonomy name. * @param string $before Optional. Before list. * @param string $sep Optional. Separate items using this. * @param string $after Optional. After list. * @return null|bool False on WordPress error. Returns null when displaying. */ function the_terms( $id, $taxonomy, $before = '', $sep = ', ', $after = '' ) { $term_list = get_the_term_list( $id, $taxonomy, $before, $sep, $after ); if ( is_wp_error( $term_list ) ) return false; echo apply_filters('the_terms', $term_list, $taxonomy, $before, $sep, $after); } /** * Check if the current post has any of given category. * * @since 3.1.0 * * @param string|int|array $category Optional. The category name/term_id/slug or array of them to check for. * @param int|object $post Optional. Post to check instead of the current post. * @return bool True if the current post has any of the given categories (or any category, if no category specified). */ function has_category( $category = '', $post = null ) { return has_term( $category, 'category', $post ); } /** * Check if the current post has any of given tags. * * The given tags are checked against the post's tags' term_ids, names and slugs. * Tags given as integers will only be checked against the post's tags' term_ids. * If no tags are given, determines if post has any tags. * * Prior to v2.7 of WordPress, tags given as integers would also be checked against the post's tags' names and slugs (in addition to term_ids) * Prior to v2.7, this function could only be used in the WordPress Loop. * As of 2.7, the function can be used anywhere if it is provided a post ID or post object. * * @since 2.6.0 * * @param string|int|array $tag Optional. The tag name/term_id/slug or array of them to check for. * @param int|object $post Optional. Post to check instead of the current post. (since 2.7.0) * @return bool True if the current post has any of the given tags (or any tag, if no tag specified). */ function has_tag( $tag = '', $post = null ) { return has_term( $tag, 'post_tag', $post ); } /** * Check if the current post has any of given terms. * * The given terms are checked against the post's terms' term_ids, names and slugs. * Terms given as integers will only be checked against the post's terms' term_ids. * If no terms are given, determines if post has any terms. * * @since 3.1.0 * * @param string|int|array $term Optional. The term name/term_id/slug or array of them to check for. * @param string $taxonomy Taxonomy name * @param int|object $post Optional. Post to check instead of the current post. * @return bool True if the current post has any of the given tags (or any tag, if no tag specified). */ function has_term( $term = '', $taxonomy = '', $post = null ) { $post = get_post($post); if ( !$post ) return false; $r = is_object_in_term( $post->ID, $taxonomy, $term ); if ( is_wp_error( $r ) ) return false; return $r; }
zyblog
trunk/zyblog/wp-includes/category-template.php
PHP
asf20
37,741
<?php /** * Main WordPress Formatting API. * * Handles many functions for formatting output. * * @package WordPress **/ /** * Replaces common plain text characters into formatted entities * * As an example, * <code> * 'cause today's effort makes it worth tomorrow's "holiday"... * </code> * Becomes: * <code> * &#8217;cause today&#8217;s effort makes it worth tomorrow&#8217;s &#8220;holiday&#8221;&#8230; * </code> * Code within certain html blocks are skipped. * * @since 0.71 * @uses $wp_cockneyreplace Array of formatted entities for certain common phrases * * @param string $text The text to be formatted * @return string The string replaced with html entities */ function wptexturize($text) { global $wp_cockneyreplace; static $static_characters, $static_replacements, $dynamic_characters, $dynamic_replacements, $default_no_texturize_tags, $default_no_texturize_shortcodes; // No need to set up these static variables more than once if ( ! isset( $static_characters ) ) { /* translators: opening curly double quote */ $opening_quote = _x( '&#8220;', 'opening curly double quote' ); /* translators: closing curly double quote */ $closing_quote = _x( '&#8221;', 'closing curly double quote' ); /* translators: apostrophe, for example in 'cause or can't */ $apos = _x( '&#8217;', 'apostrophe' ); /* translators: prime, for example in 9' (nine feet) */ $prime = _x( '&#8242;', 'prime' ); /* translators: double prime, for example in 9" (nine inches) */ $double_prime = _x( '&#8243;', 'double prime' ); /* translators: opening curly single quote */ $opening_single_quote = _x( '&#8216;', 'opening curly single quote' ); /* translators: closing curly single quote */ $closing_single_quote = _x( '&#8217;', 'closing curly single quote' ); /* translators: en dash */ $en_dash = _x( '&#8211;', 'en dash' ); /* translators: em dash */ $em_dash = _x( '&#8212;', 'em dash' ); $default_no_texturize_tags = array('pre', 'code', 'kbd', 'style', 'script', 'tt'); $default_no_texturize_shortcodes = array('code'); // if a plugin has provided an autocorrect array, use it if ( isset($wp_cockneyreplace) ) { $cockney = array_keys($wp_cockneyreplace); $cockneyreplace = array_values($wp_cockneyreplace); } elseif ( "'" != $apos ) { // Only bother if we're doing a replacement. $cockney = array( "'tain't", "'twere", "'twas", "'tis", "'twill", "'til", "'bout", "'nuff", "'round", "'cause" ); $cockneyreplace = array( $apos . "tain" . $apos . "t", $apos . "twere", $apos . "twas", $apos . "tis", $apos . "twill", $apos . "til", $apos . "bout", $apos . "nuff", $apos . "round", $apos . "cause" ); } else { $cockney = $cockneyreplace = array(); } $static_characters = array_merge( array( '---', ' -- ', '--', ' - ', 'xn&#8211;', '...', '``', '\'\'', ' (tm)' ), $cockney ); $static_replacements = array_merge( array( $em_dash, ' ' . $em_dash . ' ', $en_dash, ' ' . $en_dash . ' ', 'xn--', '&#8230;', $opening_quote, $closing_quote, ' &#8482;' ), $cockneyreplace ); $dynamic = array(); if ( "'" != $apos ) { $dynamic[ '/\'(\d\d(?:&#8217;|\')?s)/' ] = $apos . '$1'; // '99's $dynamic[ '/\'(\d)/' ] = $apos . '$1'; // '99 } if ( "'" != $opening_single_quote ) $dynamic[ '/(\s|\A|[([{<]|")\'/' ] = '$1' . $opening_single_quote; // opening single quote, even after (, {, <, [ if ( '"' != $double_prime ) $dynamic[ '/(\d)"/' ] = '$1' . $double_prime; // 9" (double prime) if ( "'" != $prime ) $dynamic[ '/(\d)\'/' ] = '$1' . $prime; // 9' (prime) if ( "'" != $apos ) $dynamic[ '/(\S)\'([^\'\s])/' ] = '$1' . $apos . '$2'; // apostrophe in a word if ( '"' != $opening_quote ) $dynamic[ '/(\s|\A|[([{<])"(?!\s)/' ] = '$1' . $opening_quote . '$2'; // opening double quote, even after (, {, <, [ if ( '"' != $closing_quote ) $dynamic[ '/"(\s|\S|\Z)/' ] = $closing_quote . '$1'; // closing double quote if ( "'" != $closing_single_quote ) $dynamic[ '/\'([\s.]|\Z)/' ] = $closing_single_quote . '$1'; // closing single quote $dynamic[ '/\b(\d+)x(\d+)\b/' ] = '$1&#215;$2'; // 9x9 (times) $dynamic_characters = array_keys( $dynamic ); $dynamic_replacements = array_values( $dynamic ); } // Transform into regexp sub-expression used in _wptexturize_pushpop_element // Must do this every time in case plugins use these filters in a context sensitive manner $no_texturize_tags = '(' . implode('|', apply_filters('no_texturize_tags', $default_no_texturize_tags) ) . ')'; $no_texturize_shortcodes = '(' . implode('|', apply_filters('no_texturize_shortcodes', $default_no_texturize_shortcodes) ) . ')'; $no_texturize_tags_stack = array(); $no_texturize_shortcodes_stack = array(); $textarr = preg_split('/(<.*>|\[.*\])/Us', $text, -1, PREG_SPLIT_DELIM_CAPTURE); foreach ( $textarr as &$curl ) { if ( empty( $curl ) ) continue; // Only call _wptexturize_pushpop_element if first char is correct tag opening $first = $curl[0]; if ( '<' === $first ) { _wptexturize_pushpop_element($curl, $no_texturize_tags_stack, $no_texturize_tags, '<', '>'); } elseif ( '[' === $first ) { _wptexturize_pushpop_element($curl, $no_texturize_shortcodes_stack, $no_texturize_shortcodes, '[', ']'); } elseif ( empty($no_texturize_shortcodes_stack) && empty($no_texturize_tags_stack) ) { // This is not a tag, nor is the texturization disabled static strings $curl = str_replace($static_characters, $static_replacements, $curl); // regular expressions $curl = preg_replace($dynamic_characters, $dynamic_replacements, $curl); } $curl = preg_replace('/&([^#])(?![a-zA-Z1-4]{1,8};)/', '&#038;$1', $curl); } return implode( '', $textarr ); } /** * Search for disabled element tags. Push element to stack on tag open and pop * on tag close. Assumes first character of $text is tag opening. * * @access private * @since 2.9.0 * * @param string $text Text to check. First character is assumed to be $opening * @param array $stack Array used as stack of opened tag elements * @param string $disabled_elements Tags to match against formatted as regexp sub-expression * @param string $opening Tag opening character, assumed to be 1 character long * @param string $closing Tag closing character */ function _wptexturize_pushpop_element($text, &$stack, $disabled_elements, $opening = '<', $closing = '>') { // Check if it is a closing tag -- otherwise assume opening tag if (strncmp($opening . '/', $text, 2)) { // Opening? Check $text+1 against disabled elements if (preg_match('/^' . $disabled_elements . '\b/', substr($text, 1), $matches)) { /* * This disables texturize until we find a closing tag of our type * (e.g. <pre>) even if there was invalid nesting before that * * Example: in the case <pre>sadsadasd</code>"baba"</pre> * "baba" won't be texturize */ array_push($stack, $matches[1]); } } else { // Closing? Check $text+2 against disabled elements $c = preg_quote($closing, '/'); if (preg_match('/^' . $disabled_elements . $c . '/', substr($text, 2), $matches)) { $last = array_pop($stack); // Make sure it matches the opening tag if ($last != $matches[1]) array_push($stack, $last); } } } /** * Replaces double line-breaks with paragraph elements. * * A group of regex replaces used to identify text formatted with newlines and * replace double line-breaks with HTML paragraph tags. The remaining * line-breaks after conversion become <<br />> tags, unless $br is set to '0' * or 'false'. * * @since 0.71 * * @param string $pee The text which has to be formatted. * @param bool $br Optional. If set, this will convert all remaining line-breaks after paragraphing. Default true. * @return string Text which has been converted into correct paragraph tags. */ function wpautop($pee, $br = true) { $pre_tags = array(); if ( trim($pee) === '' ) return ''; $pee = $pee . "\n"; // just to make things a little easier, pad the end if ( strpos($pee, '<pre') !== false ) { $pee_parts = explode( '</pre>', $pee ); $last_pee = array_pop($pee_parts); $pee = ''; $i = 0; foreach ( $pee_parts as $pee_part ) { $start = strpos($pee_part, '<pre'); // Malformed html? if ( $start === false ) { $pee .= $pee_part; continue; } $name = "<pre wp-pre-tag-$i></pre>"; $pre_tags[$name] = substr( $pee_part, $start ) . '</pre>'; $pee .= substr( $pee_part, 0, $start ) . $name; $i++; } $pee .= $last_pee; } $pee = preg_replace('|<br />\s*<br />|', "\n\n", $pee); // Space things out a little $allblocks = '(?:table|thead|tfoot|caption|col|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|select|option|form|map|area|blockquote|address|math|style|p|h[1-6]|hr|fieldset|noscript|samp|legend|section|article|aside|hgroup|header|footer|nav|figure|figcaption|details|menu|summary)'; $pee = preg_replace('!(<' . $allblocks . '[^>]*>)!', "\n$1", $pee); $pee = preg_replace('!(</' . $allblocks . '>)!', "$1\n\n", $pee); $pee = str_replace(array("\r\n", "\r"), "\n", $pee); // cross-platform newlines if ( strpos($pee, '<object') !== false ) { $pee = preg_replace('|\s*<param([^>]*)>\s*|', "<param$1>", $pee); // no pee inside object/embed $pee = preg_replace('|\s*</embed>\s*|', '</embed>', $pee); } $pee = preg_replace("/\n\n+/", "\n\n", $pee); // take care of duplicates // make paragraphs, including one at the end $pees = preg_split('/\n\s*\n/', $pee, -1, PREG_SPLIT_NO_EMPTY); $pee = ''; foreach ( $pees as $tinkle ) $pee .= '<p>' . trim($tinkle, "\n") . "</p>\n"; $pee = preg_replace('|<p>\s*</p>|', '', $pee); // under certain strange conditions it could create a P of entirely whitespace $pee = preg_replace('!<p>([^<]+)</(div|address|form)>!', "<p>$1</p></$2>", $pee); $pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee); // don't pee all over a tag $pee = preg_replace("|<p>(<li.+?)</p>|", "$1", $pee); // problem with nested lists $pee = preg_replace('|<p><blockquote([^>]*)>|i', "<blockquote$1><p>", $pee); $pee = str_replace('</blockquote></p>', '</p></blockquote>', $pee); $pee = preg_replace('!<p>\s*(</?' . $allblocks . '[^>]*>)!', "$1", $pee); $pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*</p>!', "$1", $pee); if ( $br ) { $pee = preg_replace_callback('/<(script|style).*?<\/\\1>/s', '_autop_newline_preservation_helper', $pee); $pee = preg_replace('|(?<!<br />)\s*\n|', "<br />\n", $pee); // optionally make line breaks $pee = str_replace('<WPPreserveNewline />', "\n", $pee); } $pee = preg_replace('!(</?' . $allblocks . '[^>]*>)\s*<br />!', "$1", $pee); $pee = preg_replace('!<br />(\s*</?(?:p|li|div|dl|dd|dt|th|pre|td|ul|ol)[^>]*>)!', '$1', $pee); $pee = preg_replace( "|\n</p>$|", '</p>', $pee ); if ( !empty($pre_tags) ) $pee = str_replace(array_keys($pre_tags), array_values($pre_tags), $pee); return $pee; } /** * Newline preservation help function for wpautop * * @since 3.1.0 * @access private * @param array $matches preg_replace_callback matches array * @return string */ function _autop_newline_preservation_helper( $matches ) { return str_replace("\n", "<WPPreserveNewline />", $matches[0]); } /** * Don't auto-p wrap shortcodes that stand alone * * Ensures that shortcodes are not wrapped in <<p>>...<</p>>. * * @since 2.9.0 * * @param string $pee The content. * @return string The filtered content. */ function shortcode_unautop( $pee ) { global $shortcode_tags; if ( empty( $shortcode_tags ) || !is_array( $shortcode_tags ) ) { return $pee; } $tagregexp = join( '|', array_map( 'preg_quote', array_keys( $shortcode_tags ) ) ); $pattern = '/' . '<p>' // Opening paragraph . '\\s*+' // Optional leading whitespace . '(' // 1: The shortcode . '\\[' // Opening bracket . "($tagregexp)" // 2: Shortcode name . '(?![\\w-])' // Not followed by word character or hyphen // Unroll the loop: Inside the opening shortcode tag . '[^\\]\\/]*' // Not a closing bracket or forward slash . '(?:' . '\\/(?!\\])' // A forward slash not followed by a closing bracket . '[^\\]\\/]*' // Not a closing bracket or forward slash . ')*?' . '(?:' . '\\/\\]' // Self closing tag and closing bracket . '|' . '\\]' // Closing bracket . '(?:' // Unroll the loop: Optionally, anything between the opening and closing shortcode tags . '[^\\[]*+' // Not an opening bracket . '(?:' . '\\[(?!\\/\\2\\])' // An opening bracket not followed by the closing shortcode tag . '[^\\[]*+' // Not an opening bracket . ')*+' . '\\[\\/\\2\\]' // Closing shortcode tag . ')?' . ')' . ')' . '\\s*+' // optional trailing whitespace . '<\\/p>' // closing paragraph . '/s'; return preg_replace( $pattern, '$1', $pee ); } /** * Checks to see if a string is utf8 encoded. * * NOTE: This function checks for 5-Byte sequences, UTF8 * has Bytes Sequences with a maximum length of 4. * * @author bmorel at ssi dot fr (modified) * @since 1.2.1 * * @param string $str The string to be checked * @return bool True if $str fits a UTF-8 model, false otherwise. */ function seems_utf8($str) { $length = strlen($str); for ($i=0; $i < $length; $i++) { $c = ord($str[$i]); if ($c < 0x80) $n = 0; # 0bbbbbbb elseif (($c & 0xE0) == 0xC0) $n=1; # 110bbbbb elseif (($c & 0xF0) == 0xE0) $n=2; # 1110bbbb elseif (($c & 0xF8) == 0xF0) $n=3; # 11110bbb elseif (($c & 0xFC) == 0xF8) $n=4; # 111110bb elseif (($c & 0xFE) == 0xFC) $n=5; # 1111110b else return false; # Does not match any model for ($j=0; $j<$n; $j++) { # n bytes matching 10bbbbbb follow ? if ((++$i == $length) || ((ord($str[$i]) & 0xC0) != 0x80)) return false; } } return true; } /** * Converts a number of special characters into their HTML entities. * * Specifically deals with: &, <, >, ", and '. * * $quote_style can be set to ENT_COMPAT to encode " to * &quot;, or ENT_QUOTES to do both. Default is ENT_NOQUOTES where no quotes are encoded. * * @since 1.2.2 * * @param string $string The text which is to be encoded. * @param mixed $quote_style Optional. Converts double quotes if set to ENT_COMPAT, both single and double if set to ENT_QUOTES or none if set to ENT_NOQUOTES. Also compatible with old values; converting single quotes if set to 'single', double if set to 'double' or both if otherwise set. Default is ENT_NOQUOTES. * @param string $charset Optional. The character encoding of the string. Default is false. * @param boolean $double_encode Optional. Whether to encode existing html entities. Default is false. * @return string The encoded text with HTML entities. */ function _wp_specialchars( $string, $quote_style = ENT_NOQUOTES, $charset = false, $double_encode = false ) { $string = (string) $string; if ( 0 === strlen( $string ) ) return ''; // Don't bother if there are no specialchars - saves some processing if ( ! preg_match( '/[&<>"\']/', $string ) ) return $string; // Account for the previous behaviour of the function when the $quote_style is not an accepted value if ( empty( $quote_style ) ) $quote_style = ENT_NOQUOTES; elseif ( ! in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) ) $quote_style = ENT_QUOTES; // Store the site charset as a static to avoid multiple calls to wp_load_alloptions() if ( ! $charset ) { static $_charset; if ( ! isset( $_charset ) ) { $alloptions = wp_load_alloptions(); $_charset = isset( $alloptions['blog_charset'] ) ? $alloptions['blog_charset'] : ''; } $charset = $_charset; } if ( in_array( $charset, array( 'utf8', 'utf-8', 'UTF8' ) ) ) $charset = 'UTF-8'; $_quote_style = $quote_style; if ( $quote_style === 'double' ) { $quote_style = ENT_COMPAT; $_quote_style = ENT_COMPAT; } elseif ( $quote_style === 'single' ) { $quote_style = ENT_NOQUOTES; } // Handle double encoding ourselves if ( $double_encode ) { $string = @htmlspecialchars( $string, $quote_style, $charset ); } else { // Decode &amp; into & $string = wp_specialchars_decode( $string, $_quote_style ); // Guarantee every &entity; is valid or re-encode the & $string = wp_kses_normalize_entities( $string ); // Now re-encode everything except &entity; $string = preg_split( '/(&#?x?[0-9a-z]+;)/i', $string, -1, PREG_SPLIT_DELIM_CAPTURE ); for ( $i = 0; $i < count( $string ); $i += 2 ) $string[$i] = @htmlspecialchars( $string[$i], $quote_style, $charset ); $string = implode( '', $string ); } // Backwards compatibility if ( 'single' === $_quote_style ) $string = str_replace( "'", '&#039;', $string ); return $string; } /** * Converts a number of HTML entities into their special characters. * * Specifically deals with: &, <, >, ", and '. * * $quote_style can be set to ENT_COMPAT to decode " entities, * or ENT_QUOTES to do both " and '. Default is ENT_NOQUOTES where no quotes are decoded. * * @since 2.8 * * @param string $string The text which is to be decoded. * @param mixed $quote_style Optional. Converts double quotes if set to ENT_COMPAT, both single and double if set to ENT_QUOTES or none if set to ENT_NOQUOTES. Also compatible with old _wp_specialchars() values; converting single quotes if set to 'single', double if set to 'double' or both if otherwise set. Default is ENT_NOQUOTES. * @return string The decoded text without HTML entities. */ function wp_specialchars_decode( $string, $quote_style = ENT_NOQUOTES ) { $string = (string) $string; if ( 0 === strlen( $string ) ) { return ''; } // Don't bother if there are no entities - saves a lot of processing if ( strpos( $string, '&' ) === false ) { return $string; } // Match the previous behaviour of _wp_specialchars() when the $quote_style is not an accepted value if ( empty( $quote_style ) ) { $quote_style = ENT_NOQUOTES; } elseif ( !in_array( $quote_style, array( 0, 2, 3, 'single', 'double' ), true ) ) { $quote_style = ENT_QUOTES; } // More complete than get_html_translation_table( HTML_SPECIALCHARS ) $single = array( '&#039;' => '\'', '&#x27;' => '\'' ); $single_preg = array( '/&#0*39;/' => '&#039;', '/&#x0*27;/i' => '&#x27;' ); $double = array( '&quot;' => '"', '&#034;' => '"', '&#x22;' => '"' ); $double_preg = array( '/&#0*34;/' => '&#034;', '/&#x0*22;/i' => '&#x22;' ); $others = array( '&lt;' => '<', '&#060;' => '<', '&gt;' => '>', '&#062;' => '>', '&amp;' => '&', '&#038;' => '&', '&#x26;' => '&' ); $others_preg = array( '/&#0*60;/' => '&#060;', '/&#0*62;/' => '&#062;', '/&#0*38;/' => '&#038;', '/&#x0*26;/i' => '&#x26;' ); if ( $quote_style === ENT_QUOTES ) { $translation = array_merge( $single, $double, $others ); $translation_preg = array_merge( $single_preg, $double_preg, $others_preg ); } elseif ( $quote_style === ENT_COMPAT || $quote_style === 'double' ) { $translation = array_merge( $double, $others ); $translation_preg = array_merge( $double_preg, $others_preg ); } elseif ( $quote_style === 'single' ) { $translation = array_merge( $single, $others ); $translation_preg = array_merge( $single_preg, $others_preg ); } elseif ( $quote_style === ENT_NOQUOTES ) { $translation = $others; $translation_preg = $others_preg; } // Remove zero padding on numeric entities $string = preg_replace( array_keys( $translation_preg ), array_values( $translation_preg ), $string ); // Replace characters according to translation table return strtr( $string, $translation ); } /** * Checks for invalid UTF8 in a string. * * @since 2.8 * * @param string $string The text which is to be checked. * @param boolean $strip Optional. Whether to attempt to strip out invalid UTF8. Default is false. * @return string The checked text. */ function wp_check_invalid_utf8( $string, $strip = false ) { $string = (string) $string; if ( 0 === strlen( $string ) ) { return ''; } // Store the site charset as a static to avoid multiple calls to get_option() static $is_utf8; if ( !isset( $is_utf8 ) ) { $is_utf8 = in_array( get_option( 'blog_charset' ), array( 'utf8', 'utf-8', 'UTF8', 'UTF-8' ) ); } if ( !$is_utf8 ) { return $string; } // Check for support for utf8 in the installed PCRE library once and store the result in a static static $utf8_pcre; if ( !isset( $utf8_pcre ) ) { $utf8_pcre = @preg_match( '/^./u', 'a' ); } // We can't demand utf8 in the PCRE installation, so just return the string in those cases if ( !$utf8_pcre ) { return $string; } // preg_match fails when it encounters invalid UTF8 in $string if ( 1 === @preg_match( '/^./us', $string ) ) { return $string; } // Attempt to strip the bad chars if requested (not recommended) if ( $strip && function_exists( 'iconv' ) ) { return iconv( 'utf-8', 'utf-8', $string ); } return ''; } /** * Encode the Unicode values to be used in the URI. * * @since 1.5.0 * * @param string $utf8_string * @param int $length Max length of the string * @return string String with Unicode encoded for URI. */ function utf8_uri_encode( $utf8_string, $length = 0 ) { $unicode = ''; $values = array(); $num_octets = 1; $unicode_length = 0; $string_length = strlen( $utf8_string ); for ($i = 0; $i < $string_length; $i++ ) { $value = ord( $utf8_string[ $i ] ); if ( $value < 128 ) { if ( $length && ( $unicode_length >= $length ) ) break; $unicode .= chr($value); $unicode_length++; } else { if ( count( $values ) == 0 ) $num_octets = ( $value < 224 ) ? 2 : 3; $values[] = $value; if ( $length && ( $unicode_length + ($num_octets * 3) ) > $length ) break; if ( count( $values ) == $num_octets ) { if ($num_octets == 3) { $unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]) . '%' . dechex($values[2]); $unicode_length += 9; } else { $unicode .= '%' . dechex($values[0]) . '%' . dechex($values[1]); $unicode_length += 6; } $values = array(); $num_octets = 1; } } } return $unicode; } /** * Converts all accent characters to ASCII characters. * * If there are no accent characters, then the string given is just returned. * * @since 1.2.1 * * @param string $string Text that might have accent characters * @return string Filtered string with replaced "nice" characters. */ function remove_accents($string) { if ( !preg_match('/[\x80-\xff]/', $string) ) return $string; if (seems_utf8($string)) { $chars = array( // Decompositions for Latin-1 Supplement chr(194).chr(170) => 'a', chr(194).chr(186) => 'o', chr(195).chr(128) => 'A', chr(195).chr(129) => 'A', chr(195).chr(130) => 'A', chr(195).chr(131) => 'A', chr(195).chr(132) => 'A', chr(195).chr(133) => 'A', chr(195).chr(134) => 'AE',chr(195).chr(135) => 'C', chr(195).chr(136) => 'E', chr(195).chr(137) => 'E', chr(195).chr(138) => 'E', chr(195).chr(139) => 'E', chr(195).chr(140) => 'I', chr(195).chr(141) => 'I', chr(195).chr(142) => 'I', chr(195).chr(143) => 'I', chr(195).chr(144) => 'D', chr(195).chr(145) => 'N', chr(195).chr(146) => 'O', chr(195).chr(147) => 'O', chr(195).chr(148) => 'O', chr(195).chr(149) => 'O', chr(195).chr(150) => 'O', chr(195).chr(153) => 'U', chr(195).chr(154) => 'U', chr(195).chr(155) => 'U', chr(195).chr(156) => 'U', chr(195).chr(157) => 'Y', chr(195).chr(158) => 'TH',chr(195).chr(159) => 's', chr(195).chr(160) => 'a', chr(195).chr(161) => 'a', chr(195).chr(162) => 'a', chr(195).chr(163) => 'a', chr(195).chr(164) => 'a', chr(195).chr(165) => 'a', chr(195).chr(166) => 'ae',chr(195).chr(167) => 'c', chr(195).chr(168) => 'e', chr(195).chr(169) => 'e', chr(195).chr(170) => 'e', chr(195).chr(171) => 'e', chr(195).chr(172) => 'i', chr(195).chr(173) => 'i', chr(195).chr(174) => 'i', chr(195).chr(175) => 'i', chr(195).chr(176) => 'd', chr(195).chr(177) => 'n', chr(195).chr(178) => 'o', chr(195).chr(179) => 'o', chr(195).chr(180) => 'o', chr(195).chr(181) => 'o', chr(195).chr(182) => 'o', chr(195).chr(184) => 'o', chr(195).chr(185) => 'u', chr(195).chr(186) => 'u', chr(195).chr(187) => 'u', chr(195).chr(188) => 'u', chr(195).chr(189) => 'y', chr(195).chr(190) => 'th', chr(195).chr(191) => 'y', chr(195).chr(152) => 'O', // Decompositions for Latin Extended-A chr(196).chr(128) => 'A', chr(196).chr(129) => 'a', chr(196).chr(130) => 'A', chr(196).chr(131) => 'a', chr(196).chr(132) => 'A', chr(196).chr(133) => 'a', chr(196).chr(134) => 'C', chr(196).chr(135) => 'c', chr(196).chr(136) => 'C', chr(196).chr(137) => 'c', chr(196).chr(138) => 'C', chr(196).chr(139) => 'c', chr(196).chr(140) => 'C', chr(196).chr(141) => 'c', chr(196).chr(142) => 'D', chr(196).chr(143) => 'd', chr(196).chr(144) => 'D', chr(196).chr(145) => 'd', chr(196).chr(146) => 'E', chr(196).chr(147) => 'e', chr(196).chr(148) => 'E', chr(196).chr(149) => 'e', chr(196).chr(150) => 'E', chr(196).chr(151) => 'e', chr(196).chr(152) => 'E', chr(196).chr(153) => 'e', chr(196).chr(154) => 'E', chr(196).chr(155) => 'e', chr(196).chr(156) => 'G', chr(196).chr(157) => 'g', chr(196).chr(158) => 'G', chr(196).chr(159) => 'g', chr(196).chr(160) => 'G', chr(196).chr(161) => 'g', chr(196).chr(162) => 'G', chr(196).chr(163) => 'g', chr(196).chr(164) => 'H', chr(196).chr(165) => 'h', chr(196).chr(166) => 'H', chr(196).chr(167) => 'h', chr(196).chr(168) => 'I', chr(196).chr(169) => 'i', chr(196).chr(170) => 'I', chr(196).chr(171) => 'i', chr(196).chr(172) => 'I', chr(196).chr(173) => 'i', chr(196).chr(174) => 'I', chr(196).chr(175) => 'i', chr(196).chr(176) => 'I', chr(196).chr(177) => 'i', chr(196).chr(178) => 'IJ',chr(196).chr(179) => 'ij', chr(196).chr(180) => 'J', chr(196).chr(181) => 'j', chr(196).chr(182) => 'K', chr(196).chr(183) => 'k', chr(196).chr(184) => 'k', chr(196).chr(185) => 'L', chr(196).chr(186) => 'l', chr(196).chr(187) => 'L', chr(196).chr(188) => 'l', chr(196).chr(189) => 'L', chr(196).chr(190) => 'l', chr(196).chr(191) => 'L', chr(197).chr(128) => 'l', chr(197).chr(129) => 'L', chr(197).chr(130) => 'l', chr(197).chr(131) => 'N', chr(197).chr(132) => 'n', chr(197).chr(133) => 'N', chr(197).chr(134) => 'n', chr(197).chr(135) => 'N', chr(197).chr(136) => 'n', chr(197).chr(137) => 'N', chr(197).chr(138) => 'n', chr(197).chr(139) => 'N', chr(197).chr(140) => 'O', chr(197).chr(141) => 'o', chr(197).chr(142) => 'O', chr(197).chr(143) => 'o', chr(197).chr(144) => 'O', chr(197).chr(145) => 'o', chr(197).chr(146) => 'OE',chr(197).chr(147) => 'oe', chr(197).chr(148) => 'R',chr(197).chr(149) => 'r', chr(197).chr(150) => 'R',chr(197).chr(151) => 'r', chr(197).chr(152) => 'R',chr(197).chr(153) => 'r', chr(197).chr(154) => 'S',chr(197).chr(155) => 's', chr(197).chr(156) => 'S',chr(197).chr(157) => 's', chr(197).chr(158) => 'S',chr(197).chr(159) => 's', chr(197).chr(160) => 'S', chr(197).chr(161) => 's', chr(197).chr(162) => 'T', chr(197).chr(163) => 't', chr(197).chr(164) => 'T', chr(197).chr(165) => 't', chr(197).chr(166) => 'T', chr(197).chr(167) => 't', chr(197).chr(168) => 'U', chr(197).chr(169) => 'u', chr(197).chr(170) => 'U', chr(197).chr(171) => 'u', chr(197).chr(172) => 'U', chr(197).chr(173) => 'u', chr(197).chr(174) => 'U', chr(197).chr(175) => 'u', chr(197).chr(176) => 'U', chr(197).chr(177) => 'u', chr(197).chr(178) => 'U', chr(197).chr(179) => 'u', chr(197).chr(180) => 'W', chr(197).chr(181) => 'w', chr(197).chr(182) => 'Y', chr(197).chr(183) => 'y', chr(197).chr(184) => 'Y', chr(197).chr(185) => 'Z', chr(197).chr(186) => 'z', chr(197).chr(187) => 'Z', chr(197).chr(188) => 'z', chr(197).chr(189) => 'Z', chr(197).chr(190) => 'z', chr(197).chr(191) => 's', // Decompositions for Latin Extended-B chr(200).chr(152) => 'S', chr(200).chr(153) => 's', chr(200).chr(154) => 'T', chr(200).chr(155) => 't', // Euro Sign chr(226).chr(130).chr(172) => 'E', // GBP (Pound) Sign chr(194).chr(163) => '', // Vowels with diacritic (Vietnamese) // unmarked chr(198).chr(160) => 'O', chr(198).chr(161) => 'o', chr(198).chr(175) => 'U', chr(198).chr(176) => 'u', // grave accent chr(225).chr(186).chr(166) => 'A', chr(225).chr(186).chr(167) => 'a', chr(225).chr(186).chr(176) => 'A', chr(225).chr(186).chr(177) => 'a', chr(225).chr(187).chr(128) => 'E', chr(225).chr(187).chr(129) => 'e', chr(225).chr(187).chr(146) => 'O', chr(225).chr(187).chr(147) => 'o', chr(225).chr(187).chr(156) => 'O', chr(225).chr(187).chr(157) => 'o', chr(225).chr(187).chr(170) => 'U', chr(225).chr(187).chr(171) => 'u', chr(225).chr(187).chr(178) => 'Y', chr(225).chr(187).chr(179) => 'y', // hook chr(225).chr(186).chr(162) => 'A', chr(225).chr(186).chr(163) => 'a', chr(225).chr(186).chr(168) => 'A', chr(225).chr(186).chr(169) => 'a', chr(225).chr(186).chr(178) => 'A', chr(225).chr(186).chr(179) => 'a', chr(225).chr(186).chr(186) => 'E', chr(225).chr(186).chr(187) => 'e', chr(225).chr(187).chr(130) => 'E', chr(225).chr(187).chr(131) => 'e', chr(225).chr(187).chr(136) => 'I', chr(225).chr(187).chr(137) => 'i', chr(225).chr(187).chr(142) => 'O', chr(225).chr(187).chr(143) => 'o', chr(225).chr(187).chr(148) => 'O', chr(225).chr(187).chr(149) => 'o', chr(225).chr(187).chr(158) => 'O', chr(225).chr(187).chr(159) => 'o', chr(225).chr(187).chr(166) => 'U', chr(225).chr(187).chr(167) => 'u', chr(225).chr(187).chr(172) => 'U', chr(225).chr(187).chr(173) => 'u', chr(225).chr(187).chr(182) => 'Y', chr(225).chr(187).chr(183) => 'y', // tilde chr(225).chr(186).chr(170) => 'A', chr(225).chr(186).chr(171) => 'a', chr(225).chr(186).chr(180) => 'A', chr(225).chr(186).chr(181) => 'a', chr(225).chr(186).chr(188) => 'E', chr(225).chr(186).chr(189) => 'e', chr(225).chr(187).chr(132) => 'E', chr(225).chr(187).chr(133) => 'e', chr(225).chr(187).chr(150) => 'O', chr(225).chr(187).chr(151) => 'o', chr(225).chr(187).chr(160) => 'O', chr(225).chr(187).chr(161) => 'o', chr(225).chr(187).chr(174) => 'U', chr(225).chr(187).chr(175) => 'u', chr(225).chr(187).chr(184) => 'Y', chr(225).chr(187).chr(185) => 'y', // acute accent chr(225).chr(186).chr(164) => 'A', chr(225).chr(186).chr(165) => 'a', chr(225).chr(186).chr(174) => 'A', chr(225).chr(186).chr(175) => 'a', chr(225).chr(186).chr(190) => 'E', chr(225).chr(186).chr(191) => 'e', chr(225).chr(187).chr(144) => 'O', chr(225).chr(187).chr(145) => 'o', chr(225).chr(187).chr(154) => 'O', chr(225).chr(187).chr(155) => 'o', chr(225).chr(187).chr(168) => 'U', chr(225).chr(187).chr(169) => 'u', // dot below chr(225).chr(186).chr(160) => 'A', chr(225).chr(186).chr(161) => 'a', chr(225).chr(186).chr(172) => 'A', chr(225).chr(186).chr(173) => 'a', chr(225).chr(186).chr(182) => 'A', chr(225).chr(186).chr(183) => 'a', chr(225).chr(186).chr(184) => 'E', chr(225).chr(186).chr(185) => 'e', chr(225).chr(187).chr(134) => 'E', chr(225).chr(187).chr(135) => 'e', chr(225).chr(187).chr(138) => 'I', chr(225).chr(187).chr(139) => 'i', chr(225).chr(187).chr(140) => 'O', chr(225).chr(187).chr(141) => 'o', chr(225).chr(187).chr(152) => 'O', chr(225).chr(187).chr(153) => 'o', chr(225).chr(187).chr(162) => 'O', chr(225).chr(187).chr(163) => 'o', chr(225).chr(187).chr(164) => 'U', chr(225).chr(187).chr(165) => 'u', chr(225).chr(187).chr(176) => 'U', chr(225).chr(187).chr(177) => 'u', chr(225).chr(187).chr(180) => 'Y', chr(225).chr(187).chr(181) => 'y', // Vowels with diacritic (Chinese, Hanyu Pinyin) chr(201).chr(145) => 'a', // macron chr(199).chr(149) => 'U', chr(199).chr(150) => 'u', // acute accent chr(199).chr(151) => 'U', chr(199).chr(152) => 'u', // caron chr(199).chr(141) => 'A', chr(199).chr(142) => 'a', chr(199).chr(143) => 'I', chr(199).chr(144) => 'i', chr(199).chr(145) => 'O', chr(199).chr(146) => 'o', chr(199).chr(147) => 'U', chr(199).chr(148) => 'u', chr(199).chr(153) => 'U', chr(199).chr(154) => 'u', // grave accent chr(199).chr(155) => 'U', chr(199).chr(156) => 'u', ); $string = strtr($string, $chars); } else { // Assume ISO-8859-1 if not UTF-8 $chars['in'] = chr(128).chr(131).chr(138).chr(142).chr(154).chr(158) .chr(159).chr(162).chr(165).chr(181).chr(192).chr(193).chr(194) .chr(195).chr(196).chr(197).chr(199).chr(200).chr(201).chr(202) .chr(203).chr(204).chr(205).chr(206).chr(207).chr(209).chr(210) .chr(211).chr(212).chr(213).chr(214).chr(216).chr(217).chr(218) .chr(219).chr(220).chr(221).chr(224).chr(225).chr(226).chr(227) .chr(228).chr(229).chr(231).chr(232).chr(233).chr(234).chr(235) .chr(236).chr(237).chr(238).chr(239).chr(241).chr(242).chr(243) .chr(244).chr(245).chr(246).chr(248).chr(249).chr(250).chr(251) .chr(252).chr(253).chr(255); $chars['out'] = "EfSZszYcYuAAAAAACEEEEIIIINOOOOOOUUUUYaaaaaaceeeeiiiinoooooouuuuyy"; $string = strtr($string, $chars['in'], $chars['out']); $double_chars['in'] = array(chr(140), chr(156), chr(198), chr(208), chr(222), chr(223), chr(230), chr(240), chr(254)); $double_chars['out'] = array('OE', 'oe', 'AE', 'DH', 'TH', 'ss', 'ae', 'dh', 'th'); $string = str_replace($double_chars['in'], $double_chars['out'], $string); } return $string; } /** * Sanitizes a filename replacing whitespace with dashes * * Removes special characters that are illegal in filenames on certain * operating systems and special characters requiring special escaping * to manipulate at the command line. Replaces spaces and consecutive * dashes with a single dash. Trim period, dash and underscore from beginning * and end of filename. * * @since 2.1.0 * * @param string $filename The filename to be sanitized * @return string The sanitized filename */ function sanitize_file_name( $filename ) { $filename_raw = $filename; $special_chars = array("?", "[", "]", "/", "\\", "=", "<", ">", ":", ";", ",", "'", "\"", "&", "$", "#", "*", "(", ")", "|", "~", "`", "!", "{", "}", chr(0)); $special_chars = apply_filters('sanitize_file_name_chars', $special_chars, $filename_raw); $filename = str_replace($special_chars, '', $filename); $filename = preg_replace('/[\s-]+/', '-', $filename); $filename = trim($filename, '.-_'); // Split the filename into a base and extension[s] $parts = explode('.', $filename); // Return if only one extension if ( count($parts) <= 2 ) return apply_filters('sanitize_file_name', $filename, $filename_raw); // Process multiple extensions $filename = array_shift($parts); $extension = array_pop($parts); $mimes = get_allowed_mime_types(); // Loop over any intermediate extensions. Munge them with a trailing underscore if they are a 2 - 5 character // long alpha string not in the extension whitelist. foreach ( (array) $parts as $part) { $filename .= '.' . $part; if ( preg_match("/^[a-zA-Z]{2,5}\d?$/", $part) ) { $allowed = false; foreach ( $mimes as $ext_preg => $mime_match ) { $ext_preg = '!^(' . $ext_preg . ')$!i'; if ( preg_match( $ext_preg, $part ) ) { $allowed = true; break; } } if ( !$allowed ) $filename .= '_'; } } $filename .= '.' . $extension; return apply_filters('sanitize_file_name', $filename, $filename_raw); } /** * Sanitize username stripping out unsafe characters. * * Removes tags, octets, entities, and if strict is enabled, will only keep * alphanumeric, _, space, ., -, @. After sanitizing, it passes the username, * raw username (the username in the parameter), and the value of $strict as * parameters for the 'sanitize_user' filter. * * @since 2.0.0 * @uses apply_filters() Calls 'sanitize_user' hook on username, raw username, * and $strict parameter. * * @param string $username The username to be sanitized. * @param bool $strict If set limits $username to specific characters. Default false. * @return string The sanitized username, after passing through filters. */ function sanitize_user( $username, $strict = false ) { $raw_username = $username; $username = wp_strip_all_tags( $username ); $username = remove_accents( $username ); // Kill octets $username = preg_replace( '|%([a-fA-F0-9][a-fA-F0-9])|', '', $username ); $username = preg_replace( '/&.+?;/', '', $username ); // Kill entities // If strict, reduce to ASCII for max portability. if ( $strict ) $username = preg_replace( '|[^a-z0-9 _.\-@]|i', '', $username ); $username = trim( $username ); // Consolidate contiguous whitespace $username = preg_replace( '|\s+|', ' ', $username ); return apply_filters( 'sanitize_user', $username, $raw_username, $strict ); } /** * Sanitize a string key. * * Keys are used as internal identifiers. Lowercase alphanumeric characters, dashes and underscores are allowed. * * @since 3.0.0 * * @param string $key String key * @return string Sanitized key */ function sanitize_key( $key ) { $raw_key = $key; $key = strtolower( $key ); $key = preg_replace( '/[^a-z0-9_\-]/', '', $key ); return apply_filters( 'sanitize_key', $key, $raw_key ); } /** * Sanitizes title or use fallback title. * * Specifically, HTML and PHP tags are stripped. Further actions can be added * via the plugin API. If $title is empty and $fallback_title is set, the latter * will be used. * * @since 1.0.0 * * @param string $title The string to be sanitized. * @param string $fallback_title Optional. A title to use if $title is empty. * @param string $context Optional. The operation for which the string is sanitized * @return string The sanitized string. */ function sanitize_title($title, $fallback_title = '', $context = 'save') { $raw_title = $title; if ( 'save' == $context ) $title = remove_accents($title); $title = apply_filters('sanitize_title', $title, $raw_title, $context); if ( '' === $title || false === $title ) $title = $fallback_title; return $title; } function sanitize_title_for_query($title) { return sanitize_title($title, '', 'query'); } /** * Sanitizes title, replacing whitespace and a few other characters with dashes. * * Limits the output to alphanumeric characters, underscore (_) and dash (-). * Whitespace becomes a dash. * * @since 1.2.0 * * @param string $title The title to be sanitized. * @param string $raw_title Optional. Not used. * @param string $context Optional. The operation for which the string is sanitized. * @return string The sanitized title. */ function sanitize_title_with_dashes($title, $raw_title = '', $context = 'display') { $title = strip_tags($title); // Preserve escaped octets. $title = preg_replace('|%([a-fA-F0-9][a-fA-F0-9])|', '---$1---', $title); // Remove percent signs that are not part of an octet. $title = str_replace('%', '', $title); // Restore octets. $title = preg_replace('|---([a-fA-F0-9][a-fA-F0-9])---|', '%$1', $title); if (seems_utf8($title)) { if (function_exists('mb_strtolower')) { $title = mb_strtolower($title, 'UTF-8'); } $title = utf8_uri_encode($title, 200); } $title = strtolower($title); $title = preg_replace('/&.+?;/', '', $title); // kill entities $title = str_replace('.', '-', $title); if ( 'save' == $context ) { // Convert nbsp, ndash and mdash to hyphens $title = str_replace( array( '%c2%a0', '%e2%80%93', '%e2%80%94' ), '-', $title ); // Strip these characters entirely $title = str_replace( array( // iexcl and iquest '%c2%a1', '%c2%bf', // angle quotes '%c2%ab', '%c2%bb', '%e2%80%b9', '%e2%80%ba', // curly quotes '%e2%80%98', '%e2%80%99', '%e2%80%9c', '%e2%80%9d', '%e2%80%9a', '%e2%80%9b', '%e2%80%9e', '%e2%80%9f', // copy, reg, deg, hellip and trade '%c2%a9', '%c2%ae', '%c2%b0', '%e2%80%a6', '%e2%84%a2', // grave accent, acute accent, macron, caron '%cc%80', '%cc%81', '%cc%84', '%cc%8c', ), '', $title ); // Convert times to x $title = str_replace( '%c3%97', 'x', $title ); } $title = preg_replace('/[^%a-z0-9 _-]/', '', $title); $title = preg_replace('/\s+/', '-', $title); $title = preg_replace('|-+|', '-', $title); $title = trim($title, '-'); return $title; } /** * Ensures a string is a valid SQL order by clause. * * Accepts one or more columns, with or without ASC/DESC, and also accepts * RAND(). * * @since 2.5.1 * * @param string $orderby Order by string to be checked. * @return string|bool Returns the order by clause if it is a match, false otherwise. */ function sanitize_sql_orderby( $orderby ){ preg_match('/^\s*([a-z0-9_]+(\s+(ASC|DESC))?(\s*,\s*|\s*$))+|^\s*RAND\(\s*\)\s*$/i', $orderby, $obmatches); if ( !$obmatches ) return false; return $orderby; } /** * Santizes a html classname to ensure it only contains valid characters * * Strips the string down to A-Z,a-z,0-9,_,-. If this results in an empty * string then it will return the alternative value supplied. * * @todo Expand to support the full range of CDATA that a class attribute can contain. * * @since 2.8.0 * * @param string $class The classname to be sanitized * @param string $fallback Optional. The value to return if the sanitization end's up as an empty string. * Defaults to an empty string. * @return string The sanitized value */ function sanitize_html_class( $class, $fallback = '' ) { //Strip out any % encoded octets $sanitized = preg_replace( '|%[a-fA-F0-9][a-fA-F0-9]|', '', $class ); //Limit to A-Z,a-z,0-9,_,- $sanitized = preg_replace( '/[^A-Za-z0-9_-]/', '', $sanitized ); if ( '' == $sanitized ) $sanitized = $fallback; return apply_filters( 'sanitize_html_class', $sanitized, $class, $fallback ); } /** * Converts a number of characters from a string. * * Metadata tags <<title>> and <<category>> are removed, <<br>> and <<hr>> are * converted into correct XHTML and Unicode characters are converted to the * valid range. * * @since 0.71 * * @param string $content String of characters to be converted. * @param string $deprecated Not used. * @return string Converted string. */ function convert_chars($content, $deprecated = '') { if ( !empty( $deprecated ) ) _deprecated_argument( __FUNCTION__, '0.71' ); // Translation of invalid Unicode references range to valid range $wp_htmltranswinuni = array( '&#128;' => '&#8364;', // the Euro sign '&#129;' => '', '&#130;' => '&#8218;', // these are Windows CP1252 specific characters '&#131;' => '&#402;', // they would look weird on non-Windows browsers '&#132;' => '&#8222;', '&#133;' => '&#8230;', '&#134;' => '&#8224;', '&#135;' => '&#8225;', '&#136;' => '&#710;', '&#137;' => '&#8240;', '&#138;' => '&#352;', '&#139;' => '&#8249;', '&#140;' => '&#338;', '&#141;' => '', '&#142;' => '&#381;', '&#143;' => '', '&#144;' => '', '&#145;' => '&#8216;', '&#146;' => '&#8217;', '&#147;' => '&#8220;', '&#148;' => '&#8221;', '&#149;' => '&#8226;', '&#150;' => '&#8211;', '&#151;' => '&#8212;', '&#152;' => '&#732;', '&#153;' => '&#8482;', '&#154;' => '&#353;', '&#155;' => '&#8250;', '&#156;' => '&#339;', '&#157;' => '', '&#158;' => '&#382;', '&#159;' => '&#376;' ); // Remove metadata tags $content = preg_replace('/<title>(.+?)<\/title>/','',$content); $content = preg_replace('/<category>(.+?)<\/category>/','',$content); // Converts lone & characters into &#38; (a.k.a. &amp;) $content = preg_replace('/&([^#])(?![a-z1-4]{1,8};)/i', '&#038;$1', $content); // Fix Word pasting $content = strtr($content, $wp_htmltranswinuni); // Just a little XHTML help $content = str_replace('<br>', '<br />', $content); $content = str_replace('<hr>', '<hr />', $content); return $content; } /** * Will only balance the tags if forced to and the option is set to balance tags. * * The option 'use_balanceTags' is used to determine whether the tags will be balanced. * * @since 0.71 * * @param string $text Text to be balanced * @param bool $force If true, forces balancing, ignoring the value of the option. Default false. * @return string Balanced text */ function balanceTags( $text, $force = false ) { if ( !$force && get_option('use_balanceTags') == 0 ) return $text; return force_balance_tags( $text ); } /** * Balances tags of string using a modified stack. * * @since 2.0.4 * * @author Leonard Lin <leonard@acm.org> * @license GPL * @copyright November 4, 2001 * @version 1.1 * @todo Make better - change loop condition to $text in 1.2 * @internal Modified by Scott Reilly (coffee2code) 02 Aug 2004 * 1.1 Fixed handling of append/stack pop order of end text * Added Cleaning Hooks * 1.0 First Version * * @param string $text Text to be balanced. * @return string Balanced text. */ function force_balance_tags( $text ) { $tagstack = array(); $stacksize = 0; $tagqueue = ''; $newtext = ''; // Known single-entity/self-closing tags $single_tags = array( 'area', 'base', 'basefont', 'br', 'col', 'command', 'embed', 'frame', 'hr', 'img', 'input', 'isindex', 'link', 'meta', 'param', 'source' ); // Tags that can be immediately nested within themselves $nestable_tags = array( 'blockquote', 'div', 'object', 'q', 'span' ); // WP bug fix for comments - in case you REALLY meant to type '< !--' $text = str_replace('< !--', '< !--', $text); // WP bug fix for LOVE <3 (and other situations with '<' before a number) $text = preg_replace('#<([0-9]{1})#', '&lt;$1', $text); while ( preg_match("/<(\/?[\w:]*)\s*([^>]*)>/", $text, $regex) ) { $newtext .= $tagqueue; $i = strpos($text, $regex[0]); $l = strlen($regex[0]); // clear the shifter $tagqueue = ''; // Pop or Push if ( isset($regex[1][0]) && '/' == $regex[1][0] ) { // End Tag $tag = strtolower(substr($regex[1],1)); // if too many closing tags if( $stacksize <= 0 ) { $tag = ''; // or close to be safe $tag = '/' . $tag; } // if stacktop value = tag close value then pop else if ( $tagstack[$stacksize - 1] == $tag ) { // found closing tag $tag = '</' . $tag . '>'; // Close Tag // Pop array_pop( $tagstack ); $stacksize--; } else { // closing tag not at top, search for it for ( $j = $stacksize-1; $j >= 0; $j-- ) { if ( $tagstack[$j] == $tag ) { // add tag to tagqueue for ( $k = $stacksize-1; $k >= $j; $k--) { $tagqueue .= '</' . array_pop( $tagstack ) . '>'; $stacksize--; } break; } } $tag = ''; } } else { // Begin Tag $tag = strtolower($regex[1]); // Tag Cleaning // If it's an empty tag "< >", do nothing if ( '' == $tag ) { // do nothing } // ElseIf it presents itself as a self-closing tag... elseif ( substr( $regex[2], -1 ) == '/' ) { // ...but it isn't a known single-entity self-closing tag, then don't let it be treated as such and // immediately close it with a closing tag (the tag will encapsulate no text as a result) if ( ! in_array( $tag, $single_tags ) ) $regex[2] = trim( substr( $regex[2], 0, -1 ) ) . "></$tag"; } // ElseIf it's a known single-entity tag but it doesn't close itself, do so elseif ( in_array($tag, $single_tags) ) { $regex[2] .= '/'; } // Else it's not a single-entity tag else { // If the top of the stack is the same as the tag we want to push, close previous tag if ( $stacksize > 0 && !in_array($tag, $nestable_tags) && $tagstack[$stacksize - 1] == $tag ) { $tagqueue = '</' . array_pop( $tagstack ) . '>'; $stacksize--; } $stacksize = array_push( $tagstack, $tag ); } // Attributes $attributes = $regex[2]; if( ! empty( $attributes ) && $attributes[0] != '>' ) $attributes = ' ' . $attributes; $tag = '<' . $tag . $attributes . '>'; //If already queuing a close tag, then put this tag on, too if ( !empty($tagqueue) ) { $tagqueue .= $tag; $tag = ''; } } $newtext .= substr($text, 0, $i) . $tag; $text = substr($text, $i + $l); } // Clear Tag Queue $newtext .= $tagqueue; // Add Remaining text $newtext .= $text; // Empty Stack while( $x = array_pop($tagstack) ) $newtext .= '</' . $x . '>'; // Add remaining tags to close // WP fix for the bug with HTML comments $newtext = str_replace("< !--","<!--",$newtext); $newtext = str_replace("< !--","< !--",$newtext); return $newtext; } /** * Acts on text which is about to be edited. * * The $content is run through esc_textarea(), which uses htmlspecialchars() * to convert special characters to HTML entities. If $richedit is set to true, * it is simply a holder for the 'format_to_edit' filter. * * @since 0.71 * * @param string $content The text about to be edited. * @param bool $richedit Whether the $content should not pass through htmlspecialchars(). Default false (meaning it will be passed). * @return string The text after the filter (and possibly htmlspecialchars()) has been run. */ function format_to_edit( $content, $richedit = false ) { $content = apply_filters( 'format_to_edit', $content ); if ( ! $richedit ) $content = esc_textarea( $content ); return $content; } /** * Holder for the 'format_to_post' filter. * * @since 0.71 * * @param string $content The text to pass through the filter. * @return string Text returned from the 'format_to_post' filter. */ function format_to_post($content) { $content = apply_filters('format_to_post', $content); return $content; } /** * Add leading zeros when necessary. * * If you set the threshold to '4' and the number is '10', then you will get * back '0010'. If you set the threshold to '4' and the number is '5000', then you * will get back '5000'. * * Uses sprintf to append the amount of zeros based on the $threshold parameter * and the size of the number. If the number is large enough, then no zeros will * be appended. * * @since 0.71 * * @param mixed $number Number to append zeros to if not greater than threshold. * @param int $threshold Digit places number needs to be to not have zeros added. * @return string Adds leading zeros to number if needed. */ function zeroise($number, $threshold) { return sprintf('%0'.$threshold.'s', $number); } /** * Adds backslashes before letters and before a number at the start of a string. * * @since 0.71 * * @param string $string Value to which backslashes will be added. * @return string String with backslashes inserted. */ function backslashit($string) { $string = preg_replace('/^([0-9])/', '\\\\\\\\\1', $string); $string = preg_replace('/([a-z])/i', '\\\\\1', $string); return $string; } /** * Appends a trailing slash. * * Will remove trailing slash if it exists already before adding a trailing * slash. This prevents double slashing a string or path. * * The primary use of this is for paths and thus should be used for paths. It is * not restricted to paths and offers no specific path support. * * @since 1.2.0 * @uses untrailingslashit() Unslashes string if it was slashed already. * * @param string $string What to add the trailing slash to. * @return string String with trailing slash added. */ function trailingslashit($string) { return untrailingslashit($string) . '/'; } /** * Removes trailing slash if it exists. * * The primary use of this is for paths and thus should be used for paths. It is * not restricted to paths and offers no specific path support. * * @since 2.2.0 * * @param string $string What to remove the trailing slash from. * @return string String without the trailing slash. */ function untrailingslashit($string) { return rtrim($string, '/'); } /** * Adds slashes to escape strings. * * Slashes will first be removed if magic_quotes_gpc is set, see {@link * http://www.php.net/magic_quotes} for more details. * * @since 0.71 * * @param string $gpc The string returned from HTTP request data. * @return string Returns a string escaped with slashes. */ function addslashes_gpc($gpc) { if ( get_magic_quotes_gpc() ) $gpc = stripslashes($gpc); return esc_sql($gpc); } /** * Navigates through an array and removes slashes from the values. * * If an array is passed, the array_map() function causes a callback to pass the * value back to the function. The slashes from this value will removed. * * @since 2.0.0 * * @param mixed $value The value to be stripped. * @return mixed Stripped value. */ function stripslashes_deep($value) { if ( is_array($value) ) { $value = array_map('stripslashes_deep', $value); } elseif ( is_object($value) ) { $vars = get_object_vars( $value ); foreach ($vars as $key=>$data) { $value->{$key} = stripslashes_deep( $data ); } } elseif ( is_string( $value ) ) { $value = stripslashes($value); } return $value; } /** * Navigates through an array and encodes the values to be used in a URL. * * * @since 2.2.0 * * @param array|string $value The array or string to be encoded. * @return array|string $value The encoded array (or string from the callback). */ function urlencode_deep($value) { $value = is_array($value) ? array_map('urlencode_deep', $value) : urlencode($value); return $value; } /** * Navigates through an array and raw encodes the values to be used in a URL. * * @since 3.4.0 * * @param array|string $value The array or string to be encoded. * @return array|string $value The encoded array (or string from the callback). */ function rawurlencode_deep( $value ) { return is_array( $value ) ? array_map( 'rawurlencode_deep', $value ) : rawurlencode( $value ); } /** * Converts email addresses characters to HTML entities to block spam bots. * * @since 0.71 * * @param string $emailaddy Email address. * @param int $mailto Optional. Range from 0 to 1. Used for encoding. * @return string Converted email address. */ function antispambot($emailaddy, $mailto=0) { $emailNOSPAMaddy = ''; srand ((float) microtime() * 1000000); for ($i = 0; $i < strlen($emailaddy); $i = $i + 1) { $j = floor(rand(0, 1+$mailto)); if ($j==0) { $emailNOSPAMaddy .= '&#'.ord(substr($emailaddy,$i,1)).';'; } elseif ($j==1) { $emailNOSPAMaddy .= substr($emailaddy,$i,1); } elseif ($j==2) { $emailNOSPAMaddy .= '%'.zeroise(dechex(ord(substr($emailaddy, $i, 1))), 2); } } $emailNOSPAMaddy = str_replace('@','&#64;',$emailNOSPAMaddy); return $emailNOSPAMaddy; } /** * Callback to convert URI match to HTML A element. * * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link * make_clickable()}. * * @since 2.3.2 * @access private * * @param array $matches Single Regex Match. * @return string HTML A element with URI address. */ function _make_url_clickable_cb($matches) { $url = $matches[2]; if ( ')' == $matches[3] && strpos( $url, '(' ) ) { // If the trailing character is a closing parethesis, and the URL has an opening parenthesis in it, add the closing parenthesis to the URL. // Then we can let the parenthesis balancer do its thing below. $url .= $matches[3]; $suffix = ''; } else { $suffix = $matches[3]; } // Include parentheses in the URL only if paired while ( substr_count( $url, '(' ) < substr_count( $url, ')' ) ) { $suffix = strrchr( $url, ')' ) . $suffix; $url = substr( $url, 0, strrpos( $url, ')' ) ); } $url = esc_url($url); if ( empty($url) ) return $matches[0]; return $matches[1] . "<a href=\"$url\" rel=\"nofollow\">$url</a>" . $suffix; } /** * Callback to convert URL match to HTML A element. * * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link * make_clickable()}. * * @since 2.3.2 * @access private * * @param array $matches Single Regex Match. * @return string HTML A element with URL address. */ function _make_web_ftp_clickable_cb($matches) { $ret = ''; $dest = $matches[2]; $dest = 'http://' . $dest; $dest = esc_url($dest); if ( empty($dest) ) return $matches[0]; // removed trailing [.,;:)] from URL if ( in_array( substr($dest, -1), array('.', ',', ';', ':', ')') ) === true ) { $ret = substr($dest, -1); $dest = substr($dest, 0, strlen($dest)-1); } return $matches[1] . "<a href=\"$dest\" rel=\"nofollow\">$dest</a>$ret"; } /** * Callback to convert email address match to HTML A element. * * This function was backported from 2.5.0 to 2.3.2. Regex callback for {@link * make_clickable()}. * * @since 2.3.2 * @access private * * @param array $matches Single Regex Match. * @return string HTML A element with email address. */ function _make_email_clickable_cb($matches) { $email = $matches[2] . '@' . $matches[3]; return $matches[1] . "<a href=\"mailto:$email\">$email</a>"; } /** * Convert plaintext URI to HTML links. * * Converts URI, www and ftp, and email addresses. Finishes by fixing links * within links. * * @since 0.71 * * @param string $text Content to convert URIs. * @return string Content with converted URIs. */ function make_clickable( $text ) { $r = ''; $textarr = preg_split( '/(<[^<>]+>)/', $text, -1, PREG_SPLIT_DELIM_CAPTURE ); // split out HTML tags foreach ( $textarr as $piece ) { if ( empty( $piece ) || ( $piece[0] == '<' && ! preg_match('|^<\s*[\w]{1,20}+://|', $piece) ) ) { $r .= $piece; continue; } // Long strings might contain expensive edge cases ... if ( 10000 < strlen( $piece ) ) { // ... break it up foreach ( _split_str_by_whitespace( $piece, 2100 ) as $chunk ) { // 2100: Extra room for scheme and leading and trailing paretheses if ( 2101 < strlen( $chunk ) ) { $r .= $chunk; // Too big, no whitespace: bail. } else { $r .= make_clickable( $chunk ); } } } else { $ret = " $piece "; // Pad with whitespace to simplify the regexes $url_clickable = '~ ([\\s(<.,;:!?]) # 1: Leading whitespace, or punctuation ( # 2: URL [\\w]{1,20}+:// # Scheme and hier-part prefix (?=\S{1,2000}\s) # Limit to URLs less than about 2000 characters long [\\w\\x80-\\xff#%\\~/@\\[\\]*(+=&$-]*+ # Non-punctuation URL character (?: # Unroll the Loop: Only allow puctuation URL character if followed by a non-punctuation URL character [\'.,;:!?)] # Punctuation URL character [\\w\\x80-\\xff#%\\~/@\\[\\]*(+=&$-]++ # Non-punctuation URL character )* ) (\)?) # 3: Trailing closing parenthesis (for parethesis balancing post processing) ~xS'; // The regex is a non-anchored pattern and does not have a single fixed starting character. // Tell PCRE to spend more time optimizing since, when used on a page load, it will probably be used several times. $ret = preg_replace_callback( $url_clickable, '_make_url_clickable_cb', $ret ); $ret = preg_replace_callback( '#([\s>])((www|ftp)\.[\w\\x80-\\xff\#$%&~/.\-;:=,?@\[\]+]+)#is', '_make_web_ftp_clickable_cb', $ret ); $ret = preg_replace_callback( '#([\s>])([.0-9a-z_+-]+)@(([0-9a-z-]+\.)+[0-9a-z]{2,})#i', '_make_email_clickable_cb', $ret ); $ret = substr( $ret, 1, -1 ); // Remove our whitespace padding. $r .= $ret; } } // Cleanup of accidental links within links $r = preg_replace( '#(<a( [^>]+?>|>))<a [^>]+?>([^>]+?)</a></a>#i', "$1$3</a>", $r ); return $r; } /** * Breaks a string into chunks by splitting at whitespace characters. * The length of each returned chunk is as close to the specified length goal as possible, * with the caveat that each chunk includes its trailing delimiter. * Chunks longer than the goal are guaranteed to not have any inner whitespace. * * Joining the returned chunks with empty delimiters reconstructs the input string losslessly. * * Input string must have no null characters (or eventual transformations on output chunks must not care about null characters) * * <code> * _split_str_by_whitespace( "1234 67890 1234 67890a cd 1234 890 123456789 1234567890a 45678 1 3 5 7 90 ", 10 ) == * array ( * 0 => '1234 67890 ', // 11 characters: Perfect split * 1 => '1234 ', // 5 characters: '1234 67890a' was too long * 2 => '67890a cd ', // 10 characters: '67890a cd 1234' was too long * 3 => '1234 890 ', // 11 characters: Perfect split * 4 => '123456789 ', // 10 characters: '123456789 1234567890a' was too long * 5 => '1234567890a ', // 12 characters: Too long, but no inner whitespace on which to split * 6 => ' 45678 ', // 11 characters: Perfect split * 7 => '1 3 5 7 9', // 9 characters: End of $string * ); * </code> * * @since 3.4.0 * @access private * * @param string $string The string to split. * @param int $goal The desired chunk length. * @return array Numeric array of chunks. */ function _split_str_by_whitespace( $string, $goal ) { $chunks = array(); $string_nullspace = strtr( $string, "\r\n\t\v\f ", "\000\000\000\000\000\000" ); while ( $goal < strlen( $string_nullspace ) ) { $pos = strrpos( substr( $string_nullspace, 0, $goal + 1 ), "\000" ); if ( false === $pos ) { $pos = strpos( $string_nullspace, "\000", $goal + 1 ); if ( false === $pos ) { break; } } $chunks[] = substr( $string, 0, $pos + 1 ); $string = substr( $string, $pos + 1 ); $string_nullspace = substr( $string_nullspace, $pos + 1 ); } if ( $string ) { $chunks[] = $string; } return $chunks; } /** * Adds rel nofollow string to all HTML A elements in content. * * @since 1.5.0 * * @param string $text Content that may contain HTML A elements. * @return string Converted content. */ function wp_rel_nofollow( $text ) { // This is a pre save filter, so text is already escaped. $text = stripslashes($text); $text = preg_replace_callback('|<a (.+?)>|i', 'wp_rel_nofollow_callback', $text); $text = esc_sql($text); return $text; } /** * Callback to used to add rel=nofollow string to HTML A element. * * Will remove already existing rel="nofollow" and rel='nofollow' from the * string to prevent from invalidating (X)HTML. * * @since 2.3.0 * * @param array $matches Single Match * @return string HTML A Element with rel nofollow. */ function wp_rel_nofollow_callback( $matches ) { $text = $matches[1]; $text = str_replace(array(' rel="nofollow"', " rel='nofollow'"), '', $text); return "<a $text rel=\"nofollow\">"; } /** * Convert one smiley code to the icon graphic file equivalent. * * Looks up one smiley code in the $wpsmiliestrans global array and returns an * <img> string for that smiley. * * @global array $wpsmiliestrans * @since 2.8.0 * * @param string $smiley Smiley code to convert to image. * @return string Image string for smiley. */ function translate_smiley($smiley) { global $wpsmiliestrans; if (count($smiley) == 0) { return ''; } $smiley = trim(reset($smiley)); $img = $wpsmiliestrans[$smiley]; $smiley_masked = esc_attr($smiley); $srcurl = apply_filters('smilies_src', includes_url("images/smilies/$img"), $img, site_url()); return " <img src='$srcurl' alt='$smiley_masked' class='wp-smiley' /> "; } /** * Convert text equivalent of smilies to images. * * Will only convert smilies if the option 'use_smilies' is true and the global * used in the function isn't empty. * * @since 0.71 * @uses $wp_smiliessearch * * @param string $text Content to convert smilies from text. * @return string Converted content with text smilies replaced with images. */ function convert_smilies($text) { global $wp_smiliessearch; $output = ''; if ( get_option('use_smilies') && !empty($wp_smiliessearch) ) { // HTML loop taken from texturize function, could possible be consolidated $textarr = preg_split("/(<.*>)/U", $text, -1, PREG_SPLIT_DELIM_CAPTURE); // capture the tags as well as in between $stop = count($textarr);// loop stuff for ($i = 0; $i < $stop; $i++) { $content = $textarr[$i]; if ((strlen($content) > 0) && ('<' != $content[0])) { // If it's not a tag $content = preg_replace_callback($wp_smiliessearch, 'translate_smiley', $content); } $output .= $content; } } else { // return default text. $output = $text; } return $output; } /** * Verifies that an email is valid. * * Does not grok i18n domains. Not RFC compliant. * * @since 0.71 * * @param string $email Email address to verify. * @param boolean $deprecated Deprecated. * @return string|bool Either false or the valid email address. */ function is_email( $email, $deprecated = false ) { if ( ! empty( $deprecated ) ) _deprecated_argument( __FUNCTION__, '3.0' ); // Test for the minimum length the email can be if ( strlen( $email ) < 3 ) { return apply_filters( 'is_email', false, $email, 'email_too_short' ); } // Test for an @ character after the first position if ( strpos( $email, '@', 1 ) === false ) { return apply_filters( 'is_email', false, $email, 'email_no_at' ); } // Split out the local and domain parts list( $local, $domain ) = explode( '@', $email, 2 ); // LOCAL PART // Test for invalid characters if ( !preg_match( '/^[a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]+$/', $local ) ) { return apply_filters( 'is_email', false, $email, 'local_invalid_chars' ); } // DOMAIN PART // Test for sequences of periods if ( preg_match( '/\.{2,}/', $domain ) ) { return apply_filters( 'is_email', false, $email, 'domain_period_sequence' ); } // Test for leading and trailing periods and whitespace if ( trim( $domain, " \t\n\r\0\x0B." ) !== $domain ) { return apply_filters( 'is_email', false, $email, 'domain_period_limits' ); } // Split the domain into subs $subs = explode( '.', $domain ); // Assume the domain will have at least two subs if ( 2 > count( $subs ) ) { return apply_filters( 'is_email', false, $email, 'domain_no_periods' ); } // Loop through each sub foreach ( $subs as $sub ) { // Test for leading and trailing hyphens and whitespace if ( trim( $sub, " \t\n\r\0\x0B-" ) !== $sub ) { return apply_filters( 'is_email', false, $email, 'sub_hyphen_limits' ); } // Test for invalid characters if ( !preg_match('/^[a-z0-9-]+$/i', $sub ) ) { return apply_filters( 'is_email', false, $email, 'sub_invalid_chars' ); } } // Congratulations your email made it! return apply_filters( 'is_email', $email, $email, null ); } /** * Convert to ASCII from email subjects. * * @since 1.2.0 * * @param string $string Subject line * @return string Converted string to ASCII */ function wp_iso_descrambler($string) { /* this may only work with iso-8859-1, I'm afraid */ if (!preg_match('#\=\?(.+)\?Q\?(.+)\?\=#i', $string, $matches)) { return $string; } else { $subject = str_replace('_', ' ', $matches[2]); $subject = preg_replace_callback('#\=([0-9a-f]{2})#i', '_wp_iso_convert', $subject); return $subject; } } /** * Helper function to convert hex encoded chars to ASCII * * @since 3.1.0 * @access private * @param array $match The preg_replace_callback matches array * @return array Converted chars */ function _wp_iso_convert( $match ) { return chr( hexdec( strtolower( $match[1] ) ) ); } /** * Returns a date in the GMT equivalent. * * Requires and returns a date in the Y-m-d H:i:s format. Simply subtracts the * value of the 'gmt_offset' option. Return format can be overridden using the * $format parameter. The DateTime and DateTimeZone classes are used to respect * time zone differences in DST. * * @since 1.2.0 * * @uses get_option() to retrieve the the value of 'gmt_offset'. * @param string $string The date to be converted. * @param string $format The format string for the returned date (default is Y-m-d H:i:s) * @return string GMT version of the date provided. */ function get_gmt_from_date($string, $format = 'Y-m-d H:i:s') { preg_match('#([0-9]{1,4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})#', $string, $matches); if ( ! $matches ) return date( $format, 0 ); $tz = get_option('timezone_string'); if ( $tz ) { date_default_timezone_set( $tz ); $datetime = date_create( $string ); if ( ! $datetime ) return date( $format, 0 ); $datetime->setTimezone( new DateTimeZone('UTC') ); $offset = $datetime->getOffset(); $datetime->modify( '+' . $offset / HOUR_IN_SECONDS . ' hours'); $string_gmt = gmdate($format, $datetime->format('U')); date_default_timezone_set('UTC'); } else { $string_time = gmmktime($matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1]); $string_gmt = gmdate($format, $string_time - get_option('gmt_offset') * HOUR_IN_SECONDS); } return $string_gmt; } /** * Converts a GMT date into the correct format for the blog. * * Requires and returns in the Y-m-d H:i:s format. Simply adds the value of * gmt_offset.Return format can be overridden using the $format parameter * * @since 1.2.0 * * @param string $string The date to be converted. * @param string $format The format string for the returned date (default is Y-m-d H:i:s) * @return string Formatted date relative to the GMT offset. */ function get_date_from_gmt($string, $format = 'Y-m-d H:i:s') { preg_match('#([0-9]{1,4})-([0-9]{1,2})-([0-9]{1,2}) ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2})#', $string, $matches); $string_time = gmmktime($matches[4], $matches[5], $matches[6], $matches[2], $matches[3], $matches[1]); $string_localtime = gmdate($format, $string_time + get_option('gmt_offset') * HOUR_IN_SECONDS); return $string_localtime; } /** * Computes an offset in seconds from an iso8601 timezone. * * @since 1.5.0 * * @param string $timezone Either 'Z' for 0 offset or '±hhmm'. * @return int|float The offset in seconds. */ function iso8601_timezone_to_offset($timezone) { // $timezone is either 'Z' or '[+|-]hhmm' if ($timezone == 'Z') { $offset = 0; } else { $sign = (substr($timezone, 0, 1) == '+') ? 1 : -1; $hours = intval(substr($timezone, 1, 2)); $minutes = intval(substr($timezone, 3, 4)) / 60; $offset = $sign * HOUR_IN_SECONDS * ($hours + $minutes); } return $offset; } /** * Converts an iso8601 date to MySQL DateTime format used by post_date[_gmt]. * * @since 1.5.0 * * @param string $date_string Date and time in ISO 8601 format {@link http://en.wikipedia.org/wiki/ISO_8601}. * @param string $timezone Optional. If set to GMT returns the time minus gmt_offset. Default is 'user'. * @return string The date and time in MySQL DateTime format - Y-m-d H:i:s. */ function iso8601_to_datetime($date_string, $timezone = 'user') { $timezone = strtolower($timezone); if ($timezone == 'gmt') { preg_match('#([0-9]{4})([0-9]{2})([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(Z|[\+|\-][0-9]{2,4}){0,1}#', $date_string, $date_bits); if (!empty($date_bits[7])) { // we have a timezone, so let's compute an offset $offset = iso8601_timezone_to_offset($date_bits[7]); } else { // we don't have a timezone, so we assume user local timezone (not server's!) $offset = HOUR_IN_SECONDS * get_option('gmt_offset'); } $timestamp = gmmktime($date_bits[4], $date_bits[5], $date_bits[6], $date_bits[2], $date_bits[3], $date_bits[1]); $timestamp -= $offset; return gmdate('Y-m-d H:i:s', $timestamp); } else if ($timezone == 'user') { return preg_replace('#([0-9]{4})([0-9]{2})([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(Z|[\+|\-][0-9]{2,4}){0,1}#', '$1-$2-$3 $4:$5:$6', $date_string); } } /** * Adds a element attributes to open links in new windows. * * Comment text in popup windows should be filtered through this. Right now it's * a moderately dumb function, ideally it would detect whether a target or rel * attribute was already there and adjust its actions accordingly. * * @since 0.71 * * @param string $text Content to replace links to open in a new window. * @return string Content that has filtered links. */ function popuplinks($text) { $text = preg_replace('/<a (.+?)>/i', "<a $1 target='_blank' rel='external'>", $text); return $text; } /** * Strips out all characters that are not allowable in an email. * * @since 1.5.0 * * @param string $email Email address to filter. * @return string Filtered email address. */ function sanitize_email( $email ) { // Test for the minimum length the email can be if ( strlen( $email ) < 3 ) { return apply_filters( 'sanitize_email', '', $email, 'email_too_short' ); } // Test for an @ character after the first position if ( strpos( $email, '@', 1 ) === false ) { return apply_filters( 'sanitize_email', '', $email, 'email_no_at' ); } // Split out the local and domain parts list( $local, $domain ) = explode( '@', $email, 2 ); // LOCAL PART // Test for invalid characters $local = preg_replace( '/[^a-zA-Z0-9!#$%&\'*+\/=?^_`{|}~\.-]/', '', $local ); if ( '' === $local ) { return apply_filters( 'sanitize_email', '', $email, 'local_invalid_chars' ); } // DOMAIN PART // Test for sequences of periods $domain = preg_replace( '/\.{2,}/', '', $domain ); if ( '' === $domain ) { return apply_filters( 'sanitize_email', '', $email, 'domain_period_sequence' ); } // Test for leading and trailing periods and whitespace $domain = trim( $domain, " \t\n\r\0\x0B." ); if ( '' === $domain ) { return apply_filters( 'sanitize_email', '', $email, 'domain_period_limits' ); } // Split the domain into subs $subs = explode( '.', $domain ); // Assume the domain will have at least two subs if ( 2 > count( $subs ) ) { return apply_filters( 'sanitize_email', '', $email, 'domain_no_periods' ); } // Create an array that will contain valid subs $new_subs = array(); // Loop through each sub foreach ( $subs as $sub ) { // Test for leading and trailing hyphens $sub = trim( $sub, " \t\n\r\0\x0B-" ); // Test for invalid characters $sub = preg_replace( '/[^a-z0-9-]+/i', '', $sub ); // If there's anything left, add it to the valid subs if ( '' !== $sub ) { $new_subs[] = $sub; } } // If there aren't 2 or more valid subs if ( 2 > count( $new_subs ) ) { return apply_filters( 'sanitize_email', '', $email, 'domain_no_valid_subs' ); } // Join valid subs into the new domain $domain = join( '.', $new_subs ); // Put the email back together $email = $local . '@' . $domain; // Congratulations your email made it! return apply_filters( 'sanitize_email', $email, $email, null ); } /** * Determines the difference between two timestamps. * * The difference is returned in a human readable format such as "1 hour", * "5 mins", "2 days". * * @since 1.5.0 * * @param int $from Unix timestamp from which the difference begins. * @param int $to Optional. Unix timestamp to end the time difference. Default becomes time() if not set. * @return string Human readable time difference. */ function human_time_diff( $from, $to = '' ) { if ( empty( $to ) ) $to = time(); $diff = (int) abs( $to - $from ); if ( $diff <= HOUR_IN_SECONDS ) { $mins = round( $diff / MINUTE_IN_SECONDS ); if ( $mins <= 1 ) { $mins = 1; } /* translators: min=minute */ $since = sprintf( _n( '%s min', '%s mins', $mins ), $mins ); } elseif ( ( $diff <= DAY_IN_SECONDS ) && ( $diff > HOUR_IN_SECONDS ) ) { $hours = round( $diff / HOUR_IN_SECONDS ); if ( $hours <= 1 ) { $hours = 1; } $since = sprintf( _n( '%s hour', '%s hours', $hours ), $hours ); } elseif ( $diff >= DAY_IN_SECONDS ) { $days = round( $diff / DAY_IN_SECONDS ); if ( $days <= 1 ) { $days = 1; } $since = sprintf( _n( '%s day', '%s days', $days ), $days ); } return $since; } /** * Generates an excerpt from the content, if needed. * * The excerpt word amount will be 55 words and if the amount is greater than * that, then the string ' [...]' will be appended to the excerpt. If the string * is less than 55 words, then the content will be returned as is. * * The 55 word limit can be modified by plugins/themes using the excerpt_length filter * The ' [...]' string can be modified by plugins/themes using the excerpt_more filter * * @since 1.5.0 * * @param string $text Optional. The excerpt. If set to empty, an excerpt is generated. * @return string The excerpt. */ function wp_trim_excerpt($text = '') { $raw_excerpt = $text; if ( '' == $text ) { $text = get_the_content(''); $text = strip_shortcodes( $text ); $text = apply_filters('the_content', $text); $text = str_replace(']]>', ']]&gt;', $text); $excerpt_length = apply_filters('excerpt_length', 55); $excerpt_more = apply_filters('excerpt_more', ' ' . '[...]'); $text = wp_trim_words( $text, $excerpt_length, $excerpt_more ); } return apply_filters('wp_trim_excerpt', $text, $raw_excerpt); } /** * Trims text to a certain number of words. * * This function is localized. For languages that count 'words' by the individual * character (such as East Asian languages), the $num_words argument will apply * to the number of individual characters. * * @since 3.3.0 * * @param string $text Text to trim. * @param int $num_words Number of words. Default 55. * @param string $more What to append if $text needs to be trimmed. Default '&hellip;'. * @return string Trimmed text. */ function wp_trim_words( $text, $num_words = 55, $more = null ) { if ( null === $more ) $more = __( '&hellip;' ); $original_text = $text; $text = wp_strip_all_tags( $text ); /* translators: If your word count is based on single characters (East Asian characters), enter 'characters'. Otherwise, enter 'words'. Do not translate into your own language. */ if ( 'characters' == _x( 'words', 'word count: words or characters?' ) && preg_match( '/^utf\-?8$/i', get_option( 'blog_charset' ) ) ) { $text = trim( preg_replace( "/[\n\r\t ]+/", ' ', $text ), ' ' ); preg_match_all( '/./u', $text, $words_array ); $words_array = array_slice( $words_array[0], 0, $num_words + 1 ); $sep = ''; } else { $words_array = preg_split( "/[\n\r\t ]+/", $text, $num_words + 1, PREG_SPLIT_NO_EMPTY ); $sep = ' '; } if ( count( $words_array ) > $num_words ) { array_pop( $words_array ); $text = implode( $sep, $words_array ); $text = $text . $more; } else { $text = implode( $sep, $words_array ); } return apply_filters( 'wp_trim_words', $text, $num_words, $more, $original_text ); } /** * Converts named entities into numbered entities. * * @since 1.5.1 * * @param string $text The text within which entities will be converted. * @return string Text with converted entities. */ function ent2ncr($text) { // Allow a plugin to short-circuit and override the mappings. $filtered = apply_filters( 'pre_ent2ncr', null, $text ); if( null !== $filtered ) return $filtered; $to_ncr = array( '&quot;' => '&#34;', '&amp;' => '&#38;', '&frasl;' => '&#47;', '&lt;' => '&#60;', '&gt;' => '&#62;', '|' => '&#124;', '&nbsp;' => '&#160;', '&iexcl;' => '&#161;', '&cent;' => '&#162;', '&pound;' => '&#163;', '&curren;' => '&#164;', '&yen;' => '&#165;', '&brvbar;' => '&#166;', '&brkbar;' => '&#166;', '&sect;' => '&#167;', '&uml;' => '&#168;', '&die;' => '&#168;', '&copy;' => '&#169;', '&ordf;' => '&#170;', '&laquo;' => '&#171;', '&not;' => '&#172;', '&shy;' => '&#173;', '&reg;' => '&#174;', '&macr;' => '&#175;', '&hibar;' => '&#175;', '&deg;' => '&#176;', '&plusmn;' => '&#177;', '&sup2;' => '&#178;', '&sup3;' => '&#179;', '&acute;' => '&#180;', '&micro;' => '&#181;', '&para;' => '&#182;', '&middot;' => '&#183;', '&cedil;' => '&#184;', '&sup1;' => '&#185;', '&ordm;' => '&#186;', '&raquo;' => '&#187;', '&frac14;' => '&#188;', '&frac12;' => '&#189;', '&frac34;' => '&#190;', '&iquest;' => '&#191;', '&Agrave;' => '&#192;', '&Aacute;' => '&#193;', '&Acirc;' => '&#194;', '&Atilde;' => '&#195;', '&Auml;' => '&#196;', '&Aring;' => '&#197;', '&AElig;' => '&#198;', '&Ccedil;' => '&#199;', '&Egrave;' => '&#200;', '&Eacute;' => '&#201;', '&Ecirc;' => '&#202;', '&Euml;' => '&#203;', '&Igrave;' => '&#204;', '&Iacute;' => '&#205;', '&Icirc;' => '&#206;', '&Iuml;' => '&#207;', '&ETH;' => '&#208;', '&Ntilde;' => '&#209;', '&Ograve;' => '&#210;', '&Oacute;' => '&#211;', '&Ocirc;' => '&#212;', '&Otilde;' => '&#213;', '&Ouml;' => '&#214;', '&times;' => '&#215;', '&Oslash;' => '&#216;', '&Ugrave;' => '&#217;', '&Uacute;' => '&#218;', '&Ucirc;' => '&#219;', '&Uuml;' => '&#220;', '&Yacute;' => '&#221;', '&THORN;' => '&#222;', '&szlig;' => '&#223;', '&agrave;' => '&#224;', '&aacute;' => '&#225;', '&acirc;' => '&#226;', '&atilde;' => '&#227;', '&auml;' => '&#228;', '&aring;' => '&#229;', '&aelig;' => '&#230;', '&ccedil;' => '&#231;', '&egrave;' => '&#232;', '&eacute;' => '&#233;', '&ecirc;' => '&#234;', '&euml;' => '&#235;', '&igrave;' => '&#236;', '&iacute;' => '&#237;', '&icirc;' => '&#238;', '&iuml;' => '&#239;', '&eth;' => '&#240;', '&ntilde;' => '&#241;', '&ograve;' => '&#242;', '&oacute;' => '&#243;', '&ocirc;' => '&#244;', '&otilde;' => '&#245;', '&ouml;' => '&#246;', '&divide;' => '&#247;', '&oslash;' => '&#248;', '&ugrave;' => '&#249;', '&uacute;' => '&#250;', '&ucirc;' => '&#251;', '&uuml;' => '&#252;', '&yacute;' => '&#253;', '&thorn;' => '&#254;', '&yuml;' => '&#255;', '&OElig;' => '&#338;', '&oelig;' => '&#339;', '&Scaron;' => '&#352;', '&scaron;' => '&#353;', '&Yuml;' => '&#376;', '&fnof;' => '&#402;', '&circ;' => '&#710;', '&tilde;' => '&#732;', '&Alpha;' => '&#913;', '&Beta;' => '&#914;', '&Gamma;' => '&#915;', '&Delta;' => '&#916;', '&Epsilon;' => '&#917;', '&Zeta;' => '&#918;', '&Eta;' => '&#919;', '&Theta;' => '&#920;', '&Iota;' => '&#921;', '&Kappa;' => '&#922;', '&Lambda;' => '&#923;', '&Mu;' => '&#924;', '&Nu;' => '&#925;', '&Xi;' => '&#926;', '&Omicron;' => '&#927;', '&Pi;' => '&#928;', '&Rho;' => '&#929;', '&Sigma;' => '&#931;', '&Tau;' => '&#932;', '&Upsilon;' => '&#933;', '&Phi;' => '&#934;', '&Chi;' => '&#935;', '&Psi;' => '&#936;', '&Omega;' => '&#937;', '&alpha;' => '&#945;', '&beta;' => '&#946;', '&gamma;' => '&#947;', '&delta;' => '&#948;', '&epsilon;' => '&#949;', '&zeta;' => '&#950;', '&eta;' => '&#951;', '&theta;' => '&#952;', '&iota;' => '&#953;', '&kappa;' => '&#954;', '&lambda;' => '&#955;', '&mu;' => '&#956;', '&nu;' => '&#957;', '&xi;' => '&#958;', '&omicron;' => '&#959;', '&pi;' => '&#960;', '&rho;' => '&#961;', '&sigmaf;' => '&#962;', '&sigma;' => '&#963;', '&tau;' => '&#964;', '&upsilon;' => '&#965;', '&phi;' => '&#966;', '&chi;' => '&#967;', '&psi;' => '&#968;', '&omega;' => '&#969;', '&thetasym;' => '&#977;', '&upsih;' => '&#978;', '&piv;' => '&#982;', '&ensp;' => '&#8194;', '&emsp;' => '&#8195;', '&thinsp;' => '&#8201;', '&zwnj;' => '&#8204;', '&zwj;' => '&#8205;', '&lrm;' => '&#8206;', '&rlm;' => '&#8207;', '&ndash;' => '&#8211;', '&mdash;' => '&#8212;', '&lsquo;' => '&#8216;', '&rsquo;' => '&#8217;', '&sbquo;' => '&#8218;', '&ldquo;' => '&#8220;', '&rdquo;' => '&#8221;', '&bdquo;' => '&#8222;', '&dagger;' => '&#8224;', '&Dagger;' => '&#8225;', '&bull;' => '&#8226;', '&hellip;' => '&#8230;', '&permil;' => '&#8240;', '&prime;' => '&#8242;', '&Prime;' => '&#8243;', '&lsaquo;' => '&#8249;', '&rsaquo;' => '&#8250;', '&oline;' => '&#8254;', '&frasl;' => '&#8260;', '&euro;' => '&#8364;', '&image;' => '&#8465;', '&weierp;' => '&#8472;', '&real;' => '&#8476;', '&trade;' => '&#8482;', '&alefsym;' => '&#8501;', '&crarr;' => '&#8629;', '&lArr;' => '&#8656;', '&uArr;' => '&#8657;', '&rArr;' => '&#8658;', '&dArr;' => '&#8659;', '&hArr;' => '&#8660;', '&forall;' => '&#8704;', '&part;' => '&#8706;', '&exist;' => '&#8707;', '&empty;' => '&#8709;', '&nabla;' => '&#8711;', '&isin;' => '&#8712;', '&notin;' => '&#8713;', '&ni;' => '&#8715;', '&prod;' => '&#8719;', '&sum;' => '&#8721;', '&minus;' => '&#8722;', '&lowast;' => '&#8727;', '&radic;' => '&#8730;', '&prop;' => '&#8733;', '&infin;' => '&#8734;', '&ang;' => '&#8736;', '&and;' => '&#8743;', '&or;' => '&#8744;', '&cap;' => '&#8745;', '&cup;' => '&#8746;', '&int;' => '&#8747;', '&there4;' => '&#8756;', '&sim;' => '&#8764;', '&cong;' => '&#8773;', '&asymp;' => '&#8776;', '&ne;' => '&#8800;', '&equiv;' => '&#8801;', '&le;' => '&#8804;', '&ge;' => '&#8805;', '&sub;' => '&#8834;', '&sup;' => '&#8835;', '&nsub;' => '&#8836;', '&sube;' => '&#8838;', '&supe;' => '&#8839;', '&oplus;' => '&#8853;', '&otimes;' => '&#8855;', '&perp;' => '&#8869;', '&sdot;' => '&#8901;', '&lceil;' => '&#8968;', '&rceil;' => '&#8969;', '&lfloor;' => '&#8970;', '&rfloor;' => '&#8971;', '&lang;' => '&#9001;', '&rang;' => '&#9002;', '&larr;' => '&#8592;', '&uarr;' => '&#8593;', '&rarr;' => '&#8594;', '&darr;' => '&#8595;', '&harr;' => '&#8596;', '&loz;' => '&#9674;', '&spades;' => '&#9824;', '&clubs;' => '&#9827;', '&hearts;' => '&#9829;', '&diams;' => '&#9830;' ); return str_replace( array_keys($to_ncr), array_values($to_ncr), $text ); } /** * Formats text for the rich text editor. * * The filter 'richedit_pre' is applied here. If $text is empty the filter will * be applied to an empty string. * * @since 2.0.0 * * @param string $text The text to be formatted. * @return string The formatted text after filter is applied. */ function wp_richedit_pre($text) { // Filtering a blank results in an annoying <br />\n if ( empty($text) ) return apply_filters('richedit_pre', ''); $output = convert_chars($text); $output = wpautop($output); $output = htmlspecialchars($output, ENT_NOQUOTES); return apply_filters('richedit_pre', $output); } /** * Formats text for the HTML editor. * * Unless $output is empty it will pass through htmlspecialchars before the * 'htmledit_pre' filter is applied. * * @since 2.5.0 * * @param string $output The text to be formatted. * @return string Formatted text after filter applied. */ function wp_htmledit_pre($output) { if ( !empty($output) ) $output = htmlspecialchars($output, ENT_NOQUOTES); // convert only < > & return apply_filters('htmledit_pre', $output); } /** * Perform a deep string replace operation to ensure the values in $search are no longer present * * Repeats the replacement operation until it no longer replaces anything so as to remove "nested" values * e.g. $subject = '%0%0%0DDD', $search ='%0D', $result ='' rather than the '%0%0DD' that * str_replace would return * * @since 2.8.1 * @access private * * @param string|array $search * @param string $subject * @return string The processed string */ function _deep_replace( $search, $subject ) { $found = true; $subject = (string) $subject; while ( $found ) { $found = false; foreach ( (array) $search as $val ) { while ( strpos( $subject, $val ) !== false ) { $found = true; $subject = str_replace( $val, '', $subject ); } } } return $subject; } /** * Escapes data for use in a MySQL query * * This is just a handy shortcut for $wpdb->escape(), for completeness' sake * * @since 2.8.0 * @param string $sql Unescaped SQL data * @return string The cleaned $sql */ function esc_sql( $sql ) { global $wpdb; return $wpdb->escape( $sql ); } /** * Checks and cleans a URL. * * A number of characters are removed from the URL. If the URL is for displaying * (the default behaviour) ampersands are also replaced. The 'clean_url' filter * is applied to the returned cleaned URL. * * @since 2.8.0 * @uses wp_kses_bad_protocol() To only permit protocols in the URL set * via $protocols or the common ones set in the function. * * @param string $url The URL to be cleaned. * @param array $protocols Optional. An array of acceptable protocols. * Defaults to 'http', 'https', 'ftp', 'ftps', 'mailto', 'news', 'irc', 'gopher', 'nntp', 'feed', 'telnet', 'mms', 'rtsp', 'svn' if not set. * @param string $_context Private. Use esc_url_raw() for database usage. * @return string The cleaned $url after the 'clean_url' filter is applied. */ function esc_url( $url, $protocols = null, $_context = 'display' ) { $original_url = $url; if ( '' == $url ) return $url; $url = preg_replace('|[^a-z0-9-~+_.?#=!&;,/:%@$\|*\'()\\x80-\\xff]|i', '', $url); $strip = array('%0d', '%0a', '%0D', '%0A'); $url = _deep_replace($strip, $url); $url = str_replace(';//', '://', $url); /* If the URL doesn't appear to contain a scheme, we * presume it needs http:// appended (unless a relative * link starting with /, # or ? or a php file). */ if ( strpos($url, ':') === false && ! in_array( $url[0], array( '/', '#', '?' ) ) && ! preg_match('/^[a-z0-9-]+?\.php/i', $url) ) $url = 'http://' . $url; // Replace ampersands and single quotes only when displaying. if ( 'display' == $_context ) { $url = wp_kses_normalize_entities( $url ); $url = str_replace( '&amp;', '&#038;', $url ); $url = str_replace( "'", '&#039;', $url ); } if ( ! is_array( $protocols ) ) $protocols = wp_allowed_protocols(); if ( wp_kses_bad_protocol( $url, $protocols ) != $url ) return ''; return apply_filters('clean_url', $url, $original_url, $_context); } /** * Performs esc_url() for database usage. * * @since 2.8.0 * @uses esc_url() * * @param string $url The URL to be cleaned. * @param array $protocols An array of acceptable protocols. * @return string The cleaned URL. */ function esc_url_raw( $url, $protocols = null ) { return esc_url( $url, $protocols, 'db' ); } /** * Convert entities, while preserving already-encoded entities. * * @link http://www.php.net/htmlentities Borrowed from the PHP Manual user notes. * * @since 1.2.2 * * @param string $myHTML The text to be converted. * @return string Converted text. */ function htmlentities2($myHTML) { $translation_table = get_html_translation_table( HTML_ENTITIES, ENT_QUOTES ); $translation_table[chr(38)] = '&'; return preg_replace( "/&(?![A-Za-z]{0,4}\w{2,3};|#[0-9]{2,3};)/", "&amp;", strtr($myHTML, $translation_table) ); } /** * Escape single quotes, htmlspecialchar " < > &, and fix line endings. * * Escapes text strings for echoing in JS. It is intended to be used for inline JS * (in a tag attribute, for example onclick="..."). Note that the strings have to * be in single quotes. The filter 'js_escape' is also applied here. * * @since 2.8.0 * * @param string $text The text to be escaped. * @return string Escaped text. */ function esc_js( $text ) { $safe_text = wp_check_invalid_utf8( $text ); $safe_text = _wp_specialchars( $safe_text, ENT_COMPAT ); $safe_text = preg_replace( '/&#(x)?0*(?(1)27|39);?/i', "'", stripslashes( $safe_text ) ); $safe_text = str_replace( "\r", '', $safe_text ); $safe_text = str_replace( "\n", '\\n', addslashes( $safe_text ) ); return apply_filters( 'js_escape', $safe_text, $text ); } /** * Escaping for HTML blocks. * * @since 2.8.0 * * @param string $text * @return string */ function esc_html( $text ) { $safe_text = wp_check_invalid_utf8( $text ); $safe_text = _wp_specialchars( $safe_text, ENT_QUOTES ); return apply_filters( 'esc_html', $safe_text, $text ); } /** * Escaping for HTML attributes. * * @since 2.8.0 * * @param string $text * @return string */ function esc_attr( $text ) { $safe_text = wp_check_invalid_utf8( $text ); $safe_text = _wp_specialchars( $safe_text, ENT_QUOTES ); return apply_filters( 'attribute_escape', $safe_text, $text ); } /** * Escaping for textarea values. * * @since 3.1 * * @param string $text * @return string */ function esc_textarea( $text ) { $safe_text = htmlspecialchars( $text, ENT_QUOTES ); return apply_filters( 'esc_textarea', $safe_text, $text ); } /** * Escape a HTML tag name. * * @since 2.5.0 * * @param string $tag_name * @return string */ function tag_escape($tag_name) { $safe_tag = strtolower( preg_replace('/[^a-zA-Z0-9_:]/', '', $tag_name) ); return apply_filters('tag_escape', $safe_tag, $tag_name); } /** * Escapes text for SQL LIKE special characters % and _. * * @since 2.5.0 * * @param string $text The text to be escaped. * @return string text, safe for inclusion in LIKE query. */ function like_escape($text) { return str_replace(array("%", "_"), array("\\%", "\\_"), $text); } /** * Convert full URL paths to absolute paths. * * Removes the http or https protocols and the domain. Keeps the path '/' at the * beginning, so it isn't a true relative link, but from the web root base. * * @since 2.1.0 * * @param string $link Full URL path. * @return string Absolute path. */ function wp_make_link_relative( $link ) { return preg_replace( '|https?://[^/]+(/.*)|i', '$1', $link ); } /** * Sanitises various option values based on the nature of the option. * * This is basically a switch statement which will pass $value through a number * of functions depending on the $option. * * @since 2.0.5 * * @param string $option The name of the option. * @param string $value The unsanitised value. * @return string Sanitized value. */ function sanitize_option($option, $value) { switch ( $option ) { case 'admin_email' : case 'new_admin_email' : $value = sanitize_email( $value ); if ( ! is_email( $value ) ) { $value = get_option( $option ); // Resets option to stored value in the case of failed sanitization if ( function_exists( 'add_settings_error' ) ) add_settings_error( $option, 'invalid_admin_email', __( 'The email address entered did not appear to be a valid email address. Please enter a valid email address.' ) ); } break; case 'thumbnail_size_w': case 'thumbnail_size_h': case 'medium_size_w': case 'medium_size_h': case 'large_size_w': case 'large_size_h': case 'mailserver_port': case 'comment_max_links': case 'page_on_front': case 'page_for_posts': case 'rss_excerpt_length': case 'default_category': case 'default_email_category': case 'default_link_category': case 'close_comments_days_old': case 'comments_per_page': case 'thread_comments_depth': case 'users_can_register': case 'start_of_week': $value = absint( $value ); break; case 'posts_per_page': case 'posts_per_rss': $value = (int) $value; if ( empty($value) ) $value = 1; if ( $value < -1 ) $value = abs($value); break; case 'default_ping_status': case 'default_comment_status': // Options that if not there have 0 value but need to be something like "closed" if ( $value == '0' || $value == '') $value = 'closed'; break; case 'blogdescription': case 'blogname': $value = wp_kses_post( $value ); $value = esc_html( $value ); break; case 'blog_charset': $value = preg_replace('/[^a-zA-Z0-9_-]/', '', $value); // strips slashes break; case 'blog_public': // This is the value if the settings checkbox is not checked on POST. Don't rely on this. if ( null === $value ) $value = 1; else $value = intval( $value ); break; case 'date_format': case 'time_format': case 'mailserver_url': case 'mailserver_login': case 'mailserver_pass': case 'upload_path': $value = strip_tags( $value ); $value = wp_kses_data( $value ); break; case 'ping_sites': $value = explode( "\n", $value ); $value = array_filter( array_map( 'trim', $value ) ); $value = array_filter( array_map( 'esc_url_raw', $value ) ); $value = implode( "\n", $value ); break; case 'gmt_offset': $value = preg_replace('/[^0-9:.-]/', '', $value); // strips slashes break; case 'siteurl': if ( (bool)preg_match( '#http(s?)://(.+)#i', $value) ) { $value = esc_url_raw($value); } else { $value = get_option( $option ); // Resets option to stored value in the case of failed sanitization if ( function_exists('add_settings_error') ) add_settings_error('siteurl', 'invalid_siteurl', __('The WordPress address you entered did not appear to be a valid URL. Please enter a valid URL.')); } break; case 'home': if ( (bool)preg_match( '#http(s?)://(.+)#i', $value) ) { $value = esc_url_raw($value); } else { $value = get_option( $option ); // Resets option to stored value in the case of failed sanitization if ( function_exists('add_settings_error') ) add_settings_error('home', 'invalid_home', __('The Site address you entered did not appear to be a valid URL. Please enter a valid URL.')); } break; case 'WPLANG': $allowed = get_available_languages(); if ( ! in_array( $value, $allowed ) && ! empty( $value ) ) $value = get_option( $option ); break; case 'illegal_names': if ( ! is_array( $value ) ) $value = explode( "\n", $value ); $value = array_values( array_filter( array_map( 'trim', $value ) ) ); if ( ! $value ) $value = ''; break; case 'limited_email_domains': case 'banned_email_domains': if ( ! is_array( $value ) ) $value = explode( "\n", $value ); $domains = array_values( array_filter( array_map( 'trim', $value ) ) ); $value = array(); foreach ( $domains as $domain ) { if ( ! preg_match( '/(--|\.\.)/', $domain ) && preg_match( '|^([a-zA-Z0-9-\.])+$|', $domain ) ) $value[] = $domain; } if ( ! $value ) $value = ''; break; case 'timezone_string': $allowed_zones = timezone_identifiers_list(); if ( ! in_array( $value, $allowed_zones ) && ! empty( $value ) ) { $value = get_option( $option ); // Resets option to stored value in the case of failed sanitization if ( function_exists('add_settings_error') ) add_settings_error('timezone_string', 'invalid_timezone_string', __('The timezone you have entered is not valid. Please select a valid timezone.') ); } break; case 'permalink_structure': case 'category_base': case 'tag_base': $value = esc_url_raw( $value ); $value = str_replace( 'http://', '', $value ); break; } $value = apply_filters("sanitize_option_{$option}", $value, $option); return $value; } /** * Parses a string into variables to be stored in an array. * * Uses {@link http://www.php.net/parse_str parse_str()} and stripslashes if * {@link http://www.php.net/magic_quotes magic_quotes_gpc} is on. * * @since 2.2.1 * @uses apply_filters() for the 'wp_parse_str' filter. * * @param string $string The string to be parsed. * @param array $array Variables will be stored in this array. */ function wp_parse_str( $string, &$array ) { parse_str( $string, $array ); if ( get_magic_quotes_gpc() ) $array = stripslashes_deep( $array ); $array = apply_filters( 'wp_parse_str', $array ); } /** * Convert lone less than signs. * * KSES already converts lone greater than signs. * * @uses wp_pre_kses_less_than_callback in the callback function. * @since 2.3.0 * * @param string $text Text to be converted. * @return string Converted text. */ function wp_pre_kses_less_than( $text ) { return preg_replace_callback('%<[^>]*?((?=<)|>|$)%', 'wp_pre_kses_less_than_callback', $text); } /** * Callback function used by preg_replace. * * @uses esc_html to format the $matches text. * @since 2.3.0 * * @param array $matches Populated by matches to preg_replace. * @return string The text returned after esc_html if needed. */ function wp_pre_kses_less_than_callback( $matches ) { if ( false === strpos($matches[0], '>') ) return esc_html($matches[0]); return $matches[0]; } /** * WordPress implementation of PHP sprintf() with filters. * * @since 2.5.0 * @link http://www.php.net/sprintf * * @param string $pattern The string which formatted args are inserted. * @param mixed $args,... Arguments to be formatted into the $pattern string. * @return string The formatted string. */ function wp_sprintf( $pattern ) { $args = func_get_args( ); $len = strlen($pattern); $start = 0; $result = ''; $arg_index = 0; while ( $len > $start ) { // Last character: append and break if ( strlen($pattern) - 1 == $start ) { $result .= substr($pattern, -1); break; } // Literal %: append and continue if ( substr($pattern, $start, 2) == '%%' ) { $start += 2; $result .= '%'; continue; } // Get fragment before next % $end = strpos($pattern, '%', $start + 1); if ( false === $end ) $end = $len; $fragment = substr($pattern, $start, $end - $start); // Fragment has a specifier if ( $pattern[$start] == '%' ) { // Find numbered arguments or take the next one in order if ( preg_match('/^%(\d+)\$/', $fragment, $matches) ) { $arg = isset($args[$matches[1]]) ? $args[$matches[1]] : ''; $fragment = str_replace("%{$matches[1]}$", '%', $fragment); } else { ++$arg_index; $arg = isset($args[$arg_index]) ? $args[$arg_index] : ''; } // Apply filters OR sprintf $_fragment = apply_filters( 'wp_sprintf', $fragment, $arg ); if ( $_fragment != $fragment ) $fragment = $_fragment; else $fragment = sprintf($fragment, strval($arg) ); } // Append to result and move to next fragment $result .= $fragment; $start = $end; } return $result; } /** * Localize list items before the rest of the content. * * The '%l' must be at the first characters can then contain the rest of the * content. The list items will have ', ', ', and', and ' and ' added depending * on the amount of list items in the $args parameter. * * @since 2.5.0 * * @param string $pattern Content containing '%l' at the beginning. * @param array $args List items to prepend to the content and replace '%l'. * @return string Localized list items and rest of the content. */ function wp_sprintf_l($pattern, $args) { // Not a match if ( substr($pattern, 0, 2) != '%l' ) return $pattern; // Nothing to work with if ( empty($args) ) return ''; // Translate and filter the delimiter set (avoid ampersands and entities here) $l = apply_filters('wp_sprintf_l', array( /* translators: used between list items, there is a space after the comma */ 'between' => __(', '), /* translators: used between list items, there is a space after the and */ 'between_last_two' => __(', and '), /* translators: used between only two list items, there is a space after the and */ 'between_only_two' => __(' and '), )); $args = (array) $args; $result = array_shift($args); if ( count($args) == 1 ) $result .= $l['between_only_two'] . array_shift($args); // Loop when more than two args $i = count($args); while ( $i ) { $arg = array_shift($args); $i--; if ( 0 == $i ) $result .= $l['between_last_two'] . $arg; else $result .= $l['between'] . $arg; } return $result . substr($pattern, 2); } /** * Safely extracts not more than the first $count characters from html string. * * UTF-8, tags and entities safe prefix extraction. Entities inside will *NOT* * be counted as one character. For example &amp; will be counted as 4, &lt; as * 3, etc. * * @since 2.5.0 * * @param integer $str String to get the excerpt from. * @param integer $count Maximum number of characters to take. * @return string The excerpt. */ function wp_html_excerpt( $str, $count ) { $str = wp_strip_all_tags( $str, true ); $str = mb_substr( $str, 0, $count ); // remove part of an entity at the end $str = preg_replace( '/&[^;\s]{0,6}$/', '', $str ); return $str; } /** * Add a Base url to relative links in passed content. * * By default it supports the 'src' and 'href' attributes. However this can be * changed via the 3rd param. * * @since 2.7.0 * * @param string $content String to search for links in. * @param string $base The base URL to prefix to links. * @param array $attrs The attributes which should be processed. * @return string The processed content. */ function links_add_base_url( $content, $base, $attrs = array('src', 'href') ) { global $_links_add_base; $_links_add_base = $base; $attrs = implode('|', (array)$attrs); return preg_replace_callback( "!($attrs)=(['\"])(.+?)\\2!i", '_links_add_base', $content ); } /** * Callback to add a base url to relative links in passed content. * * @since 2.7.0 * @access private * * @param string $m The matched link. * @return string The processed link. */ function _links_add_base($m) { global $_links_add_base; //1 = attribute name 2 = quotation mark 3 = URL return $m[1] . '=' . $m[2] . ( preg_match( '#^(\w{1,20}):#', $m[3], $protocol ) && in_array( $protocol[1], wp_allowed_protocols() ) ? $m[3] : path_join( $_links_add_base, $m[3] ) ) . $m[2]; } /** * Adds a Target attribute to all links in passed content. * * This function by default only applies to <a> tags, however this can be * modified by the 3rd param. * * <b>NOTE:</b> Any current target attributed will be stripped and replaced. * * @since 2.7.0 * * @param string $content String to search for links in. * @param string $target The Target to add to the links. * @param array $tags An array of tags to apply to. * @return string The processed content. */ function links_add_target( $content, $target = '_blank', $tags = array('a') ) { global $_links_add_target; $_links_add_target = $target; $tags = implode('|', (array)$tags); return preg_replace_callback( "!<($tags)(.+?)>!i", '_links_add_target', $content ); } /** * Callback to add a target attribute to all links in passed content. * * @since 2.7.0 * @access private * * @param string $m The matched link. * @return string The processed link. */ function _links_add_target( $m ) { global $_links_add_target; $tag = $m[1]; $link = preg_replace('|(target=[\'"](.*?)[\'"])|i', '', $m[2]); return '<' . $tag . $link . ' target="' . esc_attr( $_links_add_target ) . '">'; } // normalize EOL characters and strip duplicate whitespace function normalize_whitespace( $str ) { $str = trim($str); $str = str_replace("\r", "\n", $str); $str = preg_replace( array( '/\n+/', '/[ \t]+/' ), array( "\n", ' ' ), $str ); return $str; } /** * Properly strip all HTML tags including script and style * * @since 2.9.0 * * @param string $string String containing HTML tags * @param bool $remove_breaks optional Whether to remove left over line breaks and white space chars * @return string The processed string. */ function wp_strip_all_tags($string, $remove_breaks = false) { $string = preg_replace( '@<(script|style)[^>]*?>.*?</\\1>@si', '', $string ); $string = strip_tags($string); if ( $remove_breaks ) $string = preg_replace('/[\r\n\t ]+/', ' ', $string); return trim( $string ); } /** * Sanitize a string from user input or from the db * * check for invalid UTF-8, * Convert single < characters to entity, * strip all tags, * remove line breaks, tabs and extra white space, * strip octets. * * @since 2.9.0 * * @param string $str * @return string */ function sanitize_text_field($str) { $filtered = wp_check_invalid_utf8( $str ); if ( strpos($filtered, '<') !== false ) { $filtered = wp_pre_kses_less_than( $filtered ); // This will strip extra whitespace for us. $filtered = wp_strip_all_tags( $filtered, true ); } else { $filtered = trim( preg_replace('/[\r\n\t ]+/', ' ', $filtered) ); } $match = array(); $found = false; while ( preg_match('/%[a-f0-9]{2}/i', $filtered, $match) ) { $filtered = str_replace($match[0], '', $filtered); $found = true; } if ( $found ) { // Strip out the whitespace that may now exist after removing the octets. $filtered = trim( preg_replace('/ +/', ' ', $filtered) ); } return apply_filters('sanitize_text_field', $filtered, $str); } /** * i18n friendly version of basename() * * @since 3.1.0 * * @param string $path A path. * @param string $suffix If the filename ends in suffix this will also be cut off. * @return string */ function wp_basename( $path, $suffix = '' ) { return urldecode( basename( str_replace( array( '%2F', '%5C' ), '/', urlencode( $path ) ), $suffix ) ); } /** * Forever eliminate "Wordpress" from the planet (or at least the little bit we can influence). * * Violating our coding standards for a good function name. * * @since 3.0.0 */ function capital_P_dangit( $text ) { // Simple replacement for titles if ( 'the_title' === current_filter() ) return str_replace( 'Wordpress', 'WordPress', $text ); // Still here? Use the more judicious replacement static $dblq = false; if ( false === $dblq ) $dblq = _x( '&#8220;', 'opening curly double quote' ); return str_replace( array( ' Wordpress', '&#8216;Wordpress', $dblq . 'Wordpress', '>Wordpress', '(Wordpress' ), array( ' WordPress', '&#8216;WordPress', $dblq . 'WordPress', '>WordPress', '(WordPress' ), $text ); } /** * Sanitize a mime type * * @since 3.1.3 * * @param string $mime_type Mime type * @return string Sanitized mime type */ function sanitize_mime_type( $mime_type ) { $sani_mime_type = preg_replace( '/[^-+*.a-zA-Z0-9\/]/', '', $mime_type ); return apply_filters( 'sanitize_mime_type', $sani_mime_type, $mime_type ); } /** * Sanitize space or carriage return separated URLs that are used to send trackbacks. * * @since 3.4.0 * * @param string $to_ping Space or carriage return separated URLs * @return string URLs starting with the http or https protocol, separated by a carriage return. */ function sanitize_trackback_urls( $to_ping ) { $urls_to_ping = preg_split( '/[\r\n\t ]/', trim( $to_ping ), -1, PREG_SPLIT_NO_EMPTY ); foreach ( $urls_to_ping as $k => $url ) { if ( !preg_match( '#^https?://.#i', $url ) ) unset( $urls_to_ping[$k] ); } $urls_to_ping = array_map( 'esc_url_raw', $urls_to_ping ); $urls_to_ping = implode( "\n", $urls_to_ping ); return apply_filters( 'sanitize_trackback_urls', $urls_to_ping, $to_ping ); }
zyblog
trunk/zyblog/wp-includes/formatting.php
PHP
asf20
109,954
<?php /** * Admin Bar * * This code handles the building and rendering of the press bar. */ /** * Instantiate the admin bar object and set it up as a global for access elsewhere. * * To hide the admin bar, you're looking in the wrong place. Unhooking this function will not * properly remove the admin bar. For that, use show_admin_bar(false) or the show_admin_bar filter. * * @since 3.1.0 * @access private * @return bool Whether the admin bar was successfully initialized. */ function _wp_admin_bar_init() { global $wp_admin_bar; if ( ! is_admin_bar_showing() ) return false; /* Load the admin bar class code ready for instantiation */ require( ABSPATH . WPINC . '/class-wp-admin-bar.php' ); /* Instantiate the admin bar */ $admin_bar_class = apply_filters( 'wp_admin_bar_class', 'WP_Admin_Bar' ); if ( class_exists( $admin_bar_class ) ) $wp_admin_bar = new $admin_bar_class; else return false; $wp_admin_bar->initialize(); $wp_admin_bar->add_menus(); return true; } add_action( 'init', '_wp_admin_bar_init' ); // Don't remove. Wrong way to disable. /** * Render the admin bar to the page based on the $wp_admin_bar->menu member var. * This is called very late on the footer actions so that it will render after anything else being * added to the footer. * * It includes the action "admin_bar_menu" which should be used to hook in and * add new menus to the admin bar. That way you can be sure that you are adding at most optimal point, * right before the admin bar is rendered. This also gives you access to the $post global, among others. * * @since 3.1.0 */ function wp_admin_bar_render() { global $wp_admin_bar; if ( ! is_admin_bar_showing() || ! is_object( $wp_admin_bar ) ) return false; do_action_ref_array( 'admin_bar_menu', array( &$wp_admin_bar ) ); do_action( 'wp_before_admin_bar_render' ); $wp_admin_bar->render(); do_action( 'wp_after_admin_bar_render' ); } add_action( 'wp_footer', 'wp_admin_bar_render', 1000 ); add_action( 'in_admin_header', 'wp_admin_bar_render', 0 ); /** * Add the WordPress logo menu. * * @since 3.3.0 */ function wp_admin_bar_wp_menu( $wp_admin_bar ) { $wp_admin_bar->add_menu( array( 'id' => 'wp-logo', 'title' => '<span class="ab-icon"></span>', 'href' => self_admin_url( 'about.php' ), 'meta' => array( 'title' => __('About WordPress'), ), ) ); if ( is_user_logged_in() ) { // Add "About WordPress" link $wp_admin_bar->add_menu( array( 'parent' => 'wp-logo', 'id' => 'about', 'title' => __('About WordPress'), 'href' => self_admin_url( 'about.php' ), ) ); } // Add WordPress.org link $wp_admin_bar->add_menu( array( 'parent' => 'wp-logo-external', 'id' => 'wporg', 'title' => __('WordPress.org'), 'href' => __('http://wordpress.org/'), ) ); // Add codex link $wp_admin_bar->add_menu( array( 'parent' => 'wp-logo-external', 'id' => 'documentation', 'title' => __('Documentation'), 'href' => __('http://codex.wordpress.org/'), ) ); // Add forums link $wp_admin_bar->add_menu( array( 'parent' => 'wp-logo-external', 'id' => 'support-forums', 'title' => __('Support Forums'), 'href' => __('http://wordpress.org/support/'), ) ); // Add feedback link $wp_admin_bar->add_menu( array( 'parent' => 'wp-logo-external', 'id' => 'feedback', 'title' => __('Feedback'), 'href' => __('http://wordpress.org/support/forum/requests-and-feedback'), ) ); } /** * Add the "My Account" item. * * @since 3.3.0 */ function wp_admin_bar_my_account_item( $wp_admin_bar ) { $user_id = get_current_user_id(); $current_user = wp_get_current_user(); $profile_url = get_edit_profile_url( $user_id ); if ( ! $user_id ) return; $avatar = get_avatar( $user_id, 16 ); $howdy = sprintf( __('Howdy, %1$s'), $current_user->display_name ); $class = empty( $avatar ) ? '' : 'with-avatar'; $wp_admin_bar->add_menu( array( 'id' => 'my-account', 'parent' => 'top-secondary', 'title' => $howdy . $avatar, 'href' => $profile_url, 'meta' => array( 'class' => $class, 'title' => __('My Account'), ), ) ); } /** * Add the "My Account" submenu items. * * @since 3.1.0 */ function wp_admin_bar_my_account_menu( $wp_admin_bar ) { $user_id = get_current_user_id(); $current_user = wp_get_current_user(); $profile_url = get_edit_profile_url( $user_id ); if ( ! $user_id ) return; $wp_admin_bar->add_group( array( 'parent' => 'my-account', 'id' => 'user-actions', ) ); $user_info = get_avatar( $user_id, 64 ); $user_info .= "<span class='display-name'>{$current_user->display_name}</span>"; if ( $current_user->display_name !== $current_user->user_nicename ) $user_info .= "<span class='username'>{$current_user->user_nicename}</span>"; $wp_admin_bar->add_menu( array( 'parent' => 'user-actions', 'id' => 'user-info', 'title' => $user_info, 'href' => $profile_url, 'meta' => array( 'tabindex' => -1, ), ) ); $wp_admin_bar->add_menu( array( 'parent' => 'user-actions', 'id' => 'edit-profile', 'title' => __( 'Edit My Profile' ), 'href' => $profile_url, ) ); $wp_admin_bar->add_menu( array( 'parent' => 'user-actions', 'id' => 'logout', 'title' => __( 'Log Out' ), 'href' => wp_logout_url(), ) ); } /** * Add the "Site Name" menu. * * @since 3.3.0 */ function wp_admin_bar_site_menu( $wp_admin_bar ) { global $current_site; // Don't show for logged out users. if ( ! is_user_logged_in() ) return; // Show only when the user is a member of this site, or they're a super admin. if ( ! is_user_member_of_blog() && ! is_super_admin() ) return; $blogname = get_bloginfo('name'); if ( empty( $blogname ) ) $blogname = preg_replace( '#^(https?://)?(www.)?#', '', get_home_url() ); if ( is_network_admin() ) { $blogname = sprintf( __('Network Admin: %s'), esc_html( $current_site->site_name ) ); } elseif ( is_user_admin() ) { $blogname = sprintf( __('Global Dashboard: %s'), esc_html( $current_site->site_name ) ); } $title = wp_html_excerpt( $blogname, 40 ); if ( $title != $blogname ) $title = trim( $title ) . '&hellip;'; $wp_admin_bar->add_menu( array( 'id' => 'site-name', 'title' => $title, 'href' => is_admin() ? home_url( '/' ) : admin_url(), ) ); // Create submenu items. if ( is_admin() ) { // Add an option to visit the site. $wp_admin_bar->add_menu( array( 'parent' => 'site-name', 'id' => 'view-site', 'title' => __( 'Visit Site' ), 'href' => home_url( '/' ), ) ); if ( is_blog_admin() && is_multisite() && current_user_can( 'manage_sites' ) ) { $wp_admin_bar->add_menu( array( 'parent' => 'site-name', 'id' => 'edit-site', 'title' => __( 'Edit Site' ), 'href' => network_admin_url( 'site-info.php?id=' . get_current_blog_id() ), ) ); } } else { // We're on the front end, link to the Dashboard. $wp_admin_bar->add_menu( array( 'parent' => 'site-name', 'id' => 'dashboard', 'title' => __( 'Dashboard' ), 'href' => admin_url(), ) ); // Add the appearance submenu items. wp_admin_bar_appearance_menu( $wp_admin_bar ); } } /** * Add the "My Sites/[Site Name]" menu and all submenus. * * @since 3.1.0 */ function wp_admin_bar_my_sites_menu( $wp_admin_bar ) { global $wpdb; // Don't show for logged out users or single site mode. if ( ! is_user_logged_in() || ! is_multisite() ) return; // Show only when the user has at least one site, or they're a super admin. if ( count( $wp_admin_bar->user->blogs ) < 1 && ! is_super_admin() ) return; $wp_admin_bar->add_menu( array( 'id' => 'my-sites', 'title' => __( 'My Sites' ), 'href' => admin_url( 'my-sites.php' ), ) ); if ( is_super_admin() ) { $wp_admin_bar->add_group( array( 'parent' => 'my-sites', 'id' => 'my-sites-super-admin', ) ); $wp_admin_bar->add_menu( array( 'parent' => 'my-sites-super-admin', 'id' => 'network-admin', 'title' => __('Network Admin'), 'href' => network_admin_url(), ) ); $wp_admin_bar->add_menu( array( 'parent' => 'network-admin', 'id' => 'network-admin-d', 'title' => __( 'Dashboard' ), 'href' => network_admin_url(), ) ); $wp_admin_bar->add_menu( array( 'parent' => 'network-admin', 'id' => 'network-admin-s', 'title' => __( 'Sites' ), 'href' => network_admin_url( 'sites.php' ), ) ); $wp_admin_bar->add_menu( array( 'parent' => 'network-admin', 'id' => 'network-admin-u', 'title' => __( 'Users' ), 'href' => network_admin_url( 'users.php' ), ) ); $wp_admin_bar->add_menu( array( 'parent' => 'network-admin', 'id' => 'network-admin-v', 'title' => __( 'Visit Network' ), 'href' => network_home_url(), ) ); } // Add site links $wp_admin_bar->add_group( array( 'parent' => 'my-sites', 'id' => 'my-sites-list', 'meta' => array( 'class' => is_super_admin() ? 'ab-sub-secondary' : '', ), ) ); foreach ( (array) $wp_admin_bar->user->blogs as $blog ) { switch_to_blog( $blog->userblog_id ); $blavatar = '<div class="blavatar"></div>'; $blogname = empty( $blog->blogname ) ? $blog->domain : $blog->blogname; $menu_id = 'blog-' . $blog->userblog_id; $wp_admin_bar->add_menu( array( 'parent' => 'my-sites-list', 'id' => $menu_id, 'title' => $blavatar . $blogname, 'href' => admin_url(), ) ); $wp_admin_bar->add_menu( array( 'parent' => $menu_id, 'id' => $menu_id . '-d', 'title' => __( 'Dashboard' ), 'href' => admin_url(), ) ); if ( current_user_can( get_post_type_object( 'post' )->cap->create_posts ) ) { $wp_admin_bar->add_menu( array( 'parent' => $menu_id, 'id' => $menu_id . '-n', 'title' => __( 'New Post' ), 'href' => admin_url( 'post-new.php' ), ) ); } if ( current_user_can( 'edit_posts' ) ) { $wp_admin_bar->add_menu( array( 'parent' => $menu_id, 'id' => $menu_id . '-c', 'title' => __( 'Manage Comments' ), 'href' => admin_url( 'edit-comments.php' ), ) ); } $wp_admin_bar->add_menu( array( 'parent' => $menu_id, 'id' => $menu_id . '-v', 'title' => __( 'Visit Site' ), 'href' => home_url( '/' ), ) ); restore_current_blog(); } } /** * Provide a shortlink. * * @since 3.1.0 */ function wp_admin_bar_shortlink_menu( $wp_admin_bar ) { $short = wp_get_shortlink( 0, 'query' ); $id = 'get-shortlink'; if ( empty( $short ) ) return; $html = '<input class="shortlink-input" type="text" readonly="readonly" value="' . esc_attr( $short ) . '" />'; $wp_admin_bar->add_menu( array( 'id' => $id, 'title' => __( 'Shortlink' ), 'href' => $short, 'meta' => array( 'html' => $html ), ) ); } /** * Provide an edit link for posts and terms. * * @since 3.1.0 */ function wp_admin_bar_edit_menu( $wp_admin_bar ) { global $tag, $wp_the_query; if ( is_admin() ) { $current_screen = get_current_screen(); $post = get_post(); if ( 'post' == $current_screen->base && 'add' != $current_screen->action && ( $post_type_object = get_post_type_object( $post->post_type ) ) && current_user_can( $post_type_object->cap->read_post, $post->ID ) && ( $post_type_object->public ) && ( $post_type_object->show_in_admin_bar ) ) { $wp_admin_bar->add_menu( array( 'id' => 'view', 'title' => $post_type_object->labels->view_item, 'href' => get_permalink( $post->ID ) ) ); } elseif ( 'edit-tags' == $current_screen->base && isset( $tag ) && is_object( $tag ) && ( $tax = get_taxonomy( $tag->taxonomy ) ) && $tax->public ) { $wp_admin_bar->add_menu( array( 'id' => 'view', 'title' => $tax->labels->view_item, 'href' => get_term_link( $tag ) ) ); } } else { $current_object = $wp_the_query->get_queried_object(); if ( empty( $current_object ) ) return; if ( ! empty( $current_object->post_type ) && ( $post_type_object = get_post_type_object( $current_object->post_type ) ) && current_user_can( $post_type_object->cap->edit_post, $current_object->ID ) && $post_type_object->show_ui && $post_type_object->show_in_admin_bar ) { $wp_admin_bar->add_menu( array( 'id' => 'edit', 'title' => $post_type_object->labels->edit_item, 'href' => get_edit_post_link( $current_object->ID ) ) ); } elseif ( ! empty( $current_object->taxonomy ) && ( $tax = get_taxonomy( $current_object->taxonomy ) ) && current_user_can( $tax->cap->edit_terms ) && $tax->show_ui ) { $wp_admin_bar->add_menu( array( 'id' => 'edit', 'title' => $tax->labels->edit_item, 'href' => get_edit_term_link( $current_object->term_id, $current_object->taxonomy ) ) ); } } } /** * Add "Add New" menu. * * @since 3.1.0 */ function wp_admin_bar_new_content_menu( $wp_admin_bar ) { $actions = array(); $cpts = (array) get_post_types( array( 'show_in_admin_bar' => true ), 'objects' ); if ( isset( $cpts['post'] ) && current_user_can( $cpts['post']->cap->create_posts ) ) $actions[ 'post-new.php' ] = array( $cpts['post']->labels->name_admin_bar, 'new-post' ); if ( isset( $cpts['attachment'] ) && current_user_can( 'upload_files' ) ) $actions[ 'media-new.php' ] = array( $cpts['attachment']->labels->name_admin_bar, 'new-media' ); if ( current_user_can( 'manage_links' ) ) $actions[ 'link-add.php' ] = array( _x( 'Link', 'add new from admin bar' ), 'new-link' ); if ( isset( $cpts['page'] ) && current_user_can( $cpts['page']->cap->create_posts ) ) $actions[ 'post-new.php?post_type=page' ] = array( $cpts['page']->labels->name_admin_bar, 'new-page' ); unset( $cpts['post'], $cpts['page'], $cpts['attachment'] ); // Add any additional custom post types. foreach ( $cpts as $cpt ) { if ( ! current_user_can( $cpt->cap->create_posts ) ) continue; $key = 'post-new.php?post_type=' . $cpt->name; $actions[ $key ] = array( $cpt->labels->name_admin_bar, 'new-' . $cpt->name ); } // Avoid clash with parent node and a 'content' post type. if ( isset( $actions['post-new.php?post_type=content'] ) ) $actions['post-new.php?post_type=content'][1] = 'add-new-content'; if ( current_user_can( 'create_users' ) || current_user_can( 'promote_users' ) ) $actions[ 'user-new.php' ] = array( _x( 'User', 'add new from admin bar' ), 'new-user' ); if ( ! $actions ) return; $title = '<span class="ab-icon"></span><span class="ab-label">' . _x( 'New', 'admin bar menu group label' ) . '</span>'; $wp_admin_bar->add_menu( array( 'id' => 'new-content', 'title' => $title, 'href' => admin_url( current( array_keys( $actions ) ) ), 'meta' => array( 'title' => _x( 'Add New', 'admin bar menu group label' ), ), ) ); foreach ( $actions as $link => $action ) { list( $title, $id ) = $action; $wp_admin_bar->add_menu( array( 'parent' => 'new-content', 'id' => $id, 'title' => $title, 'href' => admin_url( $link ) ) ); } } /** * Add edit comments link with awaiting moderation count bubble. * * @since 3.1.0 */ function wp_admin_bar_comments_menu( $wp_admin_bar ) { if ( !current_user_can('edit_posts') ) return; $awaiting_mod = wp_count_comments(); $awaiting_mod = $awaiting_mod->moderated; $awaiting_title = esc_attr( sprintf( _n( '%s comment awaiting moderation', '%s comments awaiting moderation', $awaiting_mod ), number_format_i18n( $awaiting_mod ) ) ); $icon = '<span class="ab-icon"></span>'; $title = '<span id="ab-awaiting-mod" class="ab-label awaiting-mod pending-count count-' . $awaiting_mod . '">' . number_format_i18n( $awaiting_mod ) . '</span>'; $wp_admin_bar->add_menu( array( 'id' => 'comments', 'title' => $icon . $title, 'href' => admin_url('edit-comments.php'), 'meta' => array( 'title' => $awaiting_title ), ) ); } /** * Add appearance submenu items to the "Site Name" menu. * * @since 3.1.0 */ function wp_admin_bar_appearance_menu( $wp_admin_bar ) { $wp_admin_bar->add_group( array( 'parent' => 'site-name', 'id' => 'appearance' ) ); if ( current_user_can( 'switch_themes' ) || current_user_can( 'edit_theme_options' ) ) $wp_admin_bar->add_menu( array( 'parent' => 'appearance', 'id' => 'themes', 'title' => __('Themes'), 'href' => admin_url('themes.php') ) ); if ( ! current_user_can( 'edit_theme_options' ) ) return; $current_url = ( is_ssl() ? 'https://' : 'http://' ) . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI']; $wp_admin_bar->add_menu( array( 'parent' => 'appearance', 'id' => 'customize', 'title' => __('Customize'), 'href' => add_query_arg( 'url', urlencode( $current_url ), wp_customize_url() ), 'meta' => array( 'class' => 'hide-if-no-customize', ), ) ); add_action( 'wp_before_admin_bar_render', 'wp_customize_support_script' ); if ( current_theme_supports( 'widgets' ) ) $wp_admin_bar->add_menu( array( 'parent' => 'appearance', 'id' => 'widgets', 'title' => __('Widgets'), 'href' => admin_url('widgets.php') ) ); if ( current_theme_supports( 'menus' ) || current_theme_supports( 'widgets' ) ) $wp_admin_bar->add_menu( array( 'parent' => 'appearance', 'id' => 'menus', 'title' => __('Menus'), 'href' => admin_url('nav-menus.php') ) ); if ( current_theme_supports( 'custom-background' ) ) $wp_admin_bar->add_menu( array( 'parent' => 'appearance', 'id' => 'background', 'title' => __('Background'), 'href' => admin_url('themes.php?page=custom-background') ) ); if ( current_theme_supports( 'custom-header' ) ) $wp_admin_bar->add_menu( array( 'parent' => 'appearance', 'id' => 'header', 'title' => __('Header'), 'href' => admin_url('themes.php?page=custom-header') ) ); } /** * Provide an update link if theme/plugin/core updates are available. * * @since 3.1.0 */ function wp_admin_bar_updates_menu( $wp_admin_bar ) { $update_data = wp_get_update_data(); if ( !$update_data['counts']['total'] ) return; $title = '<span class="ab-icon"></span><span class="ab-label">' . number_format_i18n( $update_data['counts']['total'] ) . '</span>'; $title .= '<span class="screen-reader-text">' . $update_data['title'] . '</span>'; $wp_admin_bar->add_menu( array( 'id' => 'updates', 'title' => $title, 'href' => network_admin_url( 'update-core.php' ), 'meta' => array( 'title' => $update_data['title'], ), ) ); } /** * Add search form. * * @since 3.3.0 */ function wp_admin_bar_search_menu( $wp_admin_bar ) { if ( is_admin() ) return; $form = '<form action="' . esc_url( home_url( '/' ) ) . '" method="get" id="adminbarsearch">'; $form .= '<input class="adminbar-input" name="s" id="adminbar-search" type="text" value="" maxlength="150" />'; $form .= '<input type="submit" class="adminbar-button" value="' . __('Search') . '"/>'; $form .= '</form>'; $wp_admin_bar->add_menu( array( 'parent' => 'top-secondary', 'id' => 'search', 'title' => $form, 'meta' => array( 'class' => 'admin-bar-search', 'tabindex' => -1, ) ) ); } /** * Add secondary menus. * * @since 3.3.0 */ function wp_admin_bar_add_secondary_groups( $wp_admin_bar ) { $wp_admin_bar->add_group( array( 'id' => 'top-secondary', 'meta' => array( 'class' => 'ab-top-secondary', ), ) ); $wp_admin_bar->add_group( array( 'parent' => 'wp-logo', 'id' => 'wp-logo-external', 'meta' => array( 'class' => 'ab-sub-secondary', ), ) ); } /** * Style and scripts for the admin bar. * * @since 3.1.0 * */ function wp_admin_bar_header() { ?> <style type="text/css" media="print">#wpadminbar { display:none; }</style> <?php } /** * Default admin bar callback. * * @since 3.1.0 * */ function _admin_bar_bump_cb() { ?> <style type="text/css" media="screen"> html { margin-top: 28px !important; } * html body { margin-top: 28px !important; } </style> <?php } /** * Set the display status of the admin bar. * * This can be called immediately upon plugin load. It does not need to be called from a function hooked to the init action. * * @since 3.1.0 * * @param bool $show Whether to allow the admin bar to show. * @return void */ function show_admin_bar( $show ) { global $show_admin_bar; $show_admin_bar = (bool) $show; } /** * Determine whether the admin bar should be showing. * * @since 3.1.0 * * @return bool Whether the admin bar should be showing. */ function is_admin_bar_showing() { global $show_admin_bar, $pagenow; // For all these types of requests, we never want an admin bar. if ( defined('XMLRPC_REQUEST') || defined('DOING_AJAX') || defined('IFRAME_REQUEST') ) return false; // Integrated into the admin. if ( is_admin() ) return true; if ( ! isset( $show_admin_bar ) ) { if ( ! is_user_logged_in() || 'wp-login.php' == $pagenow ) { $show_admin_bar = false; } else { $show_admin_bar = _get_admin_bar_pref(); } } $show_admin_bar = apply_filters( 'show_admin_bar', $show_admin_bar ); return $show_admin_bar; } /** * Retrieve the admin bar display preference of a user. * * @since 3.1.0 * @access private * * @param string $context Context of this preference check. Defaults to 'front'. The 'admin' * preference is no longer used. * @param int $user Optional. ID of the user to check, defaults to 0 for current user. * @return bool Whether the admin bar should be showing for this user. */ function _get_admin_bar_pref( $context = 'front', $user = 0 ) { $pref = get_user_option( "show_admin_bar_{$context}", $user ); if ( false === $pref ) return true; return 'true' === $pref; }
zyblog
trunk/zyblog/wp-includes/admin-bar.php
PHP
asf20
21,604
<?php if ( !class_exists('SimplePie') ) require_once (ABSPATH . WPINC . '/class-simplepie.php'); class WP_Feed_Cache extends SimplePie_Cache { /** * Create a new SimplePie_Cache object * * @static * @access public */ function create($location, $filename, $extension) { return new WP_Feed_Cache_Transient($location, $filename, $extension); } } class WP_Feed_Cache_Transient { var $name; var $mod_name; var $lifetime = 43200; //Default lifetime in cache of 12 hours function __construct($location, $filename, $extension) { $this->name = 'feed_' . $filename; $this->mod_name = 'feed_mod_' . $filename; $this->lifetime = apply_filters('wp_feed_cache_transient_lifetime', $this->lifetime, $filename); } function save($data) { if ( is_a($data, 'SimplePie') ) $data = $data->data; set_transient($this->name, $data, $this->lifetime); set_transient($this->mod_name, time(), $this->lifetime); return true; } function load() { return get_transient($this->name); } function mtime() { return get_transient($this->mod_name); } function touch() { return set_transient($this->mod_name, time(), $this->lifetime); } function unlink() { delete_transient($this->name); delete_transient($this->mod_name); return true; } } class WP_SimplePie_File extends SimplePie_File { function __construct($url, $timeout = 10, $redirects = 5, $headers = null, $useragent = null, $force_fsockopen = false) { $this->url = $url; $this->timeout = $timeout; $this->redirects = $redirects; $this->headers = $headers; $this->useragent = $useragent; $this->method = SIMPLEPIE_FILE_SOURCE_REMOTE; if ( preg_match('/^http(s)?:\/\//i', $url) ) { $args = array( 'timeout' => $this->timeout, 'redirection' => $this->redirects); if ( !empty($this->headers) ) $args['headers'] = $this->headers; if ( SIMPLEPIE_USERAGENT != $this->useragent ) //Use default WP user agent unless custom has been specified $args['user-agent'] = $this->useragent; $res = wp_remote_request($url, $args); if ( is_wp_error($res) ) { $this->error = 'WP HTTP Error: ' . $res->get_error_message(); $this->success = false; } else { $this->headers = wp_remote_retrieve_headers( $res ); $this->body = wp_remote_retrieve_body( $res ); $this->status_code = wp_remote_retrieve_response_code( $res ); } } else { if ( ! file_exists($url) || ( ! $this->body = file_get_contents($url) ) ) { $this->error = 'file_get_contents could not read the file'; $this->success = false; } } } } /** * WordPress SimplePie Sanitization Class * * Extension of the SimplePie_Sanitize class to use KSES, because * we cannot universally count on DOMDocument being available * * @package WordPress * @since 3.5.0 */ class WP_SimplePie_Sanitize_KSES extends SimplePie_Sanitize { public function sanitize( $data, $type, $base = '' ) { $data = trim( $data ); if ( $type & SIMPLEPIE_CONSTRUCT_MAYBE_HTML ) { if (preg_match('/(&(#(x[0-9a-fA-F]+|[0-9]+)|[a-zA-Z0-9]+)|<\/[A-Za-z][^\x09\x0A\x0B\x0C\x0D\x20\x2F\x3E]*' . SIMPLEPIE_PCRE_HTML_ATTRIBUTE . '>)/', $data)) { $type |= SIMPLEPIE_CONSTRUCT_HTML; } else { $type |= SIMPLEPIE_CONSTRUCT_TEXT; } } if ( $type & SIMPLEPIE_CONSTRUCT_BASE64 ) { $data = base64_decode( $data ); } if ( $type & ( SIMPLEPIE_CONSTRUCT_HTML | SIMPLEPIE_CONSTRUCT_XHTML ) ) { $data = wp_kses_post( $data ); if ( $this->output_encoding !== 'UTF-8' ) { $data = $this->registry->call( 'Misc', 'change_encoding', array( $data, 'UTF-8', $this->output_encoding ) ); } return $data; } else { return parent::sanitize( $data, $type, $base ); } } }
zyblog
trunk/zyblog/wp-includes/class-feed.php
PHP
asf20
3,684
<?php /** * WP_HTTP_IXR_Client * * @package WordPress * @since 3.1.0 * */ class WP_HTTP_IXR_Client extends IXR_Client { function __construct($server, $path = false, $port = false, $timeout = 15) { if ( ! $path ) { // Assume we have been given a URL instead $bits = parse_url($server); $this->scheme = $bits['scheme']; $this->server = $bits['host']; $this->port = isset($bits['port']) ? $bits['port'] : $port; $this->path = !empty($bits['path']) ? $bits['path'] : '/'; // Make absolutely sure we have a path if ( ! $this->path ) $this->path = '/'; } else { $this->scheme = 'http'; $this->server = $server; $this->path = $path; $this->port = $port; } $this->useragent = 'The Incutio XML-RPC PHP Library'; $this->timeout = $timeout; } function query() { $args = func_get_args(); $method = array_shift($args); $request = new IXR_Request($method, $args); $xml = $request->getXml(); $port = $this->port ? ":$this->port" : ''; $url = $this->scheme . '://' . $this->server . $port . $this->path; $args = array( 'headers' => array('Content-Type' => 'text/xml'), 'user-agent' => $this->useragent, 'body' => $xml, ); // Merge Custom headers ala #8145 foreach ( $this->headers as $header => $value ) $args['headers'][$header] = $value; if ( $this->timeout !== false ) $args['timeout'] = $this->timeout; // Now send the request if ( $this->debug ) echo '<pre class="ixr_request">' . htmlspecialchars($xml) . "\n</pre>\n\n"; $response = wp_remote_post($url, $args); if ( is_wp_error($response) ) { $errno = $response->get_error_code(); $errorstr = $response->get_error_message(); $this->error = new IXR_Error(-32300, "transport error: $errno $errorstr"); return false; } if ( 200 != wp_remote_retrieve_response_code( $response ) ) { $this->error = new IXR_Error(-32301, 'transport error - HTTP status code was not 200 (' . wp_remote_retrieve_response_code( $response ) . ')'); return false; } if ( $this->debug ) echo '<pre class="ixr_response">' . htmlspecialchars( wp_remote_retrieve_body( $response ) ) . "\n</pre>\n\n"; // Now parse what we've got back $this->message = new IXR_Message( wp_remote_retrieve_body( $response ) ); if ( ! $this->message->parse() ) { // XML error $this->error = new IXR_Error(-32700, 'parse error. not well formed'); return false; } // Is the message a fault? if ( $this->message->messageType == 'fault' ) { $this->error = new IXR_Error($this->message->faultCode, $this->message->faultString); return false; } // Message must be OK return true; } }
zyblog
trunk/zyblog/wp-includes/class-wp-http-ixr-client.php
PHP
asf20
2,663