FlatCAMApp.py 307 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321
  1. ############################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # Author: Juan Pablo Caram (c) #
  5. # Date: 2/5/2014 #
  6. # MIT Licence #
  7. ############################################################
  8. import sys
  9. import traceback
  10. import urllib.request, urllib.parse, urllib.error
  11. import getopt
  12. import os
  13. import random
  14. import logging
  15. import simplejson as json
  16. import lzma
  17. import re
  18. import os
  19. from stat import S_IREAD, S_IRGRP, S_IROTH
  20. import subprocess
  21. import tkinter as tk
  22. from PyQt5 import QtCore, QtGui, QtWidgets, QtPrintSupport
  23. from PyQt5.QtCore import QSettings
  24. import time # Just used for debugging. Double check before removing.
  25. import urllib.request, urllib.parse, urllib.error
  26. import webbrowser
  27. from contextlib import contextmanager
  28. from xml.dom.minidom import parseString as parse_xml_string
  29. from copy import copy,deepcopy
  30. import numpy as np
  31. from datetime import datetime
  32. import gc
  33. ########################################
  34. ## Imports part of FlatCAM ##
  35. ########################################
  36. from ObjectCollection import *
  37. from FlatCAMObj import *
  38. from PlotCanvas import *
  39. from FlatCAMGUI import *
  40. from FlatCAMCommon import LoudDict
  41. from FlatCAMPostProc import load_postprocessors
  42. from FlatCAMEditor import FlatCAMGeoEditor, FlatCAMExcEditor
  43. from FlatCAMProcess import *
  44. from FlatCAMWorkerStack import WorkerStack
  45. from VisPyVisuals import Color
  46. from vispy.gloo.util import _screenshot
  47. from vispy.io import write_png
  48. from flatcamTools import *
  49. from multiprocessing import Pool
  50. import tclCommands
  51. # from ParseFont import *
  52. ########################################
  53. ## App ##
  54. ########################################
  55. class App(QtCore.QObject):
  56. """
  57. The main application class. The constructor starts the GUI.
  58. """
  59. # Get Cmd Line Options
  60. cmd_line_shellfile = ''
  61. cmd_line_help = "FlatCam.py --shellfile=<cmd_line_shellfile>"
  62. try:
  63. # Multiprocessing pool will spawn additional processes with 'multiprocessing-fork' flag
  64. cmd_line_options, args = getopt.getopt(sys.argv[1:], "h:", ["shellfile=", "multiprocessing-fork="])
  65. except getopt.GetoptError:
  66. print(cmd_line_help)
  67. sys.exit(2)
  68. for opt, arg in cmd_line_options:
  69. if opt == '-h':
  70. print(cmd_line_help)
  71. sys.exit()
  72. elif opt == '--shellfile':
  73. cmd_line_shellfile = arg
  74. # Logging ##
  75. log = logging.getLogger('base')
  76. log.setLevel(logging.DEBUG)
  77. # log.setLevel(logging.WARNING)
  78. formatter = logging.Formatter('[%(levelname)s][%(threadName)s] %(message)s')
  79. handler = logging.StreamHandler()
  80. handler.setFormatter(formatter)
  81. log.addHandler(handler)
  82. # Version
  83. version = 8.911
  84. version_date = "2019/03/2"
  85. beta = True
  86. # current date now
  87. date = str(datetime.today()).rpartition(' ')[0]
  88. # URL for update checks and statistics
  89. version_url = "http://flatcam.org/version"
  90. # App URL
  91. app_url = "http://flatcam.org"
  92. # Manual URL
  93. manual_url = "http://flatcam.org/manual/index.html"
  94. video_url = "https://www.youtube.com/playlist?list=PLVvP2SYRpx-AQgNlfoxw93tXUXon7G94_"
  95. should_we_quit = True
  96. # this variable will hold the project status
  97. # if True it will mean that the project was modified and not saved
  98. should_we_save = False
  99. ##################
  100. ## Signals ##
  101. ##################
  102. # Inform the user
  103. # Handled by:
  104. # * App.info() --> Print on the status bar
  105. inform = QtCore.pyqtSignal(str)
  106. # General purpose background task
  107. worker_task = QtCore.pyqtSignal(dict)
  108. # File opened
  109. # Handled by:
  110. # * register_folder()
  111. # * register_recent()
  112. # Note: Setting the parameters to unicode does not seem
  113. # to have an effect. Then are received as Qstring
  114. # anyway.
  115. # File type and filename
  116. file_opened = QtCore.pyqtSignal(str, str)
  117. # File type and filename
  118. file_saved = QtCore.pyqtSignal(str, str)
  119. # Percentage of progress
  120. progress = QtCore.pyqtSignal(int)
  121. plots_updated = QtCore.pyqtSignal()
  122. # Emitted by new_object() and passes the new object as argument, plot flag.
  123. # on_object_created() adds the object to the collection, plots on appropriate flag
  124. # and emits new_object_available.
  125. object_created = QtCore.pyqtSignal(object, bool, bool)
  126. # Emitted when a object has been changed (like scaled, mirrored)
  127. object_changed = QtCore.pyqtSignal(object)
  128. # Emitted after object has been plotted.
  129. # Calls 'on_zoom_fit' method to fit object in scene view in main thread to prevent drawing glitches.
  130. object_plotted = QtCore.pyqtSignal(object)
  131. # Emitted when a new object has been added or deleted from/to the collection
  132. object_status_changed = QtCore.pyqtSignal(object, str)
  133. message = QtCore.pyqtSignal(str, str, str)
  134. # Emmited when shell command is finished(one command only)
  135. shell_command_finished = QtCore.pyqtSignal(object)
  136. # Emitted when multiprocess pool has been recreated
  137. pool_recreated = QtCore.pyqtSignal(object)
  138. # Emitted when an unhandled exception happens
  139. # in the worker task.
  140. thread_exception = QtCore.pyqtSignal(object)
  141. def __init__(self, user_defaults=True, post_gui=None):
  142. """
  143. Starts the application.
  144. :return: app
  145. :rtype: App
  146. """
  147. App.log.info("FlatCAM Starting...")
  148. ###################
  149. ### OS-specific ###
  150. ###################
  151. # Folder for user settings.
  152. if sys.platform == 'win32':
  153. from win32com.shell import shell, shellcon
  154. if platform.architecture()[0] == '32bit':
  155. App.log.debug("Win32!")
  156. else:
  157. App.log.debug("Win64!")
  158. self.data_path = shell.SHGetFolderPath(0, shellcon.CSIDL_APPDATA, None, 0) + \
  159. '\FlatCAM'
  160. self.os = 'windows'
  161. else: # Linux/Unix/MacOS
  162. self.data_path = os.path.expanduser('~') + \
  163. '/.FlatCAM'
  164. self.os = 'unix'
  165. ###############################
  166. ### Setup folders and files ###
  167. ###############################
  168. if not os.path.exists(self.data_path):
  169. os.makedirs(self.data_path)
  170. App.log.debug('Created data folder: ' + self.data_path)
  171. os.makedirs(os.path.join(self.data_path, 'postprocessors'))
  172. App.log.debug('Created data postprocessors folder: ' + os.path.join(self.data_path, 'postprocessors'))
  173. self.postprocessorpaths = os.path.join(self.data_path,'postprocessors')
  174. if not os.path.exists(self.postprocessorpaths):
  175. os.makedirs(self.postprocessorpaths)
  176. App.log.debug('Created postprocessors folder: ' + self.postprocessorpaths)
  177. # create current_defaults.FlatConfig file if there is none
  178. try:
  179. f = open(self.data_path + '/current_defaults.FlatConfig')
  180. f.close()
  181. except IOError:
  182. App.log.debug('Creating empty current_defaults.FlatConfig')
  183. f = open(self.data_path + '/current_defaults.FlatConfig', 'w')
  184. json.dump({}, f)
  185. f.close()
  186. # create factory_defaults.FlatConfig file if there is none
  187. try:
  188. f = open(self.data_path + '/factory_defaults.FlatConfig')
  189. f.close()
  190. except IOError:
  191. App.log.debug('Creating empty factory_defaults.FlatConfig')
  192. f = open(self.data_path + '/factory_defaults.FlatConfig', 'w')
  193. json.dump({}, f)
  194. f.close()
  195. try:
  196. f = open(self.data_path + '/recent.json')
  197. f.close()
  198. except IOError:
  199. App.log.debug('Creating empty recent.json')
  200. f = open(self.data_path + '/recent.json', 'w')
  201. json.dump([], f)
  202. f.close()
  203. # Application directory. CHDIR to it. Otherwise, trying to load
  204. # GUI icons will fail as their path is relative.
  205. # This will fail under cx_freeze ...
  206. self.app_home = os.path.dirname(os.path.realpath(__file__))
  207. App.log.debug("Application path is " + self.app_home)
  208. App.log.debug("Started in " + os.getcwd())
  209. # cx_freeze workaround
  210. if os.path.isfile(self.app_home):
  211. self.app_home = os.path.dirname(self.app_home)
  212. os.chdir(self.app_home)
  213. # Create multiprocessing pool
  214. self.pool = Pool()
  215. # variable to store mouse coordinates
  216. self.mouse = [0, 0]
  217. ####################
  218. ## Initialize GUI ##
  219. ####################
  220. # FlatCAM colors used in plotting
  221. self.FC_light_green = '#BBF268BF'
  222. self.FC_dark_green = '#006E20BF'
  223. self.FC_light_blue = '#a5a5ffbf'
  224. self.FC_dark_blue = '#0000ffbf'
  225. QtCore.QObject.__init__(self)
  226. self.ui = FlatCAMGUI(self.version, self.beta, self)
  227. # self.connect(self.ui,
  228. # QtCore.SIGNAL("geomUpdate(int, int, int, int, int)"),
  229. # self.save_geometry) PyQt4
  230. self.ui.geom_update[int, int, int, int, int].connect(self.save_geometry)
  231. self.ui.final_save.connect(self.final_save)
  232. ##############
  233. #### Data ####
  234. ##############
  235. self.recent = []
  236. self.clipboard = QtWidgets.QApplication.clipboard()
  237. self.proc_container = FCVisibleProcessContainer(self.ui.activity_view)
  238. self.project_filename = None
  239. self.toggle_units_ignore = False
  240. # self.defaults_form = PreferencesUI()
  241. # when adding entries here read the comments in the method found bellow named:
  242. # def new_object(self, kind, name, initialize, active=True, fit=True, plot=True)
  243. self.defaults_form_fields = {
  244. # General App
  245. "units": self.ui.general_defaults_form.general_app_group.units_radio,
  246. "global_shell_at_startup": self.ui.general_defaults_form.general_app_group.shell_startup_cb,
  247. "global_version_check": self.ui.general_defaults_form.general_app_group.version_check_cb,
  248. "global_send_stats": self.ui.general_defaults_form.general_app_group.send_stats_cb,
  249. "global_project_at_startup": self.ui.general_defaults_form.general_app_group.project_startup_cb,
  250. "global_project_autohide": self.ui.general_defaults_form.general_app_group.project_autohide_cb,
  251. "global_app_level": self.ui.general_defaults_form.general_app_group.app_level_radio,
  252. "global_compression_level": self.ui.general_defaults_form.general_app_group.compress_combo,
  253. "global_save_compressed": self.ui.general_defaults_form.general_app_group.save_type_cb,
  254. "global_toggle_tooltips": self.ui.general_defaults_form.general_app_group.toggle_tooltips_cb,
  255. # General GUI
  256. "global_gridx": self.ui.general_defaults_form.general_gui_group.gridx_entry,
  257. "global_gridy": self.ui.general_defaults_form.general_gui_group.gridy_entry,
  258. "global_snap_max": self.ui.general_defaults_form.general_gui_group.snap_max_dist_entry,
  259. "global_plot_fill": self.ui.general_defaults_form.general_gui_group.pf_color_entry,
  260. "global_plot_line": self.ui.general_defaults_form.general_gui_group.pl_color_entry,
  261. "global_sel_fill": self.ui.general_defaults_form.general_gui_group.sf_color_entry,
  262. "global_sel_line": self.ui.general_defaults_form.general_gui_group.sl_color_entry,
  263. "global_alt_sel_fill": self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry,
  264. "global_alt_sel_line": self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry,
  265. "global_draw_color": self.ui.general_defaults_form.general_gui_group.draw_color_entry,
  266. "global_sel_draw_color": self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry,
  267. "global_pan_button": self.ui.general_defaults_form.general_app_group.pan_button_radio,
  268. "global_mselect_key": self.ui.general_defaults_form.general_app_group.mselect_radio,
  269. # "global_pan_with_space_key": self.ui.general_defaults_form.general_gui_group.pan_with_space_cb,
  270. "global_workspace": self.ui.general_defaults_form.general_gui_group.workspace_cb,
  271. "global_workspaceT": self.ui.general_defaults_form.general_gui_group.wk_cb,
  272. "gerber_plot": self.ui.gerber_defaults_form.gerber_gen_group.plot_cb,
  273. "gerber_solid": self.ui.gerber_defaults_form.gerber_gen_group.solid_cb,
  274. "gerber_multicolored": self.ui.gerber_defaults_form.gerber_gen_group.multicolored_cb,
  275. "gerber_circle_steps": self.ui.gerber_defaults_form.gerber_gen_group.circle_steps_entry,
  276. "gerber_isotooldia": self.ui.gerber_defaults_form.gerber_opt_group.iso_tool_dia_entry,
  277. "gerber_isopasses": self.ui.gerber_defaults_form.gerber_opt_group.iso_width_entry,
  278. "gerber_isooverlap": self.ui.gerber_defaults_form.gerber_opt_group.iso_overlap_entry,
  279. "gerber_combine_passes": self.ui.gerber_defaults_form.gerber_opt_group.combine_passes_cb,
  280. "gerber_milling_type": self.ui.gerber_defaults_form.gerber_opt_group.milling_type_radio,
  281. "gerber_noncoppermargin": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_margin_entry,
  282. "gerber_noncopperrounded": self.ui.gerber_defaults_form.gerber_opt_group.noncopper_rounded_cb,
  283. "gerber_bboxmargin": self.ui.gerber_defaults_form.gerber_opt_group.bbmargin_entry,
  284. "gerber_bboxrounded": self.ui.gerber_defaults_form.gerber_opt_group.bbrounded_cb,
  285. # Excellon General
  286. "excellon_plot": self.ui.excellon_defaults_form.excellon_gen_group.plot_cb,
  287. "excellon_solid": self.ui.excellon_defaults_form.excellon_gen_group.solid_cb,
  288. "excellon_format_upper_in": self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_in_entry,
  289. "excellon_format_lower_in": self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_in_entry,
  290. "excellon_format_upper_mm": self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_upper_mm_entry,
  291. "excellon_format_lower_mm": self.ui.excellon_defaults_form.excellon_gen_group.excellon_format_lower_mm_entry,
  292. "excellon_zeros": self.ui.excellon_defaults_form.excellon_gen_group.excellon_zeros_radio,
  293. "excellon_units": self.ui.excellon_defaults_form.excellon_gen_group.excellon_units_radio,
  294. "excellon_optimization_type": self.ui.excellon_defaults_form.excellon_gen_group.excellon_optimization_radio,
  295. "excellon_search_time": self.ui.excellon_defaults_form.excellon_gen_group.optimization_time_entry,
  296. # Excellon Options
  297. "excellon_drillz": self.ui.excellon_defaults_form.excellon_opt_group.cutz_entry,
  298. "excellon_travelz": self.ui.excellon_defaults_form.excellon_opt_group.travelz_entry,
  299. "excellon_feedrate": self.ui.excellon_defaults_form.excellon_opt_group.feedrate_entry,
  300. "excellon_spindlespeed": self.ui.excellon_defaults_form.excellon_opt_group.spindlespeed_entry,
  301. "excellon_dwell": self.ui.excellon_defaults_form.excellon_opt_group.dwell_cb,
  302. "excellon_dwelltime": self.ui.excellon_defaults_form.excellon_opt_group.dwelltime_entry,
  303. "excellon_toolchange": self.ui.excellon_defaults_form.excellon_opt_group.toolchange_cb,
  304. "excellon_toolchangez": self.ui.excellon_defaults_form.excellon_opt_group.toolchangez_entry,
  305. "excellon_ppname_e": self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb,
  306. "excellon_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.tooldia_entry,
  307. "excellon_slot_tooldia": self.ui.excellon_defaults_form.excellon_opt_group.slot_tooldia_entry,
  308. "excellon_gcode_type": self.ui.excellon_defaults_form.excellon_opt_group.excellon_gcode_type_radio,
  309. # Excellon Advanced Options
  310. "excellon_offset": self.ui.excellon_defaults_form.excellon_adv_opt_group.offset_entry,
  311. "excellon_toolchangexy": self.ui.excellon_defaults_form.excellon_adv_opt_group.toolchangexy_entry,
  312. "excellon_startz": self.ui.excellon_defaults_form.excellon_adv_opt_group.estartz_entry,
  313. "excellon_endz": self.ui.excellon_defaults_form.excellon_adv_opt_group.eendz_entry,
  314. "excellon_feedrate_rapid": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_rapid_entry,
  315. "excellon_z_pdepth": self.ui.excellon_defaults_form.excellon_adv_opt_group.pdepth_entry,
  316. "excellon_feedrate_probe": self.ui.excellon_defaults_form.excellon_adv_opt_group.feedrate_probe_entry,
  317. "excellon_f_plunge": self.ui.excellon_defaults_form.excellon_adv_opt_group.fplunge_cb,
  318. "excellon_f_retract": self.ui.excellon_defaults_form.excellon_adv_opt_group.fretract_cb,
  319. # Excellon Export
  320. "excellon_exp_units": self.ui.excellon_defaults_form.excellon_exp_group.excellon_units_radio,
  321. "excellon_exp_format": self.ui.excellon_defaults_form.excellon_exp_group.format_radio,
  322. "excellon_exp_integer": self.ui.excellon_defaults_form.excellon_exp_group.format_whole_entry,
  323. "excellon_exp_decimals": self.ui.excellon_defaults_form.excellon_exp_group.format_dec_entry,
  324. "excellon_exp_zeros": self.ui.excellon_defaults_form.excellon_exp_group.zeros_radio,
  325. # Geometry General
  326. "geometry_plot": self.ui.geometry_defaults_form.geometry_gen_group.plot_cb,
  327. "geometry_circle_steps": self.ui.geometry_defaults_form.geometry_gen_group.circle_steps_entry,
  328. "geometry_cnctooldia": self.ui.geometry_defaults_form.geometry_gen_group.cnctooldia_entry,
  329. # Geometry Options
  330. "geometry_cutz": self.ui.geometry_defaults_form.geometry_opt_group.cutz_entry,
  331. "geometry_travelz": self.ui.geometry_defaults_form.geometry_opt_group.travelz_entry,
  332. "geometry_feedrate": self.ui.geometry_defaults_form.geometry_opt_group.cncfeedrate_entry,
  333. "geometry_feedrate_z": self.ui.geometry_defaults_form.geometry_opt_group.cncplunge_entry,
  334. "geometry_spindlespeed": self.ui.geometry_defaults_form.geometry_opt_group.cncspindlespeed_entry,
  335. "geometry_dwell": self.ui.geometry_defaults_form.geometry_opt_group.dwell_cb,
  336. "geometry_dwelltime": self.ui.geometry_defaults_form.geometry_opt_group.dwelltime_entry,
  337. "geometry_ppname_g": self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb,
  338. "geometry_toolchange": self.ui.geometry_defaults_form.geometry_opt_group.toolchange_cb,
  339. "geometry_toolchangez": self.ui.geometry_defaults_form.geometry_opt_group.toolchangez_entry,
  340. "geometry_depthperpass": self.ui.geometry_defaults_form.geometry_opt_group.depthperpass_entry,
  341. "geometry_multidepth": self.ui.geometry_defaults_form.geometry_opt_group.multidepth_cb,
  342. # Geometry Advanced Options
  343. "geometry_toolchangexy": self.ui.geometry_defaults_form.geometry_adv_opt_group.toolchangexy_entry,
  344. "geometry_startz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gstartz_entry,
  345. "geometry_endz": self.ui.geometry_defaults_form.geometry_adv_opt_group.gendz_entry,
  346. "geometry_feedrate_rapid": self.ui.geometry_defaults_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  347. "geometry_extracut": self.ui.geometry_defaults_form.geometry_adv_opt_group.extracut_cb,
  348. "geometry_z_pdepth": self.ui.geometry_defaults_form.geometry_adv_opt_group.pdepth_entry,
  349. "geometry_feedrate_probe": self.ui.geometry_defaults_form.geometry_adv_opt_group.feedrate_probe_entry,
  350. "geometry_f_plunge": self.ui.geometry_defaults_form.geometry_adv_opt_group.fplunge_cb,
  351. "geometry_segx": self.ui.geometry_defaults_form.geometry_adv_opt_group.segx_entry,
  352. "geometry_segy": self.ui.geometry_defaults_form.geometry_adv_opt_group.segy_entry,
  353. # CNCJob General
  354. "cncjob_plot": self.ui.cncjob_defaults_form.cncjob_gen_group.plot_cb,
  355. "cncjob_plot_kind": self.ui.cncjob_defaults_form.cncjob_gen_group.cncplot_method_radio,
  356. "cncjob_tooldia": self.ui.cncjob_defaults_form.cncjob_gen_group.tooldia_entry,
  357. "cncjob_coords_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.coords_dec_entry,
  358. "cncjob_fr_decimals": self.ui.cncjob_defaults_form.cncjob_gen_group.fr_dec_entry,
  359. "cncjob_steps_per_circle": self.ui.cncjob_defaults_form.cncjob_gen_group.steps_per_circle_entry,
  360. "cncjob_prepend": self.ui.cncjob_defaults_form.cncjob_opt_group.prepend_text,
  361. "cncjob_append": self.ui.cncjob_defaults_form.cncjob_opt_group.append_text,
  362. # NCC Tool
  363. "tools_ncctools": self.ui.tools_defaults_form.tools_ncc_group.ncc_tool_dia_entry,
  364. "tools_nccoverlap": self.ui.tools_defaults_form.tools_ncc_group.ncc_overlap_entry,
  365. "tools_nccmargin": self.ui.tools_defaults_form.tools_ncc_group.ncc_margin_entry,
  366. "tools_nccmethod": self.ui.tools_defaults_form.tools_ncc_group.ncc_method_radio,
  367. "tools_nccconnect": self.ui.tools_defaults_form.tools_ncc_group.ncc_connect_cb,
  368. "tools_ncccontour": self.ui.tools_defaults_form.tools_ncc_group.ncc_contour_cb,
  369. "tools_nccrest": self.ui.tools_defaults_form.tools_ncc_group.ncc_rest_cb,
  370. # CutOut Tool
  371. "tools_cutouttooldia": self.ui.tools_defaults_form.tools_cutout_group.cutout_tooldia_entry,
  372. "tools_cutoutmargin": self.ui.tools_defaults_form.tools_cutout_group.cutout_margin_entry,
  373. "tools_cutoutgapsize": self.ui.tools_defaults_form.tools_cutout_group.cutout_gap_entry,
  374. "tools_gaps_rect": self.ui.tools_defaults_form.tools_cutout_group.gaps_radio,
  375. "tools_gaps_ff": self.ui.tools_defaults_form.tools_cutout_group.gaps_combo,
  376. # Paint Area Tool
  377. "tools_painttooldia": self.ui.tools_defaults_form.tools_paint_group.painttooldia_entry,
  378. "tools_paintoverlap": self.ui.tools_defaults_form.tools_paint_group.paintoverlap_entry,
  379. "tools_paintmargin": self.ui.tools_defaults_form.tools_paint_group.paintmargin_entry,
  380. "tools_paintmethod": self.ui.tools_defaults_form.tools_paint_group.paintmethod_combo,
  381. "tools_selectmethod": self.ui.tools_defaults_form.tools_paint_group.selectmethod_combo,
  382. "tools_pathconnect": self.ui.tools_defaults_form.tools_paint_group.pathconnect_cb,
  383. "tools_paintcontour": self.ui.tools_defaults_form.tools_paint_group.contour_cb,
  384. # 2-sided Tool
  385. "tools_2sided_mirror_axis": self.ui.tools_defaults_form.tools_2sided_group.mirror_axis_radio,
  386. "tools_2sided_axis_loc": self.ui.tools_defaults_form.tools_2sided_group.axis_location_radio,
  387. "tools_2sided_drilldia": self.ui.tools_defaults_form.tools_2sided_group.drill_dia_entry,
  388. # Film Tool
  389. "tools_film_type": self.ui.tools_defaults_form.tools_film_group.film_type_radio,
  390. "tools_film_boundary": self.ui.tools_defaults_form.tools_film_group.film_boundary_entry,
  391. "tools_film_scale": self.ui.tools_defaults_form.tools_film_group.film_scale_entry,
  392. # Panelize Tool
  393. "tools_panelize_spacing_columns": self.ui.tools_defaults_form.tools_panelize_group.pspacing_columns,
  394. "tools_panelize_spacing_rows": self.ui.tools_defaults_form.tools_panelize_group.pspacing_rows,
  395. "tools_panelize_columns": self.ui.tools_defaults_form.tools_panelize_group.pcolumns,
  396. "tools_panelize_rows": self.ui.tools_defaults_form.tools_panelize_group.prows,
  397. "tools_panelize_constrain": self.ui.tools_defaults_form.tools_panelize_group.pconstrain_cb,
  398. "tools_panelize_constrainx": self.ui.tools_defaults_form.tools_panelize_group.px_width_entry,
  399. "tools_panelize_constrainy": self.ui.tools_defaults_form.tools_panelize_group.py_height_entry,
  400. "tools_panelize_panel_type": self.ui.tools_defaults_form.tools_panelize_group.panel_type_radio,
  401. # Calculators Tool
  402. "tools_calc_vshape_tip_dia": self.ui.tools_defaults_form.tools_calculators_group.tip_dia_entry,
  403. "tools_calc_vshape_tip_angle": self.ui.tools_defaults_form.tools_calculators_group.tip_angle_entry,
  404. "tools_calc_vshape_cut_z": self.ui.tools_defaults_form.tools_calculators_group.cut_z_entry,
  405. "tools_calc_electro_length": self.ui.tools_defaults_form.tools_calculators_group.pcblength_entry,
  406. "tools_calc_electro_width": self.ui.tools_defaults_form.tools_calculators_group.pcbwidth_entry,
  407. "tools_calc_electro_cdensity": self.ui.tools_defaults_form.tools_calculators_group.cdensity_entry,
  408. "tools_calc_electro_growth": self.ui.tools_defaults_form.tools_calculators_group.growth_entry,
  409. # Transformations Tool
  410. "tools_transform_rotate": self.ui.tools_defaults_form.tools_transform_group.rotate_entry,
  411. "tools_transform_skew_x": self.ui.tools_defaults_form.tools_transform_group.skewx_entry,
  412. "tools_transform_skew_y": self.ui.tools_defaults_form.tools_transform_group.skewy_entry,
  413. "tools_transform_scale_x": self.ui.tools_defaults_form.tools_transform_group.scalex_entry,
  414. "tools_transform_scale_y": self.ui.tools_defaults_form.tools_transform_group.scaley_entry,
  415. "tools_transform_scale_link": self.ui.tools_defaults_form.tools_transform_group.link_cb,
  416. "tools_transform_scale_reference": self.ui.tools_defaults_form.tools_transform_group.reference_cb,
  417. "tools_transform_offset_x": self.ui.tools_defaults_form.tools_transform_group.offx_entry,
  418. "tools_transform_offset_y": self.ui.tools_defaults_form.tools_transform_group.offy_entry,
  419. "tools_transform_mirror_reference": self.ui.tools_defaults_form.tools_transform_group.mirror_reference_cb,
  420. "tools_transform_mirror_point": self.ui.tools_defaults_form.tools_transform_group.flip_ref_entry,
  421. # SolderPaste Dispensing Tool
  422. "tools_solderpaste_tools": self.ui.tools_defaults_form.tools_solderpaste_group.nozzle_tool_dia_entry,
  423. "tools_solderpaste_new": self.ui.tools_defaults_form.tools_solderpaste_group.addtool_entry,
  424. "tools_solderpaste_z_start": self.ui.tools_defaults_form.tools_solderpaste_group.z_start_entry,
  425. "tools_solderpaste_z_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.z_dispense_entry,
  426. "tools_solderpaste_z_stop": self.ui.tools_defaults_form.tools_solderpaste_group.z_stop_entry,
  427. "tools_solderpaste_z_travel": self.ui.tools_defaults_form.tools_solderpaste_group.z_travel_entry,
  428. "tools_solderpaste_z_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.z_toolchange_entry,
  429. "tools_solderpaste_xy_toolchange": self.ui.tools_defaults_form.tools_solderpaste_group.xy_toolchange_entry,
  430. "tools_solderpaste_frxy": self.ui.tools_defaults_form.tools_solderpaste_group.frxy_entry,
  431. "tools_solderpaste_frz": self.ui.tools_defaults_form.tools_solderpaste_group.frz_entry,
  432. "tools_solderpaste_frz_dispense": self.ui.tools_defaults_form.tools_solderpaste_group.frz_dispense_entry,
  433. "tools_solderpaste_speedfwd": self.ui.tools_defaults_form.tools_solderpaste_group.speedfwd_entry,
  434. "tools_solderpaste_dwellfwd": self.ui.tools_defaults_form.tools_solderpaste_group.dwellfwd_entry,
  435. "tools_solderpaste_speedrev": self.ui.tools_defaults_form.tools_solderpaste_group.speedrev_entry,
  436. "tools_solderpaste_dwellrev": self.ui.tools_defaults_form.tools_solderpaste_group.dwellrev_entry,
  437. "tools_solderpaste_pp": self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo
  438. }
  439. #############################
  440. #### LOAD POSTPROCESSORS ####
  441. #############################
  442. self.postprocessors = load_postprocessors(self)
  443. for name in list(self.postprocessors.keys()):
  444. # 'Paste' postprocessors are to be used only in the Solder Paste Dispensing Tool
  445. if name.partition('_')[0] == 'Paste':
  446. self.ui.tools_defaults_form.tools_solderpaste_group.pp_combo.addItem(name)
  447. continue
  448. self.ui.geometry_defaults_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  449. # HPGL postprocessor is only for Geometry objects therefore it should not be in the Excellon Preferences
  450. if name == 'hpgl':
  451. continue
  452. self.ui.excellon_defaults_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  453. self.defaults = LoudDict()
  454. self.defaults.set_change_callback(self.on_defaults_dict_change) # When the dictionary changes.
  455. self.defaults.update({
  456. "global_serial": 0,
  457. "global_stats": {},
  458. "units": "IN",
  459. "global_version_check": True,
  460. "global_send_stats": True,
  461. "global_project_at_startup": False,
  462. "global_project_autohide": True,
  463. "global_app_level": 'b',
  464. "global_gridx": 1.0,
  465. "global_gridy": 1.0,
  466. "global_snap_max": 0.05,
  467. "global_grid_context_menu": {
  468. 'in': [0.01, 0.02, 0.025, 0.05, 0.1],
  469. 'mm': [0.1, 0.2, 0.5, 1, 2.54]
  470. },
  471. "global_plot_fill": '#BBF268BF',
  472. "global_plot_line": '#006E20BF',
  473. "global_sel_fill": '#a5a5ffbf',
  474. "global_sel_line": '#0000ffbf',
  475. "global_alt_sel_fill": '#BBF268BF',
  476. "global_alt_sel_line": '#006E20BF',
  477. "global_draw_color": '#FF0000',
  478. "global_sel_draw_color": '#0000FF',
  479. "global_pan_button": '2',
  480. "global_mselect_key": 'Control',
  481. # "global_pan_with_space_key": False,
  482. "global_workspace": False,
  483. "global_workspaceT": "A4P",
  484. "global_toolbar_view": 127,
  485. "global_background_timeout": 300000, # Default value is 5 minutes
  486. "global_verbose_error_level": 0, # Shell verbosity 0 = default
  487. # (python trace only for unknown errors),
  488. # 1 = show trace(show trace allways),
  489. # 2 = (For the future).
  490. # Persistence
  491. "global_last_folder": None,
  492. "global_last_save_folder": None,
  493. # Default window geometry
  494. "global_def_win_x": 100,
  495. "global_def_win_y": 100,
  496. "global_def_win_w": 1024,
  497. "global_def_win_h": 650,
  498. # Constants...
  499. "global_defaults_save_period_ms": 20000, # Time between default saves.
  500. "global_shell_shape": [500, 300], # Shape of the shell in pixels.
  501. "global_shell_at_startup": False, # Show the shell at startup.
  502. "global_recent_limit": 10, # Max. items in recent list.
  503. "global_compression_level": 3,
  504. "global_save_compressed": True,
  505. "global_toggle_tooltips": True,
  506. "fit_key": 'V',
  507. "zoom_out_key": '-',
  508. "zoom_in_key": '=',
  509. "grid_toggle_key": 'G',
  510. "zoom_ratio": 1.5,
  511. "global_point_clipboard_format": "(%.4f, %.4f)",
  512. "global_zdownrate": None,
  513. "gerber_plot": True,
  514. "gerber_solid": True,
  515. "gerber_multicolored": False,
  516. "gerber_isotooldia": 0.016,
  517. "gerber_isopasses": 1,
  518. "gerber_isooverlap": 0.15,
  519. "gerber_combine_passes": False,
  520. "gerber_milling_type": "cl",
  521. "gerber_noncoppermargin": 0.1,
  522. "gerber_noncopperrounded": False,
  523. "gerber_bboxmargin": 0.1,
  524. "gerber_bboxrounded": False,
  525. "gerber_circle_steps": 64,
  526. "gerber_use_buffer_for_union": True,
  527. # Excellon General
  528. "excellon_plot": True,
  529. "excellon_solid": True,
  530. "excellon_format_upper_in": 2,
  531. "excellon_format_lower_in": 4,
  532. "excellon_format_upper_mm": 3,
  533. "excellon_format_lower_mm": 3,
  534. "excellon_zeros": "L",
  535. "excellon_units": "INCH",
  536. "excellon_optimization_type": 'B',
  537. "excellon_search_time": 3,
  538. # Excellon Options
  539. "excellon_drillz": -0.1,
  540. "excellon_travelz": 0.1,
  541. "excellon_feedrate": 3.0,
  542. "excellon_feedrate_probe": 3.0,
  543. "excellon_spindlespeed": None,
  544. "excellon_dwell": False,
  545. "excellon_dwelltime": 1,
  546. "excellon_toolchange": False,
  547. "excellon_toolchangez": 1.0,
  548. "excellon_ppname_e": 'default',
  549. "excellon_tooldia": 0.016,
  550. "excellon_slot_tooldia": 0.016,
  551. "excellon_gcode_type": "drills",
  552. # Excellon Advanced Options
  553. "excellon_offset": 0.0,
  554. "excellon_toolchangexy": "0.0, 0.0",
  555. "excellon_startz": None,
  556. "excellon_endz": 2.0,
  557. "excellon_feedrate_rapid": 3.0,
  558. "excellon_z_pdepth": -0.02,
  559. "excellon_f_plunge": False,
  560. "excellon_f_retract": False,
  561. # Excellon Export
  562. "excellon_exp_units": 'INCH',
  563. "excellon_exp_format": 'ndec',
  564. "excellon_exp_integer": 2,
  565. "excellon_exp_decimals": 4,
  566. "excellon_exp_zeros": 'LZ',
  567. # Geometry General
  568. "geometry_plot": True,
  569. "geometry_circle_steps": 64,
  570. "geometry_cnctooldia": 0.016,
  571. # Geometry Options
  572. "geometry_cutz": -0.002,
  573. "geometry_multidepth": False,
  574. "geometry_depthperpass": 0.002,
  575. "geometry_travelz": 0.1,
  576. "geometry_toolchange": False,
  577. "geometry_toolchangez": 1.0,
  578. "geometry_feedrate": 3.0,
  579. "geometry_feedrate_z": 3.0,
  580. "geometry_spindlespeed": None,
  581. "geometry_dwell": False,
  582. "geometry_dwelltime": 1,
  583. "geometry_ppname_g": 'default',
  584. # Geometry Advanced Options
  585. "geometry_toolchangexy": "0.0, 0.0",
  586. "geometry_startz": None,
  587. "geometry_endz": 2.0,
  588. "geometry_feedrate_rapid": 3.0,
  589. "geometry_extracut": False,
  590. "geometry_z_pdepth": -0.02,
  591. "geometry_f_plunge": False,
  592. "geometry_feedrate_probe": 3.0,
  593. "geometry_segx": 0.0,
  594. "geometry_segy": 0.0,
  595. "cncjob_plot": True,
  596. "cncjob_plot_kind": 'all',
  597. "cncjob_tooldia": 0.0393701,
  598. "cncjob_coords_decimals": 4,
  599. "cncjob_fr_decimals": 2,
  600. "cncjob_prepend": "",
  601. "cncjob_append": "",
  602. "cncjob_steps_per_circle": 64,
  603. "tools_ncctools": "1.0, 0.5",
  604. "tools_nccoverlap": 0.4,
  605. "tools_nccmargin": 0.1,
  606. "tools_nccmethod": "seed",
  607. "tools_nccconnect": True,
  608. "tools_ncccontour": True,
  609. "tools_nccrest": False,
  610. "tools_cutouttooldia": 0.1,
  611. "tools_cutoutmargin": 0.1,
  612. "tools_cutoutgapsize": 0.15,
  613. "tools_gaps_rect": "4",
  614. "tools_gaps_ff": "8",
  615. "tools_painttooldia": 0.07,
  616. "tools_paintoverlap": 0.15,
  617. "tools_paintmargin": 0.0,
  618. "tools_paintmethod": "seed",
  619. "tools_selectmethod": "single",
  620. "tools_pathconnect": True,
  621. "tools_paintcontour": True,
  622. "tools_2sided_mirror_axis": "X",
  623. "tools_2sided_axis_loc": "point",
  624. "tools_2sided_drilldia": 1,
  625. "tools_film_type": 'neg',
  626. "tools_film_boundary": 1,
  627. "tools_film_scale": 0,
  628. "tools_panelize_spacing_columns": 0,
  629. "tools_panelize_spacing_rows": 0,
  630. "tools_panelize_columns": 1,
  631. "tools_panelize_rows": 1,
  632. "tools_panelize_constrain": False,
  633. "tools_panelize_constrainx": 0.0,
  634. "tools_panelize_constrainy": 0.0,
  635. "tools_panelize_panel_type": 'gerber',
  636. "tools_calc_vshape_tip_dia": 0.007874,
  637. "tools_calc_vshape_tip_angle": 30,
  638. "tools_calc_vshape_cut_z": 0.000787,
  639. "tools_calc_electro_length": 10.0,
  640. "tools_calc_electro_width": 10.0,
  641. "tools_calc_electro_cdensity":13.0,
  642. "tools_calc_electro_growth": 10.0,
  643. "tools_transform_rotate": 90,
  644. "tools_transform_skew_x": 0.0,
  645. "tools_transform_skew_y": 0.0,
  646. "tools_transform_scale_x": 1.0,
  647. "tools_transform_scale_y": 1.0,
  648. "tools_transform_scale_link": True,
  649. "tools_transform_scale_reference": True,
  650. "tools_transform_offset_x": 0.0,
  651. "tools_transform_offset_y": 0.0,
  652. "tools_transform_mirror_reference": False,
  653. "tools_transform_mirror_point": (0, 0),
  654. "tools_solderpaste_tools": "1.0, 0.3",
  655. "tools_solderpaste_new": 0.3,
  656. "tools_solderpaste_z_start": 0.005,
  657. "tools_solderpaste_z_dispense": 0.01,
  658. "tools_solderpaste_z_stop": 0.005,
  659. "tools_solderpaste_z_travel": 0.1,
  660. "tools_solderpaste_z_toolchange": 1.0,
  661. "tools_solderpaste_xy_toolchange": "0.0, 0.0",
  662. "tools_solderpaste_frxy": 3.0,
  663. "tools_solderpaste_frz": 3.0,
  664. "tools_solderpaste_frz_dispense": 1.0,
  665. "tools_solderpaste_speedfwd": 20,
  666. "tools_solderpaste_dwellfwd": 1,
  667. "tools_solderpaste_speedrev": 10,
  668. "tools_solderpaste_dwellrev": 1,
  669. "tools_solderpaste_pp": 'Paste_1'
  670. })
  671. ###############################
  672. ### Load defaults from file ###
  673. if user_defaults:
  674. self.load_defaults(filename='current_defaults')
  675. chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  676. if self.defaults['global_serial'] == 0 or len(str(self.defaults['global_serial'])) < 10:
  677. self.defaults['global_serial'] = ''.join([random.choice(chars) for i in range(20)])
  678. self.save_defaults(silent=True)
  679. self.propagate_defaults(silent=True)
  680. self.restore_main_win_geom()
  681. def auto_save_defaults():
  682. try:
  683. self.save_defaults(silent=True)
  684. self.propagate_defaults(silent=True)
  685. finally:
  686. QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  687. # the following lines activates automatic defaults save
  688. # if user_defaults:
  689. # QtCore.QTimer.singleShot(self.defaults["global_defaults_save_period_ms"], auto_save_defaults)
  690. # self.options_form = PreferencesUI()
  691. self.options_form_fields = {
  692. "units": self.ui.general_options_form.general_app_group.units_radio,
  693. "global_gridx": self.ui.general_options_form.general_gui_group.gridx_entry,
  694. "global_gridy": self.ui.general_options_form.general_gui_group.gridy_entry,
  695. "global_snap_max": self.ui.general_options_form.general_gui_group.snap_max_dist_entry,
  696. "gerber_plot": self.ui.gerber_options_form.gerber_gen_group.plot_cb,
  697. "gerber_solid": self.ui.gerber_options_form.gerber_gen_group.solid_cb,
  698. "gerber_multicolored": self.ui.gerber_options_form.gerber_gen_group.multicolored_cb,
  699. "gerber_isotooldia": self.ui.gerber_options_form.gerber_opt_group.iso_tool_dia_entry,
  700. "gerber_isopasses": self.ui.gerber_options_form.gerber_opt_group.iso_width_entry,
  701. "gerber_isooverlap": self.ui.gerber_options_form.gerber_opt_group.iso_overlap_entry,
  702. "gerber_combine_passes": self.ui.gerber_options_form.gerber_opt_group.combine_passes_cb,
  703. "gerber_noncoppermargin": self.ui.gerber_options_form.gerber_opt_group.noncopper_margin_entry,
  704. "gerber_noncopperrounded": self.ui.gerber_options_form.gerber_opt_group.noncopper_rounded_cb,
  705. "gerber_bboxmargin": self.ui.gerber_options_form.gerber_opt_group.bbmargin_entry,
  706. "gerber_bboxrounded": self.ui.gerber_options_form.gerber_opt_group.bbrounded_cb,
  707. "excellon_plot": self.ui.excellon_options_form.excellon_gen_group.plot_cb,
  708. "excellon_solid": self.ui.excellon_options_form.excellon_gen_group.solid_cb,
  709. "excellon_format_upper_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_in_entry,
  710. "excellon_format_lower_in": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_in_entry,
  711. "excellon_format_upper_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_upper_mm_entry,
  712. "excellon_format_lower_mm": self.ui.excellon_options_form.excellon_gen_group.excellon_format_lower_mm_entry,
  713. "excellon_zeros": self.ui.excellon_options_form.excellon_gen_group.excellon_zeros_radio,
  714. "excellon_units": self.ui.excellon_options_form.excellon_gen_group.excellon_units_radio,
  715. "excellon_optimization_type": self.ui.excellon_options_form.excellon_gen_group.excellon_optimization_radio,
  716. "excellon_drillz": self.ui.excellon_options_form.excellon_opt_group.cutz_entry,
  717. "excellon_travelz": self.ui.excellon_options_form.excellon_opt_group.travelz_entry,
  718. "excellon_feedrate": self.ui.excellon_options_form.excellon_opt_group.feedrate_entry,
  719. "excellon_spindlespeed": self.ui.excellon_options_form.excellon_opt_group.spindlespeed_entry,
  720. "excellon_dwell": self.ui.excellon_options_form.excellon_opt_group.dwell_cb,
  721. "excellon_dwelltime": self.ui.excellon_options_form.excellon_opt_group.dwelltime_entry,
  722. "excellon_toolchange": self.ui.excellon_options_form.excellon_opt_group.toolchange_cb,
  723. "excellon_toolchangez": self.ui.excellon_options_form.excellon_opt_group.toolchangez_entry,
  724. "excellon_tooldia": self.ui.excellon_options_form.excellon_opt_group.tooldia_entry,
  725. "excellon_ppname_e": self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb,
  726. "excellon_feedrate_rapid": self.ui.excellon_options_form.excellon_adv_opt_group.feedrate_rapid_entry,
  727. "excellon_toolchangexy": self.ui.excellon_options_form.excellon_adv_opt_group.toolchangexy_entry,
  728. "excellon_f_plunge": self.ui.excellon_options_form.excellon_adv_opt_group.fplunge_cb,
  729. "excellon_startz": self.ui.excellon_options_form.excellon_adv_opt_group.estartz_entry,
  730. "excellon_endz": self.ui.excellon_options_form.excellon_adv_opt_group.eendz_entry,
  731. "geometry_plot": self.ui.geometry_options_form.geometry_gen_group.plot_cb,
  732. "geometry_cnctooldia": self.ui.geometry_options_form.geometry_gen_group.cnctooldia_entry,
  733. "geometry_cutz": self.ui.geometry_options_form.geometry_opt_group.cutz_entry,
  734. "geometry_travelz": self.ui.geometry_options_form.geometry_opt_group.travelz_entry,
  735. "geometry_feedrate": self.ui.geometry_options_form.geometry_opt_group.cncfeedrate_entry,
  736. "geometry_feedrate_z": self.ui.geometry_options_form.geometry_opt_group.cncplunge_entry,
  737. "geometry_spindlespeed": self.ui.geometry_options_form.geometry_opt_group.cncspindlespeed_entry,
  738. "geometry_dwell": self.ui.geometry_options_form.geometry_opt_group.dwell_cb,
  739. "geometry_dwelltime": self.ui.geometry_options_form.geometry_opt_group.dwelltime_entry,
  740. "geometry_ppname_g": self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb,
  741. "geometry_toolchange": self.ui.geometry_options_form.geometry_opt_group.toolchange_cb,
  742. "geometry_toolchangez": self.ui.geometry_options_form.geometry_opt_group.toolchangez_entry,
  743. "geometry_depthperpass": self.ui.geometry_options_form.geometry_opt_group.depthperpass_entry,
  744. "geometry_multidepth": self.ui.geometry_options_form.geometry_opt_group.multidepth_cb,
  745. "geometry_segx": self.ui.geometry_options_form.geometry_adv_opt_group.segx_entry,
  746. "geometry_segy": self.ui.geometry_options_form.geometry_adv_opt_group.segy_entry,
  747. "geometry_feedrate_rapid": self.ui.geometry_options_form.geometry_adv_opt_group.cncfeedrate_rapid_entry,
  748. "geometry_f_plunge": self.ui.geometry_options_form.geometry_adv_opt_group.fplunge_cb,
  749. "geometry_toolchangexy": self.ui.geometry_options_form.geometry_adv_opt_group.toolchangexy_entry,
  750. "geometry_startz": self.ui.geometry_options_form.geometry_adv_opt_group.gstartz_entry,
  751. "geometry_endz": self.ui.geometry_options_form.geometry_adv_opt_group.gendz_entry,
  752. "geometry_extracut": self.ui.geometry_options_form.geometry_adv_opt_group.extracut_cb,
  753. "cncjob_plot": self.ui.cncjob_options_form.cncjob_gen_group.plot_cb,
  754. "cncjob_tooldia": self.ui.cncjob_options_form.cncjob_gen_group.tooldia_entry,
  755. "cncjob_prepend": self.ui.cncjob_options_form.cncjob_opt_group.prepend_text,
  756. "cncjob_append": self.ui.cncjob_options_form.cncjob_opt_group.append_text,
  757. "tools_ncctools": self.ui.tools_options_form.tools_ncc_group.ncc_tool_dia_entry,
  758. "tools_nccoverlap": self.ui.tools_options_form.tools_ncc_group.ncc_overlap_entry,
  759. "tools_nccmargin": self.ui.tools_options_form.tools_ncc_group.ncc_margin_entry,
  760. "tools_cutouttooldia": self.ui.tools_options_form.tools_cutout_group.cutout_tooldia_entry,
  761. "tools_cutoutmargin": self.ui.tools_options_form.tools_cutout_group.cutout_margin_entry,
  762. "tools_cutoutgapsize": self.ui.tools_options_form.tools_cutout_group.cutout_gap_entry,
  763. "tools_gaps_rect": self.ui.tools_options_form.tools_cutout_group.gaps_radio,
  764. "tools_gaps_ff": self.ui.tools_options_form.tools_cutout_group.gaps_combo,
  765. "tools_painttooldia": self.ui.tools_options_form.tools_paint_group.painttooldia_entry,
  766. "tools_paintoverlap": self.ui.tools_options_form.tools_paint_group.paintoverlap_entry,
  767. "tools_paintmargin": self.ui.tools_options_form.tools_paint_group.paintmargin_entry,
  768. "tools_paintmethod": self.ui.tools_options_form.tools_paint_group.paintmethod_combo,
  769. "tools_selectmethod": self.ui.tools_options_form.tools_paint_group.selectmethod_combo,
  770. "tools_pathconnect": self.ui.tools_options_form.tools_paint_group.pathconnect_cb,
  771. "tools_paintcontour": self.ui.tools_options_form.tools_paint_group.contour_cb,
  772. "tools_2sided_mirror_axis": self.ui.tools_options_form.tools_2sided_group.mirror_axis_radio,
  773. "tools_2sided_axis_loc": self.ui.tools_options_form.tools_2sided_group.axis_location_radio,
  774. "tools_2sided_drilldia": self.ui.tools_options_form.tools_2sided_group.drill_dia_entry,
  775. "tools_film_type": self.ui.tools_options_form.tools_film_group.film_type_radio,
  776. "tools_film_boundary": self.ui.tools_options_form.tools_film_group.film_boundary_entry,
  777. "tools_film_scale": self.ui.tools_options_form.tools_film_group.film_scale_entry,
  778. "tools_panelize_spacing_columns": self.ui.tools_options_form.tools_panelize_group.pspacing_columns,
  779. "tools_panelize_spacing_rows": self.ui.tools_options_form.tools_panelize_group.pspacing_rows,
  780. "tools_panelize_columns": self.ui.tools_options_form.tools_panelize_group.pcolumns,
  781. "tools_panelize_rows": self.ui.tools_options_form.tools_panelize_group.prows,
  782. "tools_panelize_constrain": self.ui.tools_options_form.tools_panelize_group.pconstrain_cb,
  783. "tools_panelize_constrainx": self.ui.tools_options_form.tools_panelize_group.px_width_entry,
  784. "tools_panelize_constrainy": self.ui.tools_options_form.tools_panelize_group.py_height_entry
  785. }
  786. for name in list(self.postprocessors.keys()):
  787. self.ui.geometry_options_form.geometry_opt_group.pp_geometry_name_cb.addItem(name)
  788. self.ui.excellon_options_form.excellon_opt_group.pp_excellon_name_cb.addItem(name)
  789. self.options = LoudDict()
  790. self.options.set_change_callback(self.on_options_dict_change)
  791. self.options.update({
  792. "units": "IN",
  793. "global_gridx": 1.0,
  794. "global_gridy": 1.0,
  795. "global_snap_max": 0.05,
  796. "global_background_timeout": 300000, # Default value is 5 minutes
  797. "global_verbose_error_level": 0, # Shell verbosity:
  798. # 0 = default(python trace only for unknown errors),
  799. # 1 = show trace(show trace allways), 2 = (For the future).
  800. "gerber_plot": True,
  801. "gerber_solid": True,
  802. "gerber_multicolored": False,
  803. "gerber_isotooldia": 0.016,
  804. "gerber_isopasses": 1,
  805. "gerber_isooverlap": 0.15,
  806. "gerber_combine_passes": True,
  807. "gerber_noncoppermargin": 0.0,
  808. "gerber_noncopperrounded": False,
  809. "gerber_bboxmargin": 0.0,
  810. "gerber_bboxrounded": False,
  811. "excellon_plot": True,
  812. "excellon_solid": False,
  813. "excellon_format_upper_in": 2,
  814. "excellon_format_lower_in": 4,
  815. "excellon_format_upper_mm": 3,
  816. "excellon_format_lower_mm": 3,
  817. "excellon_units": 'INCH',
  818. "excellon_optimization_type": 'B',
  819. "excellon_search_time": 3,
  820. "excellon_zeros": "L",
  821. "excellon_drillz": -0.1,
  822. "excellon_travelz": 0.1,
  823. "excellon_feedrate": 3.0,
  824. "excellon_feedrate_rapid": 3.0,
  825. "excellon_spindlespeed": None,
  826. "excellon_dwell": True,
  827. "excellon_dwelltime": 1000,
  828. "excellon_toolchange": False,
  829. "excellon_toolchangez": 1.0,
  830. "excellon_toolchangexy": "0.0, 0.0",
  831. "excellon_tooldia": 0.016,
  832. "excellon_ppname_e": 'default',
  833. "excellon_f_plunge": False,
  834. "excellon_startz": None,
  835. "excellon_endz": 2.0,
  836. "geometry_plot": True,
  837. "geometry_segx": 0.0,
  838. "geometry_segy": 0.0,
  839. "geometry_cutz": -0.002,
  840. "geometry_travelz": 0.1,
  841. "geometry_feedrate": 3.0,
  842. "geometry_feedrate_z": 3.0,
  843. "geometry_feedrate_rapid": 3.0,
  844. "geometry_spindlespeed": None,
  845. "geometry_dwell": True,
  846. "geometry_dwelltime": 1000,
  847. "geometry_cnctooldia": 0.016,
  848. "geometry_toolchange": False,
  849. "geometry_toolchangez": 2.0,
  850. "geometry_toolchangexy": "0.0, 0.0",
  851. "geometry_startz": None,
  852. "geometry_endz": 2.0,
  853. "geometry_ppname_g": "default",
  854. "geometry_f_plunge": False,
  855. "geometry_depthperpass": 0.002,
  856. "geometry_multidepth": False,
  857. "geometry_extracut": False,
  858. "cncjob_plot": True,
  859. "cncjob_tooldia": 0.016,
  860. "cncjob_prepend": "",
  861. "cncjob_append": "",
  862. "tools_ncctools": "1.0, 0.5",
  863. "tools_nccoverlap": 0.4,
  864. "tools_nccmargin": 1,
  865. "tools_cutouttooldia": 0.07,
  866. "tools_cutoutmargin": 0.1,
  867. "tools_cutoutgapsize": 0.15,
  868. "tools_gaps_rect": "4",
  869. "tools_gaps_ff": "8",
  870. "tools_painttooldia": 0.07,
  871. "tools_paintoverlap": 0.15,
  872. "tools_paintmargin": 0.0,
  873. "tools_paintmethod": "seed",
  874. "tools_selectmethod": "single",
  875. "tools_pathconnect": True,
  876. "tools_paintcontour": True,
  877. "tools_2sided_mirror_axis": "X",
  878. "tools_2sided_axis_loc": 'point',
  879. "tools_2sided_drilldia": 1,
  880. "tools_film_type": 'neg',
  881. "tools_film_boundary": 1,
  882. "tools_film_scale": 0,
  883. "tools_panelize_spacing_columns": 0,
  884. "tools_panelize_spacing_rows": 0,
  885. "tools_panelize_columns": 1,
  886. "tools_panelize_rows": 1,
  887. "tools_panelize_constrain": False,
  888. "tools_panelize_constrainx": 0.0,
  889. "tools_panelize_constrainy": 0.0
  890. })
  891. self.options.update(self.defaults) # Copy app defaults to project options
  892. self.gen_form = None
  893. self.ger_form = None
  894. self.exc_form = None
  895. self.geo_form = None
  896. self.cnc_form = None
  897. self.tools_form = None
  898. self.on_options_combo_change(0) # Will show the initial form
  899. ### Define OBJECT COLLECTION ###
  900. self.collection = ObjectCollection(self)
  901. self.ui.project_tab_layout.addWidget(self.collection.view)
  902. ###
  903. self.log.debug("Finished creating Object Collection.")
  904. ### Initialize the color box's color in Preferences -> Global -> Color
  905. # Init Plot Colors
  906. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(self.defaults['global_plot_fill'])
  907. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  908. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  909. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.set_value(
  910. int(self.defaults['global_plot_fill'][7:9], 16))
  911. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(
  912. int(self.defaults['global_plot_fill'][7:9], 16))
  913. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(self.defaults['global_plot_line'])
  914. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  915. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  916. # Init Left-Right Selection colors
  917. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(self.defaults['global_sel_fill'])
  918. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  919. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  920. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.set_value(
  921. int(self.defaults['global_sel_fill'][7:9], 16))
  922. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(
  923. int(self.defaults['global_sel_fill'][7:9], 16))
  924. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(self.defaults['global_sel_line'])
  925. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  926. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  927. # Init Right-Left Selection colors
  928. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(self.defaults['global_alt_sel_fill'])
  929. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  930. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  931. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.set_value(
  932. int(self.defaults['global_sel_fill'][7:9], 16))
  933. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(
  934. int(self.defaults['global_sel_fill'][7:9], 16))
  935. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(self.defaults['global_alt_sel_line'])
  936. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  937. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  938. # Init Draw color and Selection Draw Color
  939. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(self.defaults['global_draw_color'])
  940. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  941. "background-color:%s" % str(self.defaults['global_draw_color'])[:7])
  942. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(self.defaults['global_sel_draw_color'])
  943. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  944. "background-color:%s" % str(self.defaults['global_sel_draw_color'])[:7])
  945. #### End of Data ####
  946. #### Plot Area ####
  947. start_plot_time = time.time() # debug
  948. self.plotcanvas = PlotCanvas(self.ui.right_layout, self)
  949. self.plotcanvas.vis_connect('mouse_move', self.on_mouse_move_over_plot)
  950. self.plotcanvas.vis_connect('mouse_press', self.on_mouse_click_over_plot)
  951. self.plotcanvas.vis_connect('mouse_release', self.on_mouse_click_release_over_plot)
  952. self.plotcanvas.vis_connect('mouse_double_click', self.on_double_click_over_plot)
  953. # Keys over plot enabled
  954. self.plotcanvas.vis_connect('key_press', self.ui.keyPressEvent)
  955. self.ui.splitter.setStretchFactor(1, 2)
  956. # So it can receive key presses
  957. self.plotcanvas.vispy_canvas.native.setFocus()
  958. self.app_cursor = self.plotcanvas.new_cursor()
  959. self.app_cursor.enabled = False
  960. # to use for tools like Measurement tool who depends on the event sources who are changed inside the Editors
  961. # depending on from where those tools are called different actions can be done
  962. self.call_source = 'app'
  963. end_plot_time = time.time()
  964. self.log.debug("Finished Canvas initialization in %s seconds." % (str(end_plot_time - start_plot_time)))
  965. ### EDITOR section
  966. self.geo_editor = FlatCAMGeoEditor(self, disabled=True)
  967. self.exc_editor = FlatCAMExcEditor(self)
  968. #### Adjust tabs width ####
  969. # self.collection.view.setMinimumWidth(self.ui.options_scroll_area.widget().sizeHint().width() +
  970. # self.ui.options_scroll_area.verticalScrollBar().sizeHint().width())
  971. self.collection.view.setMinimumWidth(290)
  972. self.log.debug("Finished adding Geometry and Excellon Editor's.")
  973. #### Worker ####
  974. self.workers = WorkerStack()
  975. self.worker_task.connect(self.workers.add_task)
  976. ### Signal handling ###
  977. ## Custom signals
  978. self.inform.connect(self.info)
  979. self.message.connect(self.message_dialog)
  980. self.progress.connect(self.set_progress_bar)
  981. self.object_created.connect(self.on_object_created)
  982. self.object_changed.connect(self.on_object_changed)
  983. self.object_plotted.connect(self.on_object_plotted)
  984. self.plots_updated.connect(self.on_plots_updated)
  985. self.file_opened.connect(self.register_recent)
  986. self.file_opened.connect(lambda kind, filename: self.register_folder(filename))
  987. self.file_saved.connect(lambda kind, filename: self.register_save_folder(filename))
  988. ## Standard signals
  989. # Menu
  990. self.ui.menufilenewproject.triggered.connect(self.on_file_new_click)
  991. self.ui.menufilenewgeo.triggered.connect(self.new_geometry_object)
  992. self.ui.menufilenewexc.triggered.connect(self.new_excellon_object)
  993. self.ui.menufileopengerber.triggered.connect(self.on_fileopengerber)
  994. self.ui.menufileopenexcellon.triggered.connect(self.on_fileopenexcellon)
  995. self.ui.menufileopengcode.triggered.connect(self.on_fileopengcode)
  996. self.ui.menufileopenproject.triggered.connect(self.on_file_openproject)
  997. self.ui.menufileopenconfig.triggered.connect(self.on_file_openconfig)
  998. self.ui.menufilerunscript.triggered.connect(self.on_filerunscript)
  999. self.ui.menufileimportsvg.triggered.connect(lambda: self.on_file_importsvg("geometry"))
  1000. self.ui.menufileimportsvg_as_gerber.triggered.connect(lambda: self.on_file_importsvg("gerber"))
  1001. self.ui.menufileimportdxf.triggered.connect(lambda: self.on_file_importdxf("geometry"))
  1002. self.ui.menufileimportdxf_as_gerber.triggered.connect(lambda: self.on_file_importdxf("gerber"))
  1003. self.ui.menufileexportsvg.triggered.connect(self.on_file_exportsvg)
  1004. self.ui.menufileexportpng.triggered.connect(self.on_file_exportpng)
  1005. self.ui.menufileexportexcellon.triggered.connect(self.on_file_exportexcellon)
  1006. self.ui.menufileexportdxf.triggered.connect(self.on_file_exportdxf)
  1007. self.ui.menufilesaveproject.triggered.connect(self.on_file_saveproject)
  1008. self.ui.menufilesaveprojectas.triggered.connect(self.on_file_saveprojectas)
  1009. self.ui.menufilesaveprojectcopy.triggered.connect(lambda: self.on_file_saveprojectas(make_copy=True))
  1010. self.ui.menufilesavedefaults.triggered.connect(self.on_file_savedefaults)
  1011. self.ui.menufile_exit.triggered.connect(self.on_app_exit)
  1012. self.ui.menueditedit.triggered.connect(self.object2editor)
  1013. self.ui.menueditok.triggered.connect(self.editor2object)
  1014. self.ui.menuedit_convertjoin.triggered.connect(self.on_edit_join)
  1015. self.ui.menuedit_convertjoinexc.triggered.connect(self.on_edit_join_exc)
  1016. self.ui.menuedit_convertjoingrb.triggered.connect(self.on_edit_join_grb)
  1017. self.ui.menuedit_convert_sg2mg.triggered.connect(self.on_convert_singlegeo_to_multigeo)
  1018. self.ui.menuedit_convert_mg2sg.triggered.connect(self.on_convert_multigeo_to_singlegeo)
  1019. self.ui.menueditdelete.triggered.connect(self.on_delete)
  1020. self.ui.menueditcopyobject.triggered.connect(self.on_copy_object)
  1021. self.ui.menueditcopyobjectasgeom.triggered.connect(self.on_copy_object_as_geometry)
  1022. self.ui.menueditorigin.triggered.connect(self.on_set_origin)
  1023. self.ui.menueditjump.triggered.connect(self.on_jump_to)
  1024. self.ui.menuedittoggleunits.triggered.connect(self.on_toggle_units_click)
  1025. self.ui.menueditselectall.triggered.connect(self.on_selectall)
  1026. self.ui.menueditpreferences.triggered.connect(self.on_preferences)
  1027. # self.ui.menuoptions_transfer_a2o.triggered.connect(self.on_options_app2object)
  1028. # self.ui.menuoptions_transfer_a2p.triggered.connect(self.on_options_app2project)
  1029. # self.ui.menuoptions_transfer_o2a.triggered.connect(self.on_options_object2app)
  1030. # self.ui.menuoptions_transfer_p2a.triggered.connect(self.on_options_project2app)
  1031. # self.ui.menuoptions_transfer_o2p.triggered.connect(self.on_options_object2project)
  1032. # self.ui.menuoptions_transfer_p2o.triggered.connect(self.on_options_project2object)
  1033. self.ui.menuoptions_transform_rotate.triggered.connect(self.on_rotate)
  1034. self.ui.menuoptions_transform_skewx.triggered.connect(self.on_skewx)
  1035. self.ui.menuoptions_transform_skewy.triggered.connect(self.on_skewy)
  1036. self.ui.menuoptions_transform_flipx.triggered.connect(self.on_flipx)
  1037. self.ui.menuoptions_transform_flipy.triggered.connect(self.on_flipy)
  1038. self.ui.menuoptions_view_source.triggered.connect(self.on_view_source)
  1039. self.ui.menuviewdisableall.triggered.connect(self.disable_all_plots)
  1040. self.ui.menuviewdisableother.triggered.connect(self.disable_other_plots)
  1041. self.ui.menuviewenable.triggered.connect(self.enable_all_plots)
  1042. self.ui.menuview_zoom_fit.triggered.connect(self.on_zoom_fit)
  1043. self.ui.menuview_zoom_in.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1044. self.ui.menuview_zoom_out.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1045. self.ui.menuview_toggle_code_editor.triggered.connect(self.on_toggle_code_editor)
  1046. self.ui.menuview_toggle_fscreen.triggered.connect(self.on_fullscreen)
  1047. self.ui.menuview_toggle_parea.triggered.connect(self.on_toggle_plotarea)
  1048. self.ui.menuview_toggle_notebook.triggered.connect(self.on_toggle_notebook)
  1049. self.ui.menuview_toggle_grid.triggered.connect(self.on_toggle_grid)
  1050. self.ui.menuview_toggle_axis.triggered.connect(self.on_toggle_axis)
  1051. self.ui.menuview_toggle_workspace.triggered.connect(self.on_workspace_menu)
  1052. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1053. self.ui.menuhelp_about.triggered.connect(self.on_about)
  1054. self.ui.menuhelp_home.triggered.connect(lambda: webbrowser.open(self.app_url))
  1055. self.ui.menuhelp_manual.triggered.connect(lambda: webbrowser.open(self.manual_url))
  1056. self.ui.menuhelp_videohelp.triggered.connect(lambda: webbrowser.open(self.video_url))
  1057. self.ui.menuhelp_shortcut_list.triggered.connect(self.on_shortcut_list)
  1058. self.ui.menuprojectenable.triggered.connect(lambda: self.enable_plots(self.collection.get_selected()))
  1059. self.ui.menuprojectdisable.triggered.connect(lambda: self.disable_plots(self.collection.get_selected()))
  1060. self.ui.menuprojectgeneratecnc.triggered.connect(lambda: self.generate_cnc_job(self.collection.get_selected()))
  1061. self.ui.menuprojectviewsource.triggered.connect(self.on_view_source)
  1062. self.ui.menuprojectcopy.triggered.connect(self.on_copy_object)
  1063. self.ui.menuprojectedit.triggered.connect(self.object2editor)
  1064. self.ui.menuprojectdelete.triggered.connect(self.on_delete)
  1065. self.ui.menuprojectsave.triggered.connect(self.on_project_context_save)
  1066. self.ui.menuprojectproperties.triggered.connect(self.obj_properties)
  1067. # Toolbar
  1068. #self.ui.file_new_btn.triggered.connect(self.on_file_new)
  1069. self.ui.file_open_btn.triggered.connect(self.on_file_openproject)
  1070. self.ui.file_save_btn.triggered.connect(self.on_file_saveproject)
  1071. self.ui.file_open_gerber_btn.triggered.connect(self.on_fileopengerber)
  1072. self.ui.file_open_excellon_btn.triggered.connect(self.on_fileopenexcellon)
  1073. self.ui.clear_plot_btn.triggered.connect(self.clear_plots)
  1074. self.ui.replot_btn.triggered.connect(self.plot_all)
  1075. self.ui.zoom_fit_btn.triggered.connect(self.on_zoom_fit)
  1076. self.ui.zoom_in_btn.triggered.connect(lambda: self.plotcanvas.zoom(1 / 1.5))
  1077. self.ui.zoom_out_btn.triggered.connect(lambda: self.plotcanvas.zoom(1.5))
  1078. self.ui.newgeo_btn.triggered.connect(self.new_geometry_object)
  1079. self.ui.newexc_btn.triggered.connect(self.new_excellon_object)
  1080. self.ui.editgeo_btn.triggered.connect(self.object2editor)
  1081. self.ui.update_obj_btn.triggered.connect(self.editor2object)
  1082. self.ui.delete_btn.triggered.connect(self.on_delete)
  1083. self.ui.shell_btn.triggered.connect(self.on_toggle_shell)
  1084. # Tools Toolbar Signals
  1085. self.ui.dblsided_btn.triggered.connect(lambda: self.dblsidedtool.run())
  1086. self.ui.cutout_btn.triggered.connect(lambda: self.cutout_tool.run())
  1087. self.ui.ncc_btn.triggered.connect(lambda: self.ncclear_tool.run())
  1088. self.ui.paint_btn.triggered.connect(lambda: self.paint_tool.run())
  1089. self.ui.panelize_btn.triggered.connect(lambda: self.panelize_tool.run())
  1090. self.ui.film_btn.triggered.connect(lambda: self.film_tool.run())
  1091. self.ui.solder_btn.triggered.connect(lambda: self.paste_tool.run())
  1092. self.ui.calculators_btn.triggered.connect(lambda: self.calculator_tool.run())
  1093. self.ui.transform_btn.triggered.connect(lambda: self.transform_tool.run())
  1094. # Context Menu
  1095. self.ui.popmenu_disable.triggered.connect(lambda: self.disable_plots(self.collection.get_selected()))
  1096. self.ui.popmenu_new_geo.triggered.connect(self.new_geometry_object)
  1097. self.ui.popmenu_new_exc.triggered.connect(self.new_excellon_object)
  1098. self.ui.popmenu_new_prj.triggered.connect(self.on_file_new)
  1099. self.ui.draw_line.triggered.connect(self.geo_editor.draw_tool_path)
  1100. self.ui.draw_rect.triggered.connect(self.geo_editor.draw_tool_rectangle)
  1101. self.ui.draw_cut.triggered.connect(self.geo_editor.cutpath)
  1102. self.ui.draw_move.triggered.connect(self.geo_editor.on_move)
  1103. self.ui.drill.triggered.connect(self.exc_editor.exc_add_drill)
  1104. self.ui.drill_array.triggered.connect(self.exc_editor.exc_add_drill_array)
  1105. self.ui.drill_copy.triggered.connect(self.exc_editor.exc_copy_drills)
  1106. self.ui.zoomfit.triggered.connect(self.on_zoom_fit)
  1107. self.ui.clearplot.triggered.connect(self.clear_plots)
  1108. self.ui.replot.triggered.connect(self.plot_all)
  1109. self.ui.popmenu_copy.triggered.connect(self.on_copy_object)
  1110. self.ui.popmenu_delete.triggered.connect(self.on_delete)
  1111. self.ui.popmenu_edit.triggered.connect(self.object2editor)
  1112. self.ui.popmenu_save.triggered.connect(self.editor2object)
  1113. self.ui.popmenu_move.triggered.connect(self.obj_move)
  1114. self.ui.popmenu_properties.triggered.connect(self.obj_properties)
  1115. # Preferences Plot Area TAB
  1116. self.ui.options_combo.activated.connect(self.on_options_combo_change)
  1117. self.ui.pref_save_button.clicked.connect(self.on_save_button)
  1118. self.ui.pref_import_button.clicked.connect(self.on_import_preferences)
  1119. self.ui.pref_export_button.clicked.connect(self.on_export_preferences)
  1120. self.ui.pref_open_button.clicked.connect(self.on_preferences_open_folder)
  1121. ###############################
  1122. ### GUI PREFERENCES SIGNALS ###
  1123. ###############################
  1124. self.ui.general_options_form.general_app_group.units_radio.group_toggle_fn = self.on_toggle_units
  1125. self.ui.general_defaults_form.general_app_group.language_apply_btn.clicked.connect(self.on_language_apply)
  1126. ###############################
  1127. ### GUI PREFERENCES SIGNALS ###
  1128. ###############################
  1129. # Setting plot colors signals
  1130. self.ui.general_defaults_form.general_gui_group.pf_color_entry.editingFinished.connect(self.on_pf_color_entry)
  1131. self.ui.general_defaults_form.general_gui_group.pf_color_button.clicked.connect(self.on_pf_color_button)
  1132. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.valueChanged.connect(self.on_pf_color_spinner)
  1133. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.valueChanged.connect(self.on_pf_color_slider)
  1134. self.ui.general_defaults_form.general_gui_group.pl_color_entry.editingFinished.connect(self.on_pl_color_entry)
  1135. self.ui.general_defaults_form.general_gui_group.pl_color_button.clicked.connect(self.on_pl_color_button)
  1136. # Setting selection (left - right) colors signals
  1137. self.ui.general_defaults_form.general_gui_group.sf_color_entry.editingFinished.connect(self.on_sf_color_entry)
  1138. self.ui.general_defaults_form.general_gui_group.sf_color_button.clicked.connect(self.on_sf_color_button)
  1139. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.valueChanged.connect(self.on_sf_color_spinner)
  1140. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.valueChanged.connect(self.on_sf_color_slider)
  1141. self.ui.general_defaults_form.general_gui_group.sl_color_entry.editingFinished.connect(self.on_sl_color_entry)
  1142. self.ui.general_defaults_form.general_gui_group.sl_color_button.clicked.connect(self.on_sl_color_button)
  1143. # Setting selection (right - left) colors signals
  1144. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.editingFinished.connect(self.on_alt_sf_color_entry)
  1145. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.clicked.connect(self.on_alt_sf_color_button)
  1146. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.valueChanged.connect(
  1147. self.on_alt_sf_color_spinner)
  1148. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.valueChanged.connect(
  1149. self.on_alt_sf_color_slider)
  1150. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.editingFinished.connect(self.on_alt_sl_color_entry)
  1151. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.clicked.connect(self.on_alt_sl_color_button)
  1152. # Setting Editor Draw colors signals
  1153. self.ui.general_defaults_form.general_gui_group.draw_color_entry.editingFinished.connect(self.on_draw_color_entry)
  1154. self.ui.general_defaults_form.general_gui_group.draw_color_button.clicked.connect(self.on_draw_color_button)
  1155. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.editingFinished.connect(self.on_sel_draw_color_entry)
  1156. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.clicked.connect(self.on_sel_draw_color_button)
  1157. self.ui.general_defaults_form.general_gui_group.wk_cb.currentIndexChanged.connect(self.on_workspace_modified)
  1158. self.ui.general_defaults_form.general_gui_group.workspace_cb.stateChanged.connect(self.on_workspace)
  1159. self.ui.general_defaults_form.general_gui_set_group.layout_combo.activated.connect(self.on_layout)
  1160. # Modify G-CODE Plot Area TAB
  1161. self.ui.code_editor.textChanged.connect(self.handleTextChanged)
  1162. self.ui.buttonOpen.clicked.connect(self.handleOpen)
  1163. self.ui.buttonPrint.clicked.connect(self.handlePrint)
  1164. self.ui.buttonPreview.clicked.connect(self.handlePreview)
  1165. self.ui.buttonSave.clicked.connect(self.handleSaveGCode)
  1166. self.ui.buttonFind.clicked.connect(self.handleFindGCode)
  1167. self.ui.buttonReplace.clicked.connect(self.handleReplaceGCode)
  1168. # Object list
  1169. self.collection.view.activated.connect(self.on_row_activated)
  1170. # Monitor the checkbox from the Application Defaults Tab and show the TCL shell or not depending on it's value
  1171. self.ui.general_defaults_form.general_app_group.shell_startup_cb.clicked.connect(self.on_toggle_shell)
  1172. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1173. self.ui.excellon_defaults_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1174. self.on_excellon_defaults_button)
  1175. # Load the defaults values into the Excellon Format and Excellon Zeros fields
  1176. self.ui.excellon_options_form.excellon_opt_group.excellon_defaults_button.clicked.connect(
  1177. self.on_excellon_options_button)
  1178. # this is a flag to signal to other tools that the ui tooltab is locked and not accessible
  1179. self.tool_tab_locked = False
  1180. # decide if to show or hide the Notebook side of the screen at startup
  1181. if self.defaults["global_project_at_startup"] is True:
  1182. self.ui.splitter.setSizes([1, 1])
  1183. else:
  1184. self.ui.splitter.setSizes([0, 1])
  1185. ####################
  1186. ### Other setups ###
  1187. ####################
  1188. # Sets up FlatCAMObj, FCProcess and FCProcessContainer.
  1189. self.setup_obj_classes()
  1190. self.setup_recent_items()
  1191. self.setup_component_editor()
  1192. #############
  1193. ### Shell ###
  1194. #############
  1195. ###
  1196. # Auto-complete KEYWORDS
  1197. self.tcl_commands_list = ['add_circle', 'add_poly', 'add_polygon', 'add_polyline', 'add_rectangle',
  1198. 'aligndrill', 'clear',
  1199. 'aligndrillgrid', 'cncjob', 'cutout', 'delete', 'drillcncjob',
  1200. 'export_gcode',
  1201. 'export_svg', 'ext', 'exteriors', 'follow', 'geo_union', 'geocutout', 'get_names',
  1202. 'get_sys', 'getsys', 'help', 'import_svg', 'interiors', 'isolate', 'join_excellon',
  1203. 'join_excellons', 'join_geometries', 'join_geometry', 'list_sys', 'listsys', 'mill',
  1204. 'millholes', 'mirror', 'new', 'new_geometry', 'offset', 'open_excellon', 'open_gcode',
  1205. 'open_gerber', 'open_project', 'options', 'paint', 'pan', 'panel', 'panelize', 'plot',
  1206. 'save', 'save_project', 'save_sys', 'scale', 'set_active', 'set_sys', 'setsys',
  1207. 'skew', 'subtract_poly', 'subtract_rectangle', 'version', 'write_gcode'
  1208. ]
  1209. self.ordinary_keywords = ['name', 'center_x', 'center_y', 'radius', 'x0', 'y0', 'x1', 'y1', 'box', 'axis',
  1210. 'holes','grid', 'minoffset', 'gridoffset','axisoffset', 'dia', 'dist', 'gridoffsetx',
  1211. 'gridoffsety', 'columns', 'rows', 'z_cut', 'z_move', 'feedrate', 'feedrate_rapid',
  1212. 'tooldia', 'multidepth', 'extracut', 'depthperpass', 'ppname_g', 'outname', 'margin',
  1213. 'gaps', 'gapsize', 'tools', 'drillz', 'travelz', 'spindlespeed', 'toolchange',
  1214. 'toolchangez', 'endz', 'ppname_e', 'opt_type', 'preamble', 'postamble', 'filename',
  1215. 'scale_factor', 'type', 'passes', 'overlap', 'combine', 'use_threads', 'x', 'y',
  1216. 'follow', 'all', 'spacing_columns', 'spacing_rows', 'factor', 'value', 'angle_x',
  1217. 'angle_y', 'gridx', 'gridy', 'True', 'False'
  1218. ]
  1219. self.myKeywords = self.tcl_commands_list + self.ordinary_keywords
  1220. self.shell = FCShell(self, version=self.version)
  1221. self.shell._edit.set_model_data(self.myKeywords)
  1222. self.shell.setWindowIcon(self.ui.app_icon)
  1223. self.shell.setWindowTitle("FlatCAM Shell")
  1224. self.shell.resize(*self.defaults["global_shell_shape"])
  1225. self.shell.append_output("FlatCAM %s (c)2014-2019 Juan Pablo Caram " % self.version)
  1226. self.shell.append_output("(Type help to get started)\n\n")
  1227. self.init_tcl()
  1228. self.ui.shell_dock = QtWidgets.QDockWidget("FlatCAM TCL Shell")
  1229. self.ui.shell_dock.setObjectName('Shell_DockWidget')
  1230. self.ui.shell_dock.setWidget(self.shell)
  1231. self.ui.shell_dock.setAllowedAreas(QtCore.Qt.AllDockWidgetAreas)
  1232. self.ui.shell_dock.setFeatures(QtWidgets.QDockWidget.DockWidgetMovable |
  1233. QtWidgets.QDockWidget.DockWidgetFloatable |
  1234. QtWidgets.QDockWidget.DockWidgetClosable)
  1235. self.ui.addDockWidget(QtCore.Qt.BottomDockWidgetArea, self.ui.shell_dock)
  1236. # show TCL shell at start-up based on the Menu -? Edit -> Preferences setting.
  1237. if self.defaults["global_shell_at_startup"]:
  1238. self.ui.shell_dock.show()
  1239. else:
  1240. self.ui.shell_dock.hide()
  1241. #########################
  1242. ### Tools and Plugins ###
  1243. #########################
  1244. # always install tools only after the shell is initialized because the self.inform.emit() depends on shell
  1245. self.install_tools()
  1246. ### System Font Parsing ###
  1247. # self.f_parse = ParseFont(self)
  1248. # self.parse_system_fonts()
  1249. # test if the program was started with a script as parameter
  1250. if self.cmd_line_shellfile:
  1251. try:
  1252. with open(self.cmd_line_shellfile, "r") as myfile:
  1253. cmd_line_shellfile_text = myfile.read()
  1254. self.shell._sysShell.exec_command(cmd_line_shellfile_text)
  1255. except Exception as ext:
  1256. print("ERROR: ", ext)
  1257. sys.exit(2)
  1258. ###########################
  1259. #### Check for updates ####
  1260. ###########################
  1261. # Separate thread (Not worker)
  1262. # Check for updates on startup but only if the user consent and the app is not in Beta version
  1263. if (self.beta is False or self.beta is None) and \
  1264. self.ui.general_defaults_form.general_gui_group.version_check_cb.get_value() is True:
  1265. App.log.info("Checking for updates in backgroud (this is version %s)." % str(self.version))
  1266. self.thr2 = QtCore.QThread()
  1267. self.worker_task.emit({'fcn': self.version_check,
  1268. 'params': []})
  1269. self.thr2.start()
  1270. ####################################
  1271. #### Variables for global usage ####
  1272. ####################################
  1273. # coordinates for relative position display
  1274. self.rel_point1 = (0, 0)
  1275. self.rel_point2 = (0, 0)
  1276. # variable to store coordinates
  1277. self.pos = (0, 0)
  1278. self.pos_jump = (0, 0)
  1279. # variable to store if there was motion before right mouse button click (panning)
  1280. self.panning_action = False
  1281. # variable to store if a command is active (then the var is not None) and which one it is
  1282. self.command_active = None
  1283. # variable to store the status of moving selection action
  1284. # None value means that it's not an selection action
  1285. # True value = a selection from left to right
  1286. # False value = a selection from right to left
  1287. self.selection_type = None
  1288. # List to store the objects that are currently loaded in FlatCAM
  1289. # This list is updated on each object creation or object delete
  1290. self.all_objects_list = []
  1291. # List to store the objects that are selected
  1292. self.sel_objects_list = []
  1293. # holds the key modifier if pressed (CTRL, SHIFT or ALT)
  1294. self.key_modifiers = None
  1295. # Variable to hold the status of the axis
  1296. self.toggle_axis = True
  1297. # Variable to store the status of the fullscreen event
  1298. self.toggle_fscreen = False
  1299. # Variable to store the status of the code editor
  1300. self.toggle_codeeditor = False
  1301. self.cursor = None
  1302. # Variable to store the GCODE that was edited
  1303. self.gcode_edited = ""
  1304. self.grb_list = ['gbr', 'ger', 'gtl', 'gbl', 'gts', 'gbs', 'gtp', 'gbp', 'gto', 'gbo', 'gm1', 'gm2', 'gm3', 'gko',
  1305. 'cmp', 'sol', 'stc', 'sts', 'plc', 'pls', 'crc', 'crs', 'tsm', 'bsm', 'ly2', 'ly15', 'dim', 'mil',
  1306. 'grb', 'top', 'bot', 'smt', 'smb', 'sst', 'ssb', 'spt', 'spb', 'pho', 'gdo', 'art', 'gbd']
  1307. self.exc_list = ['drl', 'txt', 'xln', 'drd', 'tap', 'exc']
  1308. self.gcode_list = ['nc', 'ncc', 'tap', 'gcode', 'cnc', 'ecs', 'fnc', 'dnc', 'ncg', 'gc', 'fan', 'fgc', 'din',
  1309. 'xpi', 'hnc', 'h', 'i', 'ncp', 'min', 'gcd', 'rol', 'mpr', 'ply', 'out', 'eia', 'plt', 'sbp',
  1310. 'mpf']
  1311. self.svg_list = ['svg']
  1312. self.dxf_list = ['dxf']
  1313. self.prj_list = ['flatprj']
  1314. # global variable used by NCC Tool to signal that some polygons could not be cleared, if True
  1315. # flag for polygons not cleared
  1316. self.poly_not_cleared = False
  1317. ### Save defaults to factory_defaults.FlatConfig file ###
  1318. ### It's done only once after install #############
  1319. factory_file = open(self.data_path + '/factory_defaults.FlatConfig')
  1320. fac_def_from_file = factory_file.read()
  1321. factory_defaults = json.loads(fac_def_from_file)
  1322. # if the file contain an empty dictionary then save the factory defaults into the file
  1323. if not factory_defaults:
  1324. self.save_factory_defaults(silent=False)
  1325. # ONLY AT FIRST STARTUP INIT THE GUI LAYOUT TO 'COMPACT'
  1326. self.on_layout(index=None, lay='compact')
  1327. factory_file.close()
  1328. # and then make the factory_defaults.FlatConfig file read_only os it can't be modified after creation.
  1329. filename_factory = self.data_path + '/factory_defaults.FlatConfig'
  1330. os.chmod(filename_factory, S_IREAD | S_IRGRP | S_IROTH)
  1331. # Post-GUI initialization: Experimental attempt
  1332. # to perform unit tests on the GUI.
  1333. # if post_gui is not None:
  1334. # post_gui(self)
  1335. App.log.debug("END of constructor. Releasing control.")
  1336. # accept a project file as command line parameter
  1337. # the path/file_name must be enclosed in quotes if it contain spaces
  1338. for argument in App.args:
  1339. if '.FlatPrj' in argument:
  1340. try:
  1341. project_name = str(argument)
  1342. if project_name == "":
  1343. self.inform.emit("Open cancelled.")
  1344. else:
  1345. # self.open_project(project_name)
  1346. run_from_arg = True
  1347. self.worker_task.emit({'fcn': self.open_project,
  1348. 'params': [project_name, run_from_arg]})
  1349. except Exception as e:
  1350. log.debug("Could not open FlatCAM project file as App parameter due: %s" % str(e))
  1351. if '.FlatConfig' in argument:
  1352. try:
  1353. file_name = str(argument)
  1354. if file_name == "":
  1355. self.inform.emit("Open Config file failed.")
  1356. else:
  1357. # run_from_arg = True
  1358. # self.worker_task.emit({'fcn': self.open_config_file,
  1359. # 'params': [file_name, run_from_arg]})
  1360. self.open_config_file(file_name, run_from_arg=True)
  1361. except Exception as e:
  1362. log.debug("Could not open FlatCAM Config file as App parameter due: %s" % str(e))
  1363. def defaults_read_form(self):
  1364. for option in self.defaults_form_fields:
  1365. try:
  1366. self.defaults[option] = self.defaults_form_fields[option].get_value()
  1367. except:
  1368. pass
  1369. def defaults_write_form(self):
  1370. for option in self.defaults:
  1371. self.defaults_write_form_field(option)
  1372. # try:
  1373. # self.defaults_form_fields[option].set_value(self.defaults[option])
  1374. # except KeyError:
  1375. # #self.log.debug("defaults_write_form(): No field for: %s" % option)
  1376. # # TODO: Rethink this?
  1377. # pass
  1378. def defaults_write_form_field(self, field):
  1379. try:
  1380. self.defaults_form_fields[field].set_value(self.defaults[field])
  1381. except KeyError:
  1382. #self.log.debug("defaults_write_form(): No field for: %s" % option)
  1383. # TODO: Rethink this?
  1384. pass
  1385. def clear_pool(self):
  1386. self.pool.close()
  1387. self.pool = Pool()
  1388. self.pool_recreated.emit(self.pool)
  1389. gc.collect()
  1390. # the order that the tools are installed is important as they can depend on each other install position
  1391. def install_tools(self):
  1392. self.dblsidedtool = DblSidedTool(self)
  1393. self.dblsidedtool.install(icon=QtGui.QIcon('share/doubleside16.png'), separator=True)
  1394. self.measurement_tool = Measurement(self)
  1395. self.measurement_tool.install(icon=QtGui.QIcon('share/measure16.png'), separator=True)
  1396. self.panelize_tool = Panelize(self)
  1397. self.panelize_tool.install(icon=QtGui.QIcon('share/panel16.png'))
  1398. self.film_tool = Film(self)
  1399. self.film_tool.install(icon=QtGui.QIcon('share/film16.png'))
  1400. self.paste_tool = SolderPaste(self)
  1401. self.paste_tool.install(icon=QtGui.QIcon('share/solderpastebis32.png'), separator=True)
  1402. self.move_tool = ToolMove(self)
  1403. self.move_tool.install(icon=QtGui.QIcon('share/move16.png'), pos=self.ui.menuedit,
  1404. before=self.ui.menueditorigin)
  1405. self.cutout_tool = CutOut(self)
  1406. self.cutout_tool.install(icon=QtGui.QIcon('share/cut16.png'), pos=self.ui.menutool,
  1407. before=self.measurement_tool.menuAction)
  1408. self.ncclear_tool = NonCopperClear(self)
  1409. self.ncclear_tool.install(icon=QtGui.QIcon('share/flatcam_icon16.png'), pos=self.ui.menutool,
  1410. before=self.measurement_tool.menuAction, separator=True)
  1411. self.paint_tool = ToolPaint(self)
  1412. self.paint_tool.install(icon=QtGui.QIcon('share/paint16.png'), pos=self.ui.menutool,
  1413. before=self.measurement_tool.menuAction, separator=True)
  1414. self.calculator_tool = ToolCalculator(self)
  1415. self.calculator_tool.install(icon=QtGui.QIcon('share/calculator24.png'))
  1416. self.transform_tool = ToolTransform(self)
  1417. self.transform_tool.install(icon=QtGui.QIcon('share/transform.png'), pos=self.ui.menuoptions, separator=True)
  1418. self.properties_tool = Properties(self)
  1419. self.properties_tool.install(icon=QtGui.QIcon('share/properties32.png'), pos=self.ui.menuoptions)
  1420. self.image_tool = ToolImage(self)
  1421. self.image_tool.install(icon=QtGui.QIcon('share/image32.png'), pos=self.ui.menufileimport,
  1422. separator=True)
  1423. self.log.debug("Tools are installed.")
  1424. def remove_tools(self):
  1425. for act in self.ui.menutool.actions():
  1426. self.ui.menutool.removeAction(act)
  1427. def init_tools(self):
  1428. log.debug("init_tools()")
  1429. # delete the data currently in the Tools Tab and the Tab itself
  1430. widget = QtWidgets.QTabWidget.widget(self.ui.notebook, 2)
  1431. if widget is not None:
  1432. widget.deleteLater()
  1433. self.ui.notebook.removeTab(2)
  1434. # rebuild the Tools Tab
  1435. self.ui.tool_tab = QtWidgets.QWidget()
  1436. self.ui.tool_tab_layout = QtWidgets.QVBoxLayout(self.ui.tool_tab)
  1437. self.ui.tool_tab_layout.setContentsMargins(2, 2, 2, 2)
  1438. self.ui.notebook.addTab(self.ui.tool_tab, "Tool")
  1439. self.ui.tool_scroll_area = VerticalScrollArea()
  1440. self.ui.tool_tab_layout.addWidget(self.ui.tool_scroll_area)
  1441. # reinstall all the Tools as some may have been removed when the data was removed from the Tools Tab
  1442. # first remove all of them
  1443. self.remove_tools()
  1444. # second re add the TCL Shell action to the Tools menu and reconnect it to ist slot function
  1445. self.ui.menutoolshell = self.ui.menutool.addAction(QtGui.QIcon('share/shell16.png'), '&Command Line\tS')
  1446. self.ui.menutoolshell.triggered.connect(self.on_toggle_shell)
  1447. # third install all of them
  1448. self.install_tools()
  1449. self.log.debug("Tools are initialized.")
  1450. # def parse_system_fonts(self):
  1451. # self.worker_task.emit({'fcn': self.f_parse.get_fonts_by_types,
  1452. # 'params': []})
  1453. def object2editor(self):
  1454. """
  1455. Send the current Geometry or Excellon object (if any) into the editor.
  1456. :return: None
  1457. """
  1458. self.report_usage("object2editor()")
  1459. # adjust the visibility of some of the canvas context menu
  1460. self.ui.popmenu_edit.setVisible(False)
  1461. self.ui.popmenu_save.setVisible(True)
  1462. edited_object = self.collection.get_active()
  1463. if isinstance(edited_object, FlatCAMGeometry):
  1464. # for now, if the Geometry is MultiGeo do not allow the editing
  1465. if edited_object.multigeo is True:
  1466. self.inform.emit("[WARNING_NOTCL]Editing a MultiGeo Geometry is not possible for the moment.")
  1467. return
  1468. # store the Geometry Editor Toolbar visibility before entering in the Editor
  1469. self.geo_editor.toolbar_old_state = True if self.ui.geo_edit_toolbar.isVisible() else False
  1470. self.geo_editor.edit_fcgeometry(edited_object)
  1471. # we set the notebook to hidden
  1472. self.ui.splitter.setSizes([0, 1])
  1473. # set call source to the Editor we go into
  1474. self.call_source = 'geo_editor'
  1475. elif isinstance(edited_object, FlatCAMExcellon):
  1476. # store the Excellon Editor Toolbar visibility before entering in the Editor
  1477. self.exc_editor.toolbar_old_state = True if self.ui.exc_edit_toolbar.isVisible() else False
  1478. self.exc_editor.edit_fcexcellon(edited_object)
  1479. # set call source to the Editor we go into
  1480. self.call_source = 'exc_editor'
  1481. else:
  1482. self.inform.emit("[WARNING_NOTCL]Select a Geometry or Excellon Object to edit.")
  1483. return
  1484. # make sure that we can't select another object while in Editor Mode:
  1485. self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.NoSelection)
  1486. # delete any selection shape that might be active as they are not relevant in Editor
  1487. self.delete_selection_shape()
  1488. self.ui.plot_tab_area.setTabText(0, "EDITOR Area")
  1489. self.ui.plot_tab_area.protectTab(0)
  1490. self.inform.emit("[WARNING_NOTCL]Editor is activated ...")
  1491. self.should_we_save = True
  1492. def editor2object(self):
  1493. """
  1494. Transfers the Geometry or Excellon from the editor to the current object.
  1495. :return: None
  1496. """
  1497. self.report_usage("editor2object()")
  1498. # adjust the visibility of some of the canvas context menu
  1499. self.ui.popmenu_edit.setVisible(True)
  1500. self.ui.popmenu_save.setVisible(False)
  1501. edited_obj = self.collection.get_active()
  1502. obj_type = ""
  1503. if isinstance(edited_obj, FlatCAMGeometry):
  1504. obj_type = "Geometry"
  1505. self.geo_editor.update_fcgeometry(edited_obj)
  1506. self.geo_editor.update_options(edited_obj)
  1507. self.geo_editor.deactivate()
  1508. # update the geo object options so it is including the bounding box values
  1509. try:
  1510. xmin, ymin, xmax, ymax = edited_obj.bounds()
  1511. edited_obj.options['xmin'] = xmin
  1512. edited_obj.options['ymin'] = ymin
  1513. edited_obj.options['xmax'] = xmax
  1514. edited_obj.options['ymax'] = ymax
  1515. except AttributeError:
  1516. self.inform.emit("[WARNING] Object empty after edit.")
  1517. elif isinstance(edited_obj, FlatCAMExcellon):
  1518. obj_type = "Excellon"
  1519. self.exc_editor.update_fcexcellon(edited_obj)
  1520. self.exc_editor.update_options(edited_obj)
  1521. self.exc_editor.deactivate()
  1522. else:
  1523. self.inform.emit("[WARNING_NOTCL]Select a Geometry or Excellon Object to update.")
  1524. return
  1525. # if notebook is hidden we show it
  1526. if self.ui.splitter.sizes()[0] == 0:
  1527. self.ui.splitter.setSizes([1, 1])
  1528. # restore the call_source to app
  1529. self.call_source = 'app'
  1530. edited_obj.plot()
  1531. self.ui.plot_tab_area.setTabText(0, "Plot Area")
  1532. self.ui.plot_tab_area.protectTab(0)
  1533. self.inform.emit("[selected] %s is updated, returning to App..." % obj_type)
  1534. # reset the Object UI to original settings
  1535. # edited_obj.set_ui(edited_obj.ui_type())
  1536. # edited_obj.build_ui()
  1537. # make sure that we reenable the selection on Project Tab after returning from Editor Mode:
  1538. self.collection.view.setSelectionMode(QtWidgets.QAbstractItemView.ExtendedSelection)
  1539. def get_last_folder(self):
  1540. return self.defaults["global_last_folder"]
  1541. def get_last_save_folder(self):
  1542. loc = self.defaults["global_last_save_folder"]
  1543. if loc is None:
  1544. loc = self.defaults["global_last_folder"]
  1545. if loc is None:
  1546. loc = os.path.dirname(__file__)
  1547. return loc
  1548. def report_usage(self, resource):
  1549. """
  1550. Increments usage counter for the given resource
  1551. in self.defaults['global_stats'].
  1552. :param resource: Name of the resource.
  1553. :return: None
  1554. """
  1555. if resource in self.defaults['global_stats']:
  1556. self.defaults['global_stats'][resource] += 1
  1557. else:
  1558. self.defaults['global_stats'][resource] = 1
  1559. def init_tcl(self):
  1560. if hasattr(self,'tcl'):
  1561. # self.tcl = None
  1562. # TODO we need to clean non default variables and procedures here
  1563. # new object cannot be used here as it will not remember values created for next passes,
  1564. # because tcl was execudted in old instance of TCL
  1565. pass
  1566. else:
  1567. self.tcl = tk.Tcl()
  1568. self.setup_shell()
  1569. self.log.debug("TCL Shell has been initialized.")
  1570. # TODO: This shouldn't be here.
  1571. class TclErrorException(Exception):
  1572. """
  1573. this exception is deffined here, to be able catch it if we sucessfully handle all errors from shell command
  1574. """
  1575. pass
  1576. def shell_message(self, msg, show=False, error=False, warning=False, success=False, selected=False):
  1577. """
  1578. Shows a message on the FlatCAM Shell
  1579. :param msg: Message to display.
  1580. :param show: Opens the shell.
  1581. :param error: Shows the message as an error.
  1582. :return: None
  1583. """
  1584. if show:
  1585. self.ui.shell_dock.show()
  1586. try:
  1587. if error:
  1588. self.shell.append_error(msg + "\n")
  1589. elif warning:
  1590. self.shell.append_warning(msg + "\n")
  1591. elif success:
  1592. self.shell.append_success(msg + "\n")
  1593. elif selected:
  1594. self.shell.append_selected(msg + "\n")
  1595. else:
  1596. self.shell.append_output(msg + "\n")
  1597. except AttributeError:
  1598. log.debug("shell_message() is called before Shell Class is instantiated. The message is: %s", str(msg))
  1599. def raise_tcl_unknown_error(self, unknownException):
  1600. """
  1601. Raise exception if is different type than TclErrorException
  1602. this is here mainly to show unknown errors inside TCL shell console.
  1603. :param unknownException:
  1604. :return:
  1605. """
  1606. if not isinstance(unknownException, self.TclErrorException):
  1607. self.raise_tcl_error("Unknown error: %s" % str(unknownException))
  1608. else:
  1609. raise unknownException
  1610. def display_tcl_error(self, error, error_info=None):
  1611. """
  1612. escape bracket [ with \ otherwise there is error
  1613. "ERROR: missing close-bracket" instead of real error
  1614. :param error: it may be text or exception
  1615. :return: None
  1616. """
  1617. if isinstance(error, Exception):
  1618. exc_type, exc_value, exc_traceback = error_info
  1619. if not isinstance(error, self.TclErrorException):
  1620. show_trace = 1
  1621. else:
  1622. show_trace = int(self.defaults['global_verbose_error_level'])
  1623. if show_trace > 0:
  1624. trc = traceback.format_list(traceback.extract_tb(exc_traceback))
  1625. trc_formated = []
  1626. for a in reversed(trc):
  1627. trc_formated.append(a.replace(" ", " > ").replace("\n", ""))
  1628. text = "%s\nPython traceback: %s\n%s" % (exc_value,
  1629. exc_type,
  1630. "\n".join(trc_formated))
  1631. else:
  1632. text = "%s" % error
  1633. else:
  1634. text = error
  1635. text = text.replace('[', '\\[').replace('"', '\\"')
  1636. self.tcl.eval('return -code error "%s"' % text)
  1637. def raise_tcl_error(self, text):
  1638. """
  1639. this method pass exception from python into TCL as error, so we get stacktrace and reason
  1640. :param text: text of error
  1641. :return: raise exception
  1642. """
  1643. self.display_tcl_error(text)
  1644. raise self.TclErrorException(text)
  1645. def exec_command(self, text):
  1646. """
  1647. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  1648. Also handles execution in separated threads
  1649. :param text:
  1650. :return: output if there was any
  1651. """
  1652. self.report_usage('exec_command')
  1653. result = self.exec_command_test(text, False)
  1654. #MS: added this method call so the geometry is updated once the TCL
  1655. #command is executed
  1656. self.plot_all()
  1657. return result
  1658. def exec_command_test(self, text, reraise=True):
  1659. """
  1660. Same as exec_command(...) with additional control over exceptions.
  1661. Handles input from the shell. See FlatCAMApp.setup_shell for shell commands.
  1662. :param text: Input command
  1663. :param reraise: Re-raise TclError exceptions in Python (mostly for unitttests).
  1664. :return: Output from the command
  1665. """
  1666. text = str(text)
  1667. try:
  1668. self.shell.open_proccessing() # Disables input box.
  1669. result = self.tcl.eval(str(text))
  1670. if result != 'None':
  1671. self.shell.append_output(result + '\n')
  1672. except tk.TclError as e:
  1673. # This will display more precise answer if something in TCL shell fails
  1674. result = self.tcl.eval("set errorInfo")
  1675. self.log.error("Exec command Exception: %s" % (result + '\n'))
  1676. self.shell.append_error('ERROR: ' + result + '\n')
  1677. # Show error in console and just return or in test raise exception
  1678. if reraise:
  1679. raise e
  1680. finally:
  1681. self.shell.close_proccessing()
  1682. pass
  1683. return result
  1684. # """
  1685. # Code below is unsused. Saved for later.
  1686. # """
  1687. # parts = re.findall(r'([\w\\:\.]+|".*?")+', text)
  1688. # parts = [p.replace('\n', '').replace('"', '') for p in parts]
  1689. # self.log.debug(parts)
  1690. # try:
  1691. # if parts[0] not in commands:
  1692. # self.shell.append_error("Unknown command\n")
  1693. # return
  1694. #
  1695. # #import inspect
  1696. # #inspect.getargspec(someMethod)
  1697. # if (type(commands[parts[0]]["params"]) is not list and len(parts)-1 != commands[parts[0]]["params"]) or \
  1698. # (type(commands[parts[0]]["params"]) is list and len(parts)-1 not in commands[parts[0]]["params"]):
  1699. # self.shell.append_error(
  1700. # "Command %s takes %d arguments. %d given.\n" %
  1701. # (parts[0], commands[parts[0]]["params"], len(parts)-1)
  1702. # )
  1703. # return
  1704. #
  1705. # cmdfcn = commands[parts[0]]["fcn"]
  1706. # cmdconv = commands[parts[0]]["converters"]
  1707. # if len(parts) - 1 > 0:
  1708. # retval = cmdfcn(*[cmdconv[i](parts[i + 1]) for i in range(len(parts)-1)])
  1709. # else:
  1710. # retval = cmdfcn()
  1711. # retfcn = commands[parts[0]]["retfcn"]
  1712. # if retval and retfcn(retval):
  1713. # self.shell.append_output(retfcn(retval) + "\n")
  1714. #
  1715. # except Exception as e:
  1716. # #self.shell.append_error(''.join(traceback.format_exc()))
  1717. # #self.shell.append_error("?\n")
  1718. # self.shell.append_error(str(e) + "\n")
  1719. def info(self, msg):
  1720. """
  1721. Informs the user. Normally on the status bar, optionally
  1722. also on the shell.
  1723. :param msg: Text to write.
  1724. :return: None
  1725. """
  1726. # Type of message in brackets at the begining of the message.
  1727. match = re.search("\[([^\]]+)\](.*)", msg)
  1728. if match:
  1729. level = match.group(1)
  1730. msg_ = match.group(2)
  1731. self.ui.fcinfo.set_status(str(msg_), level=level)
  1732. if level.lower() == "error":
  1733. self.shell_message(msg, error=True, show=True)
  1734. elif level.lower() == "warning":
  1735. self.shell_message(msg, warning=True, show=True)
  1736. elif level.lower() == "error_notcl":
  1737. self.shell_message(msg, error=True, show=False)
  1738. elif level.lower() == "warning_notcl":
  1739. self.shell_message(msg, warning=True, show=False)
  1740. elif level.lower() == "success":
  1741. self.shell_message(msg, success=True, show=False)
  1742. elif level.lower() == "selected":
  1743. self.shell_message(msg, selected=True, show=False)
  1744. else:
  1745. self.shell_message(msg, show=False)
  1746. else:
  1747. self.ui.fcinfo.set_status(str(msg), level="info")
  1748. # make sure that if the message is to clear the infobar with a space
  1749. # is not printed over and over on the shell
  1750. if msg != '':
  1751. self.shell_message(msg)
  1752. def restore_toolbar_view(self):
  1753. tb = self.defaults["global_toolbar_view"]
  1754. if tb & 1:
  1755. self.ui.toolbarfile.setVisible(True)
  1756. else:
  1757. self.ui.toolbarfile.setVisible(False)
  1758. if tb & 2:
  1759. self.ui.toolbargeo.setVisible(True)
  1760. else:
  1761. self.ui.toolbargeo.setVisible(False)
  1762. if tb & 4:
  1763. self.ui.toolbarview.setVisible(True)
  1764. else:
  1765. self.ui.toolbarview.setVisible(False)
  1766. if tb & 8:
  1767. self.ui.toolbartools.setVisible(True)
  1768. else:
  1769. self.ui.toolbartools.setVisible(False)
  1770. if tb & 16:
  1771. self.ui.exc_edit_toolbar.setVisible(True)
  1772. else:
  1773. self.ui.exc_edit_toolbar.setVisible(False)
  1774. if tb & 32:
  1775. self.ui.geo_edit_toolbar.setVisible(True)
  1776. else:
  1777. self.ui.geo_edit_toolbar.setVisible(False)
  1778. if tb & 64:
  1779. self.ui.snap_toolbar.setVisible(True)
  1780. else:
  1781. self.ui.snap_toolbar.setVisible(False)
  1782. if tb & 128:
  1783. self.ui.toolbarshell.setVisible(True)
  1784. else:
  1785. self.ui.toolbarshell.setVisible(False)
  1786. def load_defaults(self, filename):
  1787. """
  1788. Loads the aplication's default settings from current_defaults.FlatConfig into
  1789. ``self.defaults``.
  1790. :return: None
  1791. """
  1792. try:
  1793. f = open(self.data_path + "/" + filename + ".FlatConfig")
  1794. options = f.read()
  1795. f.close()
  1796. except IOError:
  1797. self.log.error("Could not load defaults file.")
  1798. self.inform.emit("[ERROR] Could not load defaults file.")
  1799. # in case the defaults file can't be loaded, show all toolbars
  1800. self.defaults["global_toolbar_view"] = 255
  1801. return
  1802. try:
  1803. defaults = json.loads(options)
  1804. except:
  1805. # in case the defaults file can't be loaded, show all toolbars
  1806. self.defaults["global_toolbar_view"] = 255
  1807. e = sys.exc_info()[0]
  1808. App.log.error(str(e))
  1809. self.inform.emit("[ERROR] Failed to parse defaults file.")
  1810. return
  1811. self.defaults.update(defaults)
  1812. log.debug("FlatCAM defaults loaded from: %s" % filename)
  1813. # restore the toolbar view
  1814. self.restore_toolbar_view()
  1815. def on_import_preferences(self):
  1816. """
  1817. Loads the aplication's factory default settings from factory_defaults.FlatConfig into
  1818. ``self.defaults``.
  1819. :return: None
  1820. """
  1821. self.report_usage("on_import_preferences")
  1822. App.log.debug("on_import_preferences()")
  1823. filter = "Config File (*.FlatConfig);;All Files (*.*)"
  1824. try:
  1825. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Import FlatCAM Preferences",
  1826. directory=self.data_path, filter=filter)
  1827. except TypeError:
  1828. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Import FlatCAM Preferences", filter=filter)
  1829. filename = str(filename)
  1830. if filename == "":
  1831. self.inform.emit("[WARNING_NOTCL]FlatCAM preferences import cancelled.")
  1832. else:
  1833. try:
  1834. f = open(filename)
  1835. options = f.read()
  1836. f.close()
  1837. except IOError:
  1838. self.log.error("Could not load defaults file.")
  1839. self.inform.emit("[ERROR_NOTCL] Could not load defaults file.")
  1840. return
  1841. try:
  1842. defaults_from_file = json.loads(options)
  1843. except:
  1844. e = sys.exc_info()[0]
  1845. App.log.error(str(e))
  1846. self.inform.emit("[ERROR_NOTCL] Failed to parse defaults file.")
  1847. return
  1848. self.defaults.update(defaults_from_file)
  1849. self.inform.emit("[success]Imported Defaults from %s" %filename)
  1850. def on_export_preferences(self):
  1851. self.report_usage("on_export_preferences")
  1852. App.log.debug("on_export_preferences()")
  1853. filter = "Config File (*.FlatConfig);;All Files (*.*)"
  1854. try:
  1855. filename, _ = QtWidgets.QFileDialog.getSaveFileName(
  1856. caption="Export FlatCAM Preferences",
  1857. directory=self.data_path + '/preferences_' + self.date.replace('-', ''), filter=filter
  1858. )
  1859. except TypeError:
  1860. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export FlatCAM Preferences", filter=filter)
  1861. filename = str(filename)
  1862. defaults_from_file = {}
  1863. if filename == "":
  1864. self.inform.emit("[WARNING_NOTCL]FlatCAM preferences export cancelled.")
  1865. return
  1866. else:
  1867. try:
  1868. f = open(filename, 'w')
  1869. defaults_file_content = f.read()
  1870. f.close()
  1871. except IOError:
  1872. App.log.debug('Creating a new preferences file ...')
  1873. f = open(filename, 'w')
  1874. json.dump({}, f)
  1875. f.close()
  1876. except:
  1877. e = sys.exc_info()[0]
  1878. App.log.error("Could not load defaults file.")
  1879. App.log.error(str(e))
  1880. self.inform.emit("[ERROR_NOTCL]Could not load defaults file.")
  1881. return
  1882. try:
  1883. defaults_from_file = json.loads(defaults_file_content)
  1884. except:
  1885. App.log.warning("Trying to read an empty Preferences file. Continue.")
  1886. # Update options
  1887. self.defaults_read_form()
  1888. defaults_from_file.update(self.defaults)
  1889. self.propagate_defaults(silent=True)
  1890. # Save update options
  1891. try:
  1892. f = open(filename, "w")
  1893. json.dump(defaults_from_file, f)
  1894. f.close()
  1895. except:
  1896. self.inform.emit("[ERROR_NOTCL] Failed to write defaults to file.")
  1897. return
  1898. self.file_saved.emit("preferences", filename)
  1899. self.inform.emit("[success]Exported Defaults to %s" % filename)
  1900. def on_preferences_open_folder(self):
  1901. self.report_usage("on_preferences_open_folder()")
  1902. if sys.platform == 'win32':
  1903. subprocess.Popen('explorer %s' % self.data_path)
  1904. elif sys.platform == 'darwin':
  1905. os.system('open "%s"' % self.data_path)
  1906. else:
  1907. subprocess.Popen(['xdg-open', self.data_path])
  1908. self.inform.emit("[success]FlatCAM Preferences Folder opened.")
  1909. def save_geometry(self, x, y, width, height, notebook_width):
  1910. self.defaults["global_def_win_x"] = x
  1911. self.defaults["global_def_win_y"] = y
  1912. self.defaults["global_def_win_w"] = width
  1913. self.defaults["global_def_win_h"] = height
  1914. self.defaults["def_notebook_width"] = notebook_width
  1915. self.save_defaults()
  1916. def message_dialog(self, title, message, kind="info"):
  1917. icon = {"info": QtWidgets.QMessageBox.Information,
  1918. "warning": QtWidgets.QMessageBox.Warning,
  1919. "error": QtWidgets.QMessageBox.Critical}[str(kind)]
  1920. dlg = QtWidgets.QMessageBox(icon, title, message, parent=self.ui)
  1921. dlg.setText(message)
  1922. dlg.exec_()
  1923. def register_recent(self, kind, filename):
  1924. self.log.debug("register_recent()")
  1925. self.log.debug(" %s" % kind)
  1926. self.log.debug(" %s" % filename)
  1927. record = {'kind': str(kind), 'filename': str(filename)}
  1928. if record in self.recent:
  1929. return
  1930. self.recent.insert(0, record)
  1931. if len(self.recent) > self.defaults['global_recent_limit']: # Limit reached
  1932. self.recent.pop()
  1933. try:
  1934. f = open(self.data_path + '/recent.json', 'w')
  1935. except IOError:
  1936. App.log.error("Failed to open recent items file for writing.")
  1937. self.inform.emit('[ERROR_NOTCL]Failed to open recent files file for writing.')
  1938. return
  1939. #try:
  1940. json.dump(self.recent, f, default=to_dict, indent=2, sort_keys=True)
  1941. # except:
  1942. # App.log.error("Failed to write to recent items file.")
  1943. # self.inform.emit('ERROR: Failed to write to recent items file.')
  1944. # f.close()
  1945. f.close()
  1946. # Re-buid the recent items menu
  1947. self.setup_recent_items()
  1948. def new_object(self, kind, name, initialize, active=True, fit=True, plot=True, autoselected=True):
  1949. """
  1950. Creates a new specalized FlatCAMObj and attaches it to the application,
  1951. this is, updates the GUI accordingly, any other records and plots it.
  1952. This method is thread-safe.
  1953. Notes:
  1954. * If the name is in use, the self.collection will modify it
  1955. when appending it to the collection. There is no need to handle
  1956. name conflicts here.
  1957. :param kind: The kind of object to create. One of 'gerber',
  1958. 'excellon', 'cncjob' and 'geometry'.
  1959. :type kind: str
  1960. :param name: Name for the object.
  1961. :type name: str
  1962. :param initialize: Function to run after creation of the object
  1963. but before it is attached to the application. The function is
  1964. called with 2 parameters: the new object and the App instance.
  1965. :type initialize: function
  1966. :return: None
  1967. :rtype: None
  1968. """
  1969. App.log.debug("new_object()")
  1970. obj_plot = plot
  1971. obj_autoselected = autoselected
  1972. t0 = time.time() # Debug
  1973. ## Create object
  1974. classdict = {
  1975. "gerber": FlatCAMGerber,
  1976. "excellon": FlatCAMExcellon,
  1977. "cncjob": FlatCAMCNCjob,
  1978. "geometry": FlatCAMGeometry
  1979. }
  1980. App.log.debug("Calling object constructor...")
  1981. obj = classdict[kind](name)
  1982. obj.units = self.options["units"] # TODO: The constructor should look at defaults.
  1983. # Set options from "Project options" form
  1984. self.options_read_form()
  1985. # IMPORTANT
  1986. # The key names in defaults and options dictionary's are not random:
  1987. # they have to have in name first the type of the object (geometry, excellon, cncjob and gerber) or how it's
  1988. # called here, the 'kind' followed by an underline. The function called above (self.options_read_form()) copy
  1989. # the options from project options form into the self.options. After that, below, depending on the type of
  1990. # object that is created, it will strip the name of the object and the underline (if the original key was
  1991. # let's say "excellon_toolchange", it will strip the excellon_) and to the obj.options the key will become
  1992. # "toolchange"
  1993. for option in self.options:
  1994. if option.find(kind + "_") == 0:
  1995. oname = option[len(kind) + 1:]
  1996. obj.options[oname] = self.options[option]
  1997. # if kind == 'geometry':
  1998. # obj.tools = {}
  1999. # elif kind == 'cncjob':
  2000. # obj.cnc_tools = {}
  2001. # Initialize as per user request
  2002. # User must take care to implement initialize
  2003. # in a thread-safe way as is is likely that we
  2004. # have been invoked in a separate thread.
  2005. t1 = time.time()
  2006. self.log.debug("%f seconds before initialize()." % (t1 - t0))
  2007. try:
  2008. return_value = initialize(obj, self)
  2009. except Exception as e:
  2010. msg = "[ERROR_NOTCL] An internal error has ocurred. See shell.\n"
  2011. msg += "Object (%s) failed because: %s \n\n" % (kind, str(e))
  2012. msg += traceback.format_exc()
  2013. self.inform.emit(msg)
  2014. # if str(e) == "Empty Geometry":
  2015. # self.inform.emit("[ERROR_NOTCL] )
  2016. # else:
  2017. # self.inform.emit("[ERROR] Object (%s) failed because: %s" % (kind, str(e)))
  2018. return "fail"
  2019. t2 = time.time()
  2020. self.log.debug("%f seconds executing initialize()." % (t2 - t1))
  2021. if return_value == 'fail':
  2022. log.debug("Object (%s) parsing and/or geometry creation failed." % kind)
  2023. return "fail"
  2024. # Check units and convert if necessary
  2025. # This condition CAN be true because initialize() can change obj.units
  2026. if self.options["units"].upper() != obj.units.upper():
  2027. self.inform.emit("Converting units to " + self.options["units"] + ".")
  2028. obj.convert_units(self.options["units"])
  2029. t3 = time.time()
  2030. self.log.debug("%f seconds converting units." % (t3 - t2))
  2031. # Create the bounding box for the object and then add the results to the obj.options
  2032. try:
  2033. xmin, ymin, xmax, ymax = obj.bounds()
  2034. obj.options['xmin'] = xmin
  2035. obj.options['ymin'] = ymin
  2036. obj.options['xmax'] = xmax
  2037. obj.options['ymax'] = ymax
  2038. except:
  2039. log.warning("The object has no bounds properties.")
  2040. # don't plot objects with no bounds, there is nothing to plot
  2041. self.plot = False
  2042. pass
  2043. FlatCAMApp.App.log.debug("Moving new object back to main thread.")
  2044. # Move the object to the main thread and let the app know that it is available.
  2045. obj.moveToThread(QtWidgets.QApplication.instance().thread())
  2046. self.object_created.emit(obj, obj_plot, obj_autoselected)
  2047. return obj
  2048. def new_excellon_object(self):
  2049. self.report_usage("new_excellon_object()")
  2050. self.new_object('excellon', 'new_e', lambda x, y: None, plot=False)
  2051. def new_geometry_object(self):
  2052. self.report_usage("new_geometry_object()")
  2053. def initialize(obj, self):
  2054. obj.multitool = False
  2055. self.new_object('geometry', 'new_g', initialize, plot=False)
  2056. def on_object_created(self, obj, plot, autoselect):
  2057. """
  2058. Event callback for object creation.
  2059. :param obj: The newly created FlatCAM object.
  2060. :return: None
  2061. """
  2062. t0 = time.time() # DEBUG
  2063. self.log.debug("on_object_created()")
  2064. # The Collection might change the name if there is a collision
  2065. self.collection.append(obj)
  2066. # after adding the object to the collection always update the list of objects that are in the collection
  2067. self.all_objects_list = self.collection.get_list()
  2068. # self.inform.emit('[selected] %s created & selected: %s' %
  2069. # (str(obj.kind).capitalize(), str(obj.options['name'])))
  2070. if obj.kind == 'gerber':
  2071. self.inform.emit('[selected]%s created/selected: <span style="color:%s;">%s</span>' %
  2072. (obj.kind.capitalize(), 'green', str(obj.options['name'])))
  2073. elif obj.kind == 'excellon':
  2074. self.inform.emit('[selected]%s created/selected: <span style="color:%s;">%s</span>' %
  2075. (obj.kind.capitalize(), 'brown', str(obj.options['name'])))
  2076. elif obj.kind == 'cncjob':
  2077. self.inform.emit('[selected]%s created/selected: <span style="color:%s;">%s</span>' %
  2078. (obj.kind.capitalize(), 'blue', str(obj.options['name'])))
  2079. elif obj.kind == 'geometry':
  2080. self.inform.emit('[selected]%s created/selected: <span style="color:%s;">%s</span>' %
  2081. (obj.kind.capitalize(), 'red', str(obj.options['name'])))
  2082. # update the SHELL auto-completer model with the name of the new object
  2083. self.myKeywords.append(obj.options['name'])
  2084. self.shell._edit.set_model_data(self.myKeywords)
  2085. if autoselect:
  2086. # select the just opened object but deselect the previous ones
  2087. self.collection.set_all_inactive()
  2088. self.collection.set_active(obj.options["name"])
  2089. # here it is done the object plotting
  2090. def worker_task(obj):
  2091. with self.proc_container.new("Plotting"):
  2092. if isinstance(obj, FlatCAMCNCjob):
  2093. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  2094. else:
  2095. obj.plot()
  2096. t1 = time.time() # DEBUG
  2097. self.log.debug("%f seconds adding object and plotting." % (t1 - t0))
  2098. self.object_plotted.emit(obj)
  2099. # Send to worker
  2100. # self.worker.add_task(worker_task, [self])
  2101. if plot is True:
  2102. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  2103. def on_object_changed(self, obj):
  2104. # update the bounding box data from obj.options
  2105. xmin, ymin, xmax, ymax = obj.bounds()
  2106. obj.options['xmin'] = xmin
  2107. obj.options['ymin'] = ymin
  2108. obj.options['xmax'] = xmax
  2109. obj.options['ymax'] = ymax
  2110. log.debug("Object changed, updating the bounding box data on self.options")
  2111. # delete the old selection shape
  2112. self.delete_selection_shape()
  2113. self.should_we_save = True
  2114. def on_object_plotted(self, obj):
  2115. self.on_zoom_fit(None)
  2116. def options_read_form(self):
  2117. for option in self.options_form_fields:
  2118. self.options[option] = self.options_form_fields[option].get_value()
  2119. def options_write_form(self):
  2120. for option in self.options:
  2121. self.options_write_form_field(option)
  2122. def options_write_form_field(self, field):
  2123. try:
  2124. self.options_form_fields[field].set_value(self.options[field])
  2125. except KeyError:
  2126. # Changed from error to debug. This allows to have data stored
  2127. # which is not user-editable.
  2128. # self.log.debug("options_write_form_field(): No field for: %s" % field)
  2129. pass
  2130. def on_about(self):
  2131. """
  2132. Displays the "about" dialog.
  2133. :return: None
  2134. """
  2135. self.report_usage("on_about")
  2136. version = self.version
  2137. version_date = self.version_date
  2138. beta = self.beta
  2139. class AboutDialog(QtWidgets.QDialog):
  2140. def __init__(self, parent=None):
  2141. QtWidgets.QDialog.__init__(self, parent)
  2142. # Icon and title
  2143. self.setWindowIcon(parent.app_icon)
  2144. self.setWindowTitle("FlatCAM")
  2145. layout1 = QtWidgets.QVBoxLayout()
  2146. self.setLayout(layout1)
  2147. layout2 = QtWidgets.QHBoxLayout()
  2148. layout1.addLayout(layout2)
  2149. logo = QtWidgets.QLabel()
  2150. logo.setPixmap(QtGui.QPixmap('share/flatcam_icon256.png'))
  2151. layout2.addWidget(logo, stretch=0)
  2152. title = QtWidgets.QLabel(
  2153. "<font size=8><B>FlatCAM</B></font><BR>"
  2154. "Version %s %s (%s) - %s <BR>"
  2155. "<BR>"
  2156. "2D Computer-Aided Printed Circuit Board<BR>"
  2157. "Manufacturing.<BR>"
  2158. "<BR>"
  2159. "(c) 2014-2019 <B>Juan Pablo Caram</B><BR>"
  2160. "<BR>"
  2161. "<B> Main Contributors:</B><BR>"
  2162. "Denis Hayrullin<BR>"
  2163. "Kamil Sopko<BR>"
  2164. "Marius Stanciu<BR>"
  2165. "Matthieu Berthomé<BR>"
  2166. "and many others found "
  2167. "<a href = \"https://bitbucket.org/jpcgt/flatcam/pull-requests/?state=MERGED\">here.</a><BR>"
  2168. "<BR>"
  2169. "Development is done "
  2170. "<a href = \"https://bitbucket.org/jpcgt/flatcam/src/Beta/\">here.</a><BR>"
  2171. "DOWNLOAD area "
  2172. "<a href = \"https://bitbucket.org/jpcgt/flatcam/downloads/\">here.</a><BR>"
  2173. "" % (version, ('BETA' if beta else ''), version_date, platform.architecture()[0])
  2174. )
  2175. title.setOpenExternalLinks(True)
  2176. layout2.addWidget(title, stretch=1)
  2177. layout3 = QtWidgets.QHBoxLayout()
  2178. layout1.addLayout(layout3)
  2179. layout3.addStretch()
  2180. okbtn = QtWidgets.QPushButton("Close")
  2181. layout3.addWidget(okbtn)
  2182. okbtn.clicked.connect(self.accept)
  2183. AboutDialog(self.ui).exec_()
  2184. def on_file_savedefaults(self):
  2185. """
  2186. Callback for menu item File->Save Defaults. Saves application default options
  2187. ``self.defaults`` to current_defaults.FlatConfig.
  2188. :return: None
  2189. """
  2190. self.save_defaults()
  2191. def on_app_exit(self):
  2192. self.report_usage("on_app_exit()")
  2193. if self.collection.get_list():
  2194. msgbox = QtWidgets.QMessageBox()
  2195. # msgbox.setText("<B>Save changes ...</B>")
  2196. msgbox.setText("There are files/objects opened in FlatCAM. "
  2197. "\n"
  2198. "Do you want to Save the project?")
  2199. msgbox.setWindowTitle("Save changes")
  2200. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2201. msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  2202. QtWidgets.QMessageBox.Cancel)
  2203. msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  2204. response = msgbox.exec_()
  2205. if response == QtWidgets.QMessageBox.Yes:
  2206. self.on_file_saveprojectas(thread=False)
  2207. elif response == QtWidgets.QMessageBox.Cancel:
  2208. return
  2209. self.save_defaults()
  2210. else:
  2211. self.save_defaults()
  2212. log.debug("Application defaults saved ... Exit event.")
  2213. QtWidgets.qApp.quit()
  2214. def save_defaults(self, silent=False):
  2215. """
  2216. Saves application default options
  2217. ``self.defaults`` to current_defaults.FlatConfig.
  2218. :return: None
  2219. """
  2220. self.report_usage("save_defaults")
  2221. # Read options from file
  2222. try:
  2223. f = open(self.data_path + "/current_defaults.FlatConfig")
  2224. defaults_file_content = f.read()
  2225. f.close()
  2226. except:
  2227. e = sys.exc_info()[0]
  2228. App.log.error("Could not load defaults file.")
  2229. App.log.error(str(e))
  2230. self.inform.emit("[ERROR_NOTCL] Could not load defaults file.")
  2231. return
  2232. try:
  2233. defaults = json.loads(defaults_file_content)
  2234. except:
  2235. e = sys.exc_info()[0]
  2236. App.log.error("Failed to parse defaults file.")
  2237. App.log.error(str(e))
  2238. self.inform.emit("[ERROR_NOTCL] Failed to parse defaults file.")
  2239. return
  2240. # Update options
  2241. self.defaults_read_form()
  2242. defaults.update(self.defaults)
  2243. self.propagate_defaults(silent=True)
  2244. # Save update options
  2245. try:
  2246. f = open(self.data_path + "/current_defaults.FlatConfig", "w")
  2247. json.dump(defaults, f, default=to_dict, indent=2, sort_keys=True)
  2248. f.close()
  2249. except:
  2250. self.inform.emit("[ERROR_NOTCL] Failed to write defaults to file.")
  2251. return
  2252. # Save the toolbar view
  2253. tb_status = 0
  2254. if self.ui.toolbarfile.isVisible():
  2255. tb_status += 1
  2256. if self.ui.toolbargeo.isVisible():
  2257. tb_status += 2
  2258. if self.ui.toolbarview.isVisible():
  2259. tb_status += 4
  2260. if self.ui.toolbartools.isVisible():
  2261. tb_status += 8
  2262. if self.ui.exc_edit_toolbar.isVisible():
  2263. tb_status += 16
  2264. if self.ui.geo_edit_toolbar.isVisible():
  2265. tb_status += 32
  2266. if self.ui.snap_toolbar.isVisible():
  2267. tb_status += 64
  2268. if self.ui.toolbarshell.isVisible():
  2269. tb_status += 128
  2270. self.defaults["global_toolbar_view"] = tb_status
  2271. if not silent:
  2272. self.inform.emit("[success]Defaults saved.")
  2273. def save_factory_defaults(self, silent=False):
  2274. """
  2275. Saves application factory default options
  2276. ``self.defaults`` to factory_defaults.FlatConfig.
  2277. It's a one time job done just after the first install.
  2278. :return: None
  2279. """
  2280. self.report_usage("save_factory_defaults")
  2281. # Read options from file
  2282. try:
  2283. f_f_def = open(self.data_path + "/factory_defaults.FlatConfig")
  2284. factory_defaults_file_content = f_f_def.read()
  2285. f_f_def.close()
  2286. except:
  2287. e = sys.exc_info()[0]
  2288. App.log.error("Could not load factory defaults file.")
  2289. App.log.error(str(e))
  2290. self.inform.emit("[ERROR_NOTCL] Could not load factory defaults file.")
  2291. return
  2292. try:
  2293. factory_defaults = json.loads(factory_defaults_file_content)
  2294. except:
  2295. e = sys.exc_info()[0]
  2296. App.log.error("Failed to parse factory defaults file.")
  2297. App.log.error(str(e))
  2298. self.inform.emit("[ERROR_NOTCL] Failed to parse factory defaults file.")
  2299. return
  2300. # Update options
  2301. self.defaults_read_form()
  2302. factory_defaults.update(self.defaults)
  2303. self.propagate_defaults(silent=True)
  2304. # Save update options
  2305. try:
  2306. f_f_def_s = open(self.data_path + "/factory_defaults.FlatConfig", "w")
  2307. json.dump(factory_defaults, f_f_def_s, default=to_dict, indent=2, sort_keys=True)
  2308. f_f_def_s.close()
  2309. except:
  2310. self.inform.emit("[ERROR_NOTCL] Failed to write factory defaults to file.")
  2311. return
  2312. if silent is False:
  2313. self.inform.emit("Factory defaults saved.")
  2314. def final_save(self):
  2315. if self.should_we_save and self.collection.get_list():
  2316. msgbox = QtWidgets.QMessageBox()
  2317. # msgbox.setText("<B>Save changes ...</B>")
  2318. msgbox.setText("There are files/objects modified in FlatCAM. "
  2319. "\n"
  2320. "Do you want to Save the project?")
  2321. msgbox.setWindowTitle("Save changes")
  2322. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  2323. msgbox.setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No |
  2324. QtWidgets.QMessageBox.Cancel)
  2325. msgbox.setDefaultButton(QtWidgets.QMessageBox.Yes)
  2326. response = msgbox.exec_()
  2327. if response == QtWidgets.QMessageBox.Yes:
  2328. self.on_file_saveprojectas(thread=False)
  2329. elif response == QtWidgets.QMessageBox.Cancel:
  2330. self.should_we_quit = False
  2331. return
  2332. self.save_defaults()
  2333. log.debug("Application defaults saved ... Exit event.")
  2334. def on_toggle_shell(self):
  2335. """
  2336. toggle shell if is visible close it if closed open it
  2337. :return:
  2338. """
  2339. self.report_usage("on_toggle_shell()")
  2340. if self.ui.shell_dock.isVisible():
  2341. self.ui.shell_dock.hide()
  2342. else:
  2343. self.ui.shell_dock.show()
  2344. def on_edit_join(self, name=None):
  2345. """
  2346. Callback for Edit->Join. Joins the selected geometry objects into
  2347. a new one.
  2348. :return: None
  2349. """
  2350. self.report_usage("on_edit_join()")
  2351. obj_name_single = str(name) if name else "Combo_SingleGeo"
  2352. obj_name_multi = str(name) if name else "Combo_MultiGeo"
  2353. tooldias = []
  2354. geo_type_list = []
  2355. objs = self.collection.get_selected()
  2356. for obj in objs:
  2357. geo_type_list.append(obj.multigeo)
  2358. # if len(set(geo_type_list)) == 1 means that all list elements are the same
  2359. if len(set(geo_type_list)) != 1:
  2360. self.inform.emit("[ERROR] Failed join. The Geometry objects are of different types.\n"
  2361. "At least one is MultiGeo type and the other is SingleGeo type. A possibility is to "
  2362. "convert from one to another and retry joining \n"
  2363. "but in the case of converting from MultiGeo to SingleGeo, informations may be lost and "
  2364. "the result may not be what was expected. \n"
  2365. "Check the generated GCODE.")
  2366. return
  2367. # if at least one True object is in the list then due of the previous check, all list elements are True objects
  2368. if True in geo_type_list:
  2369. def initialize(obj, app):
  2370. FlatCAMGeometry.merge(objs, obj, multigeo=True)
  2371. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2372. for v in obj.tools.values():
  2373. v['data']['name'] = obj_name_multi
  2374. self.new_object("geometry", obj_name_multi, initialize)
  2375. else:
  2376. def initialize(obj, app):
  2377. FlatCAMGeometry.merge(objs, obj, multigeo=False)
  2378. # rename all the ['name] key in obj.tools[tooluid]['data'] to the obj_name_multi
  2379. for v in obj.tools.values():
  2380. v['data']['name'] = obj_name_single
  2381. self.new_object("geometry", obj_name_single, initialize)
  2382. self.should_we_save = True
  2383. def on_edit_join_exc(self):
  2384. """
  2385. Callback for Edit->Join Excellon. Joins the selected excellon objects into
  2386. a new one.
  2387. :return: None
  2388. """
  2389. self.report_usage("on_edit_join_exc()")
  2390. objs = self.collection.get_selected()
  2391. for obj in objs:
  2392. if not isinstance(obj, FlatCAMExcellon):
  2393. self.inform.emit("[ERROR_NOTCL]Failed. Excellon joining works only on Excellon objects.")
  2394. return
  2395. def initialize(obj, app):
  2396. FlatCAMExcellon.merge(objs, obj)
  2397. self.new_object("excellon", 'Combo_Excellon', initialize)
  2398. self.should_we_save = True
  2399. def on_edit_join_grb(self):
  2400. """
  2401. Callback for Edit->Join Gerber. Joins the selected Gerber objects into
  2402. a new one.
  2403. :return: None
  2404. """
  2405. self.report_usage("on_edit_join_grb()")
  2406. objs = self.collection.get_selected()
  2407. for obj in objs:
  2408. if not isinstance(obj, FlatCAMGerber):
  2409. self.inform.emit("[ERROR_NOTCL]Failed. Gerber joining works only on Gerber objects.")
  2410. return
  2411. def initialize(obj, app):
  2412. FlatCAMGerber.merge(objs, obj)
  2413. self.new_object("gerber", 'Combo_Gerber', initialize)
  2414. self.should_we_save = True
  2415. def on_convert_singlegeo_to_multigeo(self):
  2416. self.report_usage("on_convert_singlegeo_to_multigeo()")
  2417. obj = self.collection.get_active()
  2418. if obj is None:
  2419. self.inform.emit("[ERROR_NOTCL]Failed. Select a Geometry Object and try again.")
  2420. return
  2421. if not isinstance(obj, FlatCAMGeometry):
  2422. self.inform.emit("[ERROR_NOTCL]Expected a FlatCAMGeometry, got %s" % type(obj))
  2423. return
  2424. obj.multigeo = True
  2425. for tooluid, dict_value in obj.tools.items():
  2426. dict_value['solid_geometry'] = deepcopy(obj.solid_geometry)
  2427. if not isinstance(obj.solid_geometry, list):
  2428. obj.solid_geometry = [obj.solid_geometry]
  2429. obj.solid_geometry[:] = []
  2430. obj.plot()
  2431. self.should_we_save = True
  2432. self.inform.emit("[success] A Geometry object was converted to MultiGeo type.")
  2433. def on_convert_multigeo_to_singlegeo(self):
  2434. self.report_usage("on_convert_multigeo_to_singlegeo()")
  2435. obj = self.collection.get_active()
  2436. if obj is None:
  2437. self.inform.emit("[ERROR_NOTCL]Failed. Select a Geometry Object and try again.")
  2438. return
  2439. if not isinstance(obj, FlatCAMGeometry):
  2440. self.inform.emit("[ERROR_NOTCL]Expected a FlatCAMGeometry, got %s" % type(obj))
  2441. return
  2442. obj.multigeo = False
  2443. total_solid_geometry = []
  2444. for tooluid, dict_value in obj.tools.items():
  2445. total_solid_geometry += deepcopy(dict_value['solid_geometry'])
  2446. # clear the original geometry
  2447. dict_value['solid_geometry'][:] = []
  2448. obj.solid_geometry = deepcopy(total_solid_geometry)
  2449. obj.plot()
  2450. self.should_we_save = True
  2451. self.inform.emit("[success] A Geometry object was converted to SingleGeo type.")
  2452. def on_options_dict_change(self, field):
  2453. self.options_write_form_field(field)
  2454. if field == "units":
  2455. self.set_screen_units(self.options['units'])
  2456. def on_defaults_dict_change(self, field):
  2457. self.defaults_write_form_field(field)
  2458. def set_screen_units(self, units):
  2459. self.ui.units_label.setText("[" + self.options["units"].lower() + "]")
  2460. def on_toggle_units(self):
  2461. """
  2462. Callback for the Units radio-button change in the Options tab.
  2463. Changes the application's default units or the current project's units.
  2464. If changing the project's units, the change propagates to all of
  2465. the objects in the project.
  2466. :return: None
  2467. """
  2468. self.report_usage("on_toggle_units")
  2469. if self.toggle_units_ignore:
  2470. return
  2471. # If option is the same, then ignore
  2472. if self.ui.general_options_form.general_app_group.units_radio.get_value().upper() == self.options["units"].upper():
  2473. self.log.debug("on_toggle_units(): Same as options, so ignoring.")
  2474. return
  2475. # Options to scale
  2476. dimensions = ['gerber_isotooldia', 'tools_cutoutmargin', 'tools_cutoutgapsize',
  2477. 'gerber_noncoppermargin', 'gerber_bboxmargin','gerber_isooverlap','tools_nccoverlap',
  2478. 'tools_nccmargin','tools_cutouttooldia','tools_cutoutgapsize',
  2479. 'gerber_noncoppermargin','gerber_bboxmargin',
  2480. 'excellon_drillz', "excellon_toolchangexy",
  2481. 'excellon_travelz', 'excellon_feedrate', 'excellon_feedrate_rapid', 'excellon_toolchangez',
  2482. 'excellon_tooldia', 'excellon_endz', 'cncjob_tooldia',
  2483. 'geometry_cutz', 'geometry_travelz', 'geometry_feedrate', 'geometry_feedrate_rapid',
  2484. 'geometry_cnctooldia', 'tools_painttooldia', 'tools_paintoverlap', 'geometry_toolchangexy',
  2485. 'geometry_toolchangez',
  2486. 'tools_paintmargin', 'geometry_endz', 'geometry_depthperpass', 'global_gridx', 'global_gridy']
  2487. def scale_options(sfactor):
  2488. for dim in dimensions:
  2489. if dim == 'excellon_toolchangexy':
  2490. coords_xy = [float(eval(a)) for a in self.defaults["excellon_toolchangexy"].split(",")]
  2491. coords_xy[0] *= sfactor
  2492. coords_xy[1] *= sfactor
  2493. self.options['excellon_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  2494. elif dim == 'geometry_toolchangexy':
  2495. coords_xy = [float(eval(a)) for a in self.defaults["geometry_toolchangexy"].split(",")]
  2496. coords_xy[0] *= sfactor
  2497. coords_xy[1] *= sfactor
  2498. self.options['geometry_toolchangexy'] = "%f, %f" % (coords_xy[0], coords_xy[1])
  2499. else:
  2500. self.options[dim] *= sfactor
  2501. # The scaling factor depending on choice of units.
  2502. factor = 1/25.4
  2503. if self.ui.general_options_form.general_app_group.units_radio.get_value().upper() == 'MM':
  2504. factor = 25.4
  2505. # Changing project units. Warn user.
  2506. msgbox = QtWidgets.QMessageBox()
  2507. msgbox.setText("<B>Change project units ...</B>")
  2508. msgbox.setInformativeText("Changing the units of the project causes all geometrical "
  2509. "properties of all objects to be scaled accordingly. Continue?")
  2510. msgbox.setStandardButtons(QtWidgets.QMessageBox.Cancel | QtWidgets.QMessageBox.Ok)
  2511. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  2512. response = msgbox.exec_()
  2513. if response == QtWidgets.QMessageBox.Ok:
  2514. self.options_read_form()
  2515. scale_options(factor)
  2516. self.options_write_form()
  2517. self.should_we_save = True
  2518. # change this only if the workspace is active
  2519. if self.defaults['global_workspace'] is True:
  2520. self.plotcanvas.draw_workspace()
  2521. # adjust the grid values on the main toolbar
  2522. self.ui.grid_gap_x_entry.set_value(float(self.ui.grid_gap_x_entry.get_value()) * factor)
  2523. self.ui.grid_gap_y_entry.set_value(float(self.ui.grid_gap_y_entry.get_value()) * factor)
  2524. for obj in self.collection.get_list():
  2525. units = self.ui.general_options_form.general_app_group.units_radio.get_value().upper()
  2526. obj.convert_units(units)
  2527. # make that the properties stored in the object are also updated
  2528. self.object_changed.emit(obj)
  2529. obj.build_ui()
  2530. current = self.collection.get_active()
  2531. if current is not None:
  2532. # the transfer of converted values to the UI form for Geometry is done local in the FlatCAMObj.py
  2533. if not isinstance(current, FlatCAMGeometry):
  2534. current.to_form()
  2535. self.plot_all()
  2536. self.inform.emit("[success]Converted units to %s" % self.options["units"])
  2537. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  2538. self.set_screen_units(self.options["units"])
  2539. else:
  2540. # Undo toggling
  2541. self.toggle_units_ignore = True
  2542. if self.ui.general_options_form.general_app_group.units_radio.get_value().upper() == 'MM':
  2543. self.ui.general_options_form.general_app_group.units_radio.set_value('IN')
  2544. else:
  2545. self.ui.general_options_form.general_app_group.units_radio.set_value('MM')
  2546. self.toggle_units_ignore = False
  2547. self.inform.emit("[WARNING_NOTCL]Units conversion cancelled.")
  2548. self.options_read_form()
  2549. def on_toggle_units_click(self):
  2550. if self.options["units"] == 'MM':
  2551. self.ui.general_options_form.general_app_group.units_radio.set_value("IN")
  2552. else:
  2553. self.ui.general_options_form.general_app_group.units_radio.set_value("MM")
  2554. self.on_toggle_units()
  2555. def on_language_apply(self):
  2556. self.report_usage("on_language_apply()")
  2557. # TODO: apply the language
  2558. # app restart section
  2559. pass
  2560. def on_fullscreen(self):
  2561. self.report_usage("on_fullscreen()")
  2562. if self.toggle_fscreen is False:
  2563. if sys.platform == 'win32':
  2564. self.ui.showFullScreen()
  2565. for tb in self.ui.findChildren(QtWidgets.QToolBar):
  2566. tb.setVisible(False)
  2567. self.ui.splitter_left.setVisible(False)
  2568. self.toggle_fscreen = True
  2569. else:
  2570. if sys.platform == 'win32':
  2571. self.ui.showNormal()
  2572. self.restore_toolbar_view()
  2573. self.ui.splitter_left.setVisible(True)
  2574. self.toggle_fscreen = False
  2575. def on_toggle_plotarea(self):
  2576. self.report_usage("on_toggle_plotarea()")
  2577. try:
  2578. name = self.ui.plot_tab_area.widget(0).objectName()
  2579. except AttributeError:
  2580. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  2581. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  2582. self.ui.plot_tab_area.protectTab(0)
  2583. return
  2584. if name != 'plotarea':
  2585. self.ui.plot_tab_area.insertTab(0, self.ui.plot_tab, "Plot Area")
  2586. # remove the close button from the Plot Area tab (first tab index = 0) as this one will always be ON
  2587. self.ui.plot_tab_area.protectTab(0)
  2588. else:
  2589. self.ui.plot_tab_area.closeTab(0)
  2590. def on_toggle_notebook(self):
  2591. if self.ui.splitter.sizes()[0] == 0:
  2592. self.ui.splitter.setSizes([1, 1])
  2593. else:
  2594. self.ui.splitter.setSizes([0, 1])
  2595. def on_toggle_axis(self):
  2596. self.report_usage("on_toggle_axis()")
  2597. if self.toggle_axis is False:
  2598. self.plotcanvas.v_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  2599. self.plotcanvas.h_line.set_data(color=(0.70, 0.3, 0.3, 1.0))
  2600. self.plotcanvas.redraw()
  2601. self.toggle_axis = True
  2602. else:
  2603. self.plotcanvas.v_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  2604. self.plotcanvas.h_line.set_data(color=(0.0, 0.0, 0.0, 0.0))
  2605. self.plotcanvas.redraw()
  2606. self.toggle_axis = False
  2607. def on_toggle_grid(self):
  2608. self.report_usage("on_toggle_grid()")
  2609. self.ui.grid_snap_btn.trigger()
  2610. def on_toggle_code_editor(self):
  2611. self.report_usage("on_toggle_code_editor()")
  2612. if self.toggle_codeeditor is False:
  2613. # add the tab if it was closed
  2614. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, "Code Editor")
  2615. self.ui.cncjob_tab.setObjectName('cncjob_tab')
  2616. # first clear previous text in text editor (if any)
  2617. self.ui.code_editor.clear()
  2618. # Switch plot_area to CNCJob tab
  2619. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  2620. self.toggle_codeeditor = True
  2621. else:
  2622. for idx in range(self.ui.plot_tab_area.count()):
  2623. if self.ui.plot_tab_area.widget(idx).objectName() == "cncjob_tab":
  2624. self.ui.plot_tab_area.closeTab(idx)
  2625. break
  2626. self.toggle_codeeditor = False
  2627. def on_options_combo_change(self, sel):
  2628. """
  2629. Called when the combo box to choose between application defaults and
  2630. project option changes value. The corresponding variables are
  2631. copied to the UI.
  2632. :param sel: The option index that was chosen.
  2633. :return: None
  2634. """
  2635. # combo_sel = self.ui.notebook.combo_options.get_active()
  2636. App.log.debug("Options --> %s" % sel)
  2637. # form = [self.defaults_form, self.options_form][sel]
  2638. # self.ui.notebook.options_contents.pack_start(form, False, False, 1)
  2639. if sel == 0:
  2640. self.gen_form = self.ui.general_defaults_form
  2641. self.ger_form = self.ui.gerber_defaults_form
  2642. self.exc_form = self.ui.excellon_defaults_form
  2643. self.geo_form = self.ui.geometry_defaults_form
  2644. self.cnc_form = self.ui.cncjob_defaults_form
  2645. self.tools_form = self.ui.tools_defaults_form
  2646. elif sel == 1:
  2647. self.gen_form = self.ui.general_options_form
  2648. self.ger_form = self.ui.gerber_options_form
  2649. self.exc_form = self.ui.excellon_options_form
  2650. self.geo_form = self.ui.geometry_options_form
  2651. self.cnc_form = self.ui.cncjob_options_form
  2652. self.tools_form = self.ui.tools_options_form
  2653. else:
  2654. return
  2655. try:
  2656. self.ui.general_scroll_area.takeWidget()
  2657. except:
  2658. self.log.debug("Nothing to remove")
  2659. self.ui.general_scroll_area.setWidget(self.gen_form)
  2660. self.gen_form.show()
  2661. try:
  2662. self.ui.gerber_scroll_area.takeWidget()
  2663. except:
  2664. self.log.debug("Nothing to remove")
  2665. self.ui.gerber_scroll_area.setWidget(self.ger_form)
  2666. self.ger_form.show()
  2667. try:
  2668. self.ui.excellon_scroll_area.takeWidget()
  2669. except:
  2670. self.log.debug("Nothing to remove")
  2671. self.ui.excellon_scroll_area.setWidget(self.exc_form)
  2672. self.exc_form.show()
  2673. try:
  2674. self.ui.geometry_scroll_area.takeWidget()
  2675. except:
  2676. self.log.debug("Nothing to remove")
  2677. self.ui.geometry_scroll_area.setWidget(self.geo_form)
  2678. self.geo_form.show()
  2679. try:
  2680. self.ui.cncjob_scroll_area.takeWidget()
  2681. except:
  2682. self.log.debug("Nothing to remove")
  2683. self.ui.cncjob_scroll_area.setWidget(self.cnc_form)
  2684. self.cnc_form.show()
  2685. try:
  2686. self.ui.tools_scroll_area.takeWidget()
  2687. except:
  2688. self.log.debug("Nothing to remove")
  2689. self.ui.tools_scroll_area.setWidget(self.tools_form)
  2690. self.tools_form.show()
  2691. self.log.debug("Finished GUI form initialization.")
  2692. # self.options2form()
  2693. def on_excellon_defaults_button(self):
  2694. self.defaults_form_fields["excellon_format_lower_in"].set_value('4')
  2695. self.defaults_form_fields["excellon_format_upper_in"].set_value('2')
  2696. self.defaults_form_fields["excellon_format_lower_mm"].set_value('3')
  2697. self.defaults_form_fields["excellon_format_upper_mm"].set_value('3')
  2698. self.defaults_form_fields["excellon_zeros"].set_value('L')
  2699. self.defaults_form_fields["excellon_units"].set_value('INCH')
  2700. log.debug("Excellon app defaults loaded ...")
  2701. def on_excellon_options_button(self):
  2702. self.options_form_fields["excellon_format_lower_in"].set_value('4')
  2703. self.options_form_fields["excellon_format_upper_in"].set_value('2')
  2704. self.options_form_fields["excellon_format_lower_mm"].set_value('3')
  2705. self.options_form_fields["excellon_format_upper_mm"].set_value('3')
  2706. self.options_form_fields["excellon_zeros"].set_value('L')
  2707. self.options_form_fields["excellon_units"].set_value('INCH')
  2708. log.debug("Excellon options defaults loaded ...")
  2709. # Setting plot colors handlers
  2710. def on_pf_color_entry(self):
  2711. self.defaults['global_plot_fill'] = self.ui.general_defaults_form.general_gui_group.pf_color_entry.get_value()[:7] + \
  2712. self.defaults['global_plot_fill'][7:9]
  2713. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  2714. "background-color:%s" % str(self.defaults['global_plot_fill'])[:7])
  2715. def on_pf_color_button(self):
  2716. current_color = QtGui.QColor(self.defaults['global_plot_fill'][:7])
  2717. c_dialog = QtWidgets.QColorDialog()
  2718. plot_fill_color = c_dialog.getColor(initial=current_color)
  2719. if plot_fill_color.isValid() is False:
  2720. return
  2721. self.ui.general_defaults_form.general_gui_group.pf_color_button.setStyleSheet(
  2722. "background-color:%s" % str(plot_fill_color.name()))
  2723. new_val = str(plot_fill_color.name()) + str(self.defaults['global_plot_fill'][7:9])
  2724. self.ui.general_defaults_form.general_gui_group.pf_color_entry.set_value(new_val)
  2725. self.defaults['global_plot_fill'] = new_val
  2726. def on_pf_color_spinner(self):
  2727. spinner_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.value()
  2728. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.setValue(spinner_value)
  2729. self.defaults['global_plot_fill'] = self.defaults['global_plot_fill'][:7] + \
  2730. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2731. self.defaults['global_plot_line'] = self.defaults['global_plot_line'][:7] + \
  2732. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2733. def on_pf_color_slider(self):
  2734. slider_value = self.ui.general_defaults_form.general_gui_group.pf_color_alpha_slider.value()
  2735. self.ui.general_defaults_form.general_gui_group.pf_color_alpha_spinner.setValue(slider_value)
  2736. def on_pl_color_entry(self):
  2737. self.defaults['global_plot_line'] = self.ui.general_defaults_form.general_gui_group.pl_color_entry.get_value()[:7] + \
  2738. self.defaults['global_plot_line'][7:9]
  2739. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  2740. "background-color:%s" % str(self.defaults['global_plot_line'])[:7])
  2741. def on_pl_color_button(self):
  2742. current_color = QtGui.QColor(self.defaults['global_plot_line'][:7])
  2743. # print(current_color)
  2744. c_dialog = QtWidgets.QColorDialog()
  2745. plot_line_color = c_dialog.getColor(initial=current_color)
  2746. if plot_line_color.isValid() is False:
  2747. return
  2748. self.ui.general_defaults_form.general_gui_group.pl_color_button.setStyleSheet(
  2749. "background-color:%s" % str(plot_line_color.name()))
  2750. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_plot_line'][7:9])
  2751. self.ui.general_defaults_form.general_gui_group.pl_color_entry.set_value(new_val_line)
  2752. self.defaults['global_plot_line'] = new_val_line
  2753. # Setting selection colors (left - right) handlers
  2754. def on_sf_color_entry(self):
  2755. self.defaults['global_sel_fill'] = self.ui.general_defaults_form.general_gui_group.sf_color_entry.get_value()[:7] + \
  2756. self.defaults['global_sel_fill'][7:9]
  2757. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  2758. "background-color:%s" % str(self.defaults['global_sel_fill'])[:7])
  2759. def on_sf_color_button(self):
  2760. current_color = QtGui.QColor(self.defaults['global_sel_fill'][:7])
  2761. c_dialog = QtWidgets.QColorDialog()
  2762. plot_fill_color = c_dialog.getColor(initial=current_color)
  2763. if plot_fill_color.isValid() is False:
  2764. return
  2765. self.ui.general_defaults_form.general_gui_group.sf_color_button.setStyleSheet(
  2766. "background-color:%s" % str(plot_fill_color.name()))
  2767. new_val = str(plot_fill_color.name()) + str(self.defaults['global_sel_fill'][7:9])
  2768. self.ui.general_defaults_form.general_gui_group.sf_color_entry.set_value(new_val)
  2769. self.defaults['global_sel_fill'] = new_val
  2770. def on_sf_color_spinner(self):
  2771. spinner_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.value()
  2772. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.setValue(spinner_value)
  2773. self.defaults['global_sel_fill'] = self.defaults['global_sel_fill'][:7] + \
  2774. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2775. self.defaults['global_sel_line'] = self.defaults['global_sel_line'][:7] + \
  2776. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2777. def on_sf_color_slider(self):
  2778. slider_value = self.ui.general_defaults_form.general_gui_group.sf_color_alpha_slider.value()
  2779. self.ui.general_defaults_form.general_gui_group.sf_color_alpha_spinner.setValue(slider_value)
  2780. def on_sl_color_entry(self):
  2781. self.defaults['global_sel_line'] = self.ui.general_defaults_form.general_gui_group.sl_color_entry.get_value()[:7] + \
  2782. self.defaults['global_sel_line'][7:9]
  2783. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  2784. "background-color:%s" % str(self.defaults['global_sel_line'])[:7])
  2785. def on_sl_color_button(self):
  2786. current_color = QtGui.QColor(self.defaults['global_sel_line'][:7])
  2787. c_dialog = QtWidgets.QColorDialog()
  2788. plot_line_color = c_dialog.getColor(initial=current_color)
  2789. if plot_line_color.isValid() is False:
  2790. return
  2791. self.ui.general_defaults_form.general_gui_group.sl_color_button.setStyleSheet(
  2792. "background-color:%s" % str(plot_line_color.name()))
  2793. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_sel_line'][7:9])
  2794. self.ui.general_defaults_form.general_gui_group.sl_color_entry.set_value(new_val_line)
  2795. self.defaults['global_sel_line'] = new_val_line
  2796. # Setting selection colors (right - left) handlers
  2797. def on_alt_sf_color_entry(self):
  2798. self.defaults['global_alt_sel_fill'] = self.ui.general_defaults_form.general_gui_group \
  2799. .alt_sf_color_entry.get_value()[:7] + self.defaults['global_alt_sel_fill'][7:9]
  2800. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  2801. "background-color:%s" % str(self.defaults['global_alt_sel_fill'])[:7])
  2802. def on_alt_sf_color_button(self):
  2803. current_color = QtGui.QColor(self.defaults['global_alt_sel_fill'][:7])
  2804. c_dialog = QtWidgets.QColorDialog()
  2805. plot_fill_color = c_dialog.getColor(initial=current_color)
  2806. if plot_fill_color.isValid() is False:
  2807. return
  2808. self.ui.general_defaults_form.general_gui_group.alt_sf_color_button.setStyleSheet(
  2809. "background-color:%s" % str(plot_fill_color.name()))
  2810. new_val = str(plot_fill_color.name()) + str(self.defaults['global_alt_sel_fill'][7:9])
  2811. self.ui.general_defaults_form.general_gui_group.alt_sf_color_entry.set_value(new_val)
  2812. self.defaults['global_alt_sel_fill'] = new_val
  2813. def on_alt_sf_color_spinner(self):
  2814. spinner_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.value()
  2815. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.setValue(spinner_value)
  2816. self.defaults['global_alt_sel_fill'] = self.defaults['global_alt_sel_fill'][:7] + \
  2817. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2818. self.defaults['global_alt_sel_line'] = self.defaults['global_alt_sel_line'][:7] + \
  2819. (hex(spinner_value)[2:] if int(hex(spinner_value)[2:], 16) > 0 else '00')
  2820. def on_alt_sf_color_slider(self):
  2821. slider_value = self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_slider.value()
  2822. self.ui.general_defaults_form.general_gui_group.alt_sf_color_alpha_spinner.setValue(slider_value)
  2823. def on_alt_sl_color_entry(self):
  2824. self.defaults['global_alt_sel_line'] = self.ui.general_defaults_form.general_gui_group \
  2825. .alt_sl_color_entry.get_value()[:7] + self.defaults['global_alt_sel_line'][7:9]
  2826. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  2827. "background-color:%s" % str(self.defaults['global_alt_sel_line'])[:7])
  2828. def on_alt_sl_color_button(self):
  2829. current_color = QtGui.QColor(self.defaults['global_alt_sel_line'][:7])
  2830. c_dialog = QtWidgets.QColorDialog()
  2831. plot_line_color = c_dialog.getColor(initial=current_color)
  2832. if plot_line_color.isValid() is False:
  2833. return
  2834. self.ui.general_defaults_form.general_gui_group.alt_sl_color_button.setStyleSheet(
  2835. "background-color:%s" % str(plot_line_color.name()))
  2836. new_val_line = str(plot_line_color.name()) + str(self.defaults['global_alt_sel_line'][7:9])
  2837. self.ui.general_defaults_form.general_gui_group.alt_sl_color_entry.set_value(new_val_line)
  2838. self.defaults['global_alt_sel_line'] = new_val_line
  2839. # Setting Editor colors
  2840. def on_draw_color_entry(self):
  2841. self.defaults['global_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  2842. .draw_color_entry.get_value()
  2843. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  2844. "background-color:%s" % str(self.defaults['global_draw_color']))
  2845. def on_draw_color_button(self):
  2846. current_color = QtGui.QColor(self.defaults['global_draw_color'])
  2847. c_dialog = QtWidgets.QColorDialog()
  2848. draw_color = c_dialog.getColor(initial=current_color)
  2849. if draw_color.isValid() is False:
  2850. return
  2851. self.ui.general_defaults_form.general_gui_group.draw_color_button.setStyleSheet(
  2852. "background-color:%s" % str(draw_color.name()))
  2853. new_val = str(draw_color.name())
  2854. self.ui.general_defaults_form.general_gui_group.draw_color_entry.set_value(new_val)
  2855. self.defaults['global_draw_color'] = new_val
  2856. def on_sel_draw_color_entry(self):
  2857. self.defaults['global_sel_draw_color'] = self.ui.general_defaults_form.general_gui_group \
  2858. .sel_draw_color_entry.get_value()
  2859. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  2860. "background-color:%s" % str(self.defaults['global_sel_draw_color']))
  2861. def on_sel_draw_color_button(self):
  2862. current_color = QtGui.QColor(self.defaults['global_sel_draw_color'])
  2863. c_dialog = QtWidgets.QColorDialog()
  2864. sel_draw_color = c_dialog.getColor(initial=current_color)
  2865. if sel_draw_color.isValid() is False:
  2866. return
  2867. self.ui.general_defaults_form.general_gui_group.sel_draw_color_button.setStyleSheet(
  2868. "background-color:%s" % str(sel_draw_color.name()))
  2869. new_val_sel = str(sel_draw_color.name())
  2870. self.ui.general_defaults_form.general_gui_group.sel_draw_color_entry.set_value(new_val_sel)
  2871. self.defaults['global_sel_draw_color'] = new_val_sel
  2872. def on_deselect_all(self):
  2873. self.collection.set_all_inactive()
  2874. self.delete_selection_shape()
  2875. def on_workspace_modified(self):
  2876. self.save_defaults(silent=True)
  2877. self.plotcanvas.draw_workspace()
  2878. def on_workspace(self):
  2879. self.report_usage("on_workspace()")
  2880. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  2881. self.plotcanvas.restore_workspace()
  2882. else:
  2883. self.plotcanvas.delete_workspace()
  2884. self.save_defaults(silent=True)
  2885. def on_workspace_menu(self):
  2886. if self.ui.general_defaults_form.general_gui_group.workspace_cb.isChecked():
  2887. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(False)
  2888. else:
  2889. self.ui.general_defaults_form.general_gui_group.workspace_cb.setChecked(True)
  2890. self.on_workspace()
  2891. def on_layout(self, index, lay=None):
  2892. self.report_usage("on_layout()")
  2893. if lay:
  2894. current_layout = lay
  2895. else:
  2896. current_layout = self.ui.general_defaults_form.general_gui_set_group.layout_combo.get_value().lower()
  2897. settings = QSettings("Open Source", "FlatCAM")
  2898. settings.setValue('layout', current_layout)
  2899. # This will write the setting to the platform specific storage.
  2900. del settings
  2901. # first remove the toolbars:
  2902. self.ui.removeToolBar(self.ui.toolbarfile)
  2903. self.ui.removeToolBar(self.ui.toolbargeo)
  2904. self.ui.removeToolBar(self.ui.toolbarview)
  2905. self.ui.removeToolBar(self.ui.toolbarshell)
  2906. self.ui.removeToolBar(self.ui.toolbartools)
  2907. self.ui.removeToolBar(self.ui.exc_edit_toolbar)
  2908. self.ui.removeToolBar(self.ui.geo_edit_toolbar)
  2909. self.ui.removeToolBar(self.ui.snap_toolbar)
  2910. self.ui.removeToolBar(self.ui.toolbarshell)
  2911. if current_layout == 'standard':
  2912. ### TOOLBAR INSTALLATION ###
  2913. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  2914. self.ui.toolbarfile.setObjectName('File_TB')
  2915. self.ui.addToolBar(self.ui.toolbarfile)
  2916. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  2917. self.ui.toolbargeo.setObjectName('Edit_TB')
  2918. self.ui.addToolBar(self.ui.toolbargeo)
  2919. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  2920. self.ui.toolbarview.setObjectName('View_TB')
  2921. self.ui.addToolBar(self.ui.toolbarview)
  2922. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  2923. self.ui.toolbarshell.setObjectName('Shell_TB')
  2924. self.ui.addToolBar(self.ui.toolbarshell)
  2925. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  2926. self.ui.toolbartools.setObjectName('Tools_TB')
  2927. self.ui.addToolBar(self.ui.toolbartools)
  2928. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  2929. self.ui.exc_edit_toolbar.setVisible(False)
  2930. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  2931. self.ui.addToolBar(self.ui.exc_edit_toolbar)
  2932. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  2933. self.ui.geo_edit_toolbar.setVisible(False)
  2934. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  2935. self.ui.addToolBar(self.ui.geo_edit_toolbar)
  2936. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  2937. self.ui.snap_toolbar.setObjectName('Snap_TB')
  2938. # self.ui.snap_toolbar.setMaximumHeight(30)
  2939. self.ui.addToolBar(self.ui.snap_toolbar)
  2940. self.ui.corner_snap_btn.setVisible(False)
  2941. self.ui.snap_magnet.setVisible(False)
  2942. elif current_layout == 'compact':
  2943. ### TOOLBAR INSTALLATION ###
  2944. self.ui.toolbarfile = QtWidgets.QToolBar('File Toolbar')
  2945. self.ui.toolbarfile.setObjectName('File_TB')
  2946. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarfile)
  2947. self.ui.toolbargeo = QtWidgets.QToolBar('Edit Toolbar')
  2948. self.ui.toolbargeo.setObjectName('Edit_TB')
  2949. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbargeo)
  2950. self.ui.toolbarview = QtWidgets.QToolBar('View Toolbar')
  2951. self.ui.toolbarview.setObjectName('View_TB')
  2952. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarview)
  2953. self.ui.toolbarshell = QtWidgets.QToolBar('Shell Toolbar')
  2954. self.ui.toolbarshell.setObjectName('Shell_TB')
  2955. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbarshell)
  2956. self.ui.toolbartools = QtWidgets.QToolBar('Tools Toolbar')
  2957. self.ui.toolbartools.setObjectName('Tools_TB')
  2958. self.ui.addToolBar(Qt.LeftToolBarArea, self.ui.toolbartools)
  2959. self.ui.geo_edit_toolbar = QtWidgets.QToolBar('Geometry Editor Toolbar')
  2960. # self.ui.geo_edit_toolbar.setVisible(False)
  2961. self.ui.geo_edit_toolbar.setObjectName('GeoEditor_TB')
  2962. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.geo_edit_toolbar)
  2963. self.ui.exc_edit_toolbar = QtWidgets.QToolBar('Excellon Editor Toolbar')
  2964. self.ui.exc_edit_toolbar.setObjectName('ExcEditor_TB')
  2965. self.ui.addToolBar(Qt.RightToolBarArea, self.ui.exc_edit_toolbar)
  2966. self.ui.snap_toolbar = QtWidgets.QToolBar('Grid Toolbar')
  2967. self.ui.snap_toolbar.setObjectName('Snap_TB')
  2968. self.ui.snap_toolbar.setMaximumHeight(30)
  2969. self.ui.splitter_left.addWidget(self.ui.snap_toolbar)
  2970. self.ui.corner_snap_btn.setVisible(True)
  2971. self.ui.snap_magnet.setVisible(True)
  2972. self.ui.populate_toolbars()
  2973. self.ui.grid_snap_btn.setChecked(True)
  2974. self.ui.grid_gap_x_entry.setText(str(self.defaults["global_gridx"]))
  2975. self.ui.grid_gap_y_entry.setText(str(self.defaults["global_gridy"]))
  2976. self.ui.snap_max_dist_entry.setText(str(self.defaults["global_snap_max"]))
  2977. self.ui.grid_gap_link_cb.setChecked(True)
  2978. def on_save_button(self):
  2979. self.save_defaults(silent=False)
  2980. # load the defaults so they are updated into the app
  2981. self.load_defaults(filename='current_defaults')
  2982. # Re-fresh project options
  2983. self.on_options_app2project()
  2984. def handleOpen(self):
  2985. self.report_usage("handleOpen()")
  2986. filter_group = " G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  2987. "All Files (*.*)"
  2988. path, _ = QtWidgets.QFileDialog.getOpenFileName(
  2989. caption='Open file', directory=self.get_last_folder(), filter=filter_group)
  2990. if path:
  2991. file = QtCore.QFile(path)
  2992. if file.open(QtCore.QIODevice.ReadOnly):
  2993. stream = QtCore.QTextStream(file)
  2994. self.gcode_edited = stream.readAll()
  2995. self.ui.code_editor.setPlainText(self.gcode_edited)
  2996. file.close()
  2997. def handlePrint(self):
  2998. self.report_usage("handlePrint()")
  2999. dialog = QtPrintSupport.QPrintDialog()
  3000. if dialog.exec_() == QtWidgets.QDialog.Accepted:
  3001. self.ui.code_editor.document().print_(dialog.printer())
  3002. def handlePreview(self):
  3003. self.report_usage("handlePreview()")
  3004. dialog = QtPrintSupport.QPrintPreviewDialog()
  3005. dialog.paintRequested.connect(self.ui.code_editor.print_)
  3006. dialog.exec_()
  3007. def handleTextChanged(self):
  3008. self.report_usage("handleTextChanged()")
  3009. # enable = not self.ui.code_editor.document().isEmpty()
  3010. # self.ui.buttonPrint.setEnabled(enable)
  3011. # self.ui.buttonPreview.setEnabled(enable)
  3012. pass
  3013. def handleSaveGCode(self, signal, name=None, filt=None):
  3014. self.report_usage("handleSaveGCode()")
  3015. if filt:
  3016. _filter_ = filt
  3017. else:
  3018. _filter_ = "G-Code Files (*.nc);; G-Code Files (*.txt);; G-Code Files (*.tap);; G-Code Files (*.cnc);; " \
  3019. "All Files (*.*)"
  3020. if name:
  3021. obj_name = name
  3022. else:
  3023. try:
  3024. obj_name = self.collection.get_active().options['name']
  3025. except AttributeError:
  3026. obj_name = 'file'
  3027. _filter_ = "FlatConfig Files (*.FlatConfig);;All Files (*.*)"
  3028. try:
  3029. filename = str(QtWidgets.QFileDialog.getSaveFileName(
  3030. caption="Export G-Code ...",
  3031. directory=self.defaults["global_last_folder"] + '/' + str(obj_name),
  3032. filter=_filter_
  3033. )[0])
  3034. except TypeError:
  3035. filename = str(QtWidgets.QFileDialog.getSaveFileName(caption="Export G-Code ...", filter=_filter_)[0])
  3036. if filename == "":
  3037. self.inform.emit("[WARNING_NOTCL]Export Code cancelled.")
  3038. return
  3039. else:
  3040. try:
  3041. my_gcode = self.ui.code_editor.toPlainText()
  3042. with open(filename, 'w') as f:
  3043. for line in my_gcode:
  3044. f.write(line)
  3045. except FileNotFoundError:
  3046. self.inform.emit("[WARNING] No such file or directory")
  3047. return
  3048. # Just for adding it to the recent files list.
  3049. self.file_opened.emit("cncjob", filename)
  3050. self.file_saved.emit("cncjob", filename)
  3051. self.inform.emit("Saved to: " + filename)
  3052. def handleFindGCode(self):
  3053. self.report_usage("handleFindGCode()")
  3054. flags = QtGui.QTextDocument.FindCaseSensitively
  3055. text_to_be_found = self.ui.entryFind.get_value()
  3056. r = self.ui.code_editor.find(str(text_to_be_found), flags)
  3057. if r is False:
  3058. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  3059. def handleReplaceGCode(self):
  3060. self.report_usage("handleReplaceGCode()")
  3061. old = self.ui.entryFind.get_value()
  3062. new = self.ui.entryReplace.get_value()
  3063. if self.ui.sel_all_cb.isChecked():
  3064. while True:
  3065. cursor = self.ui.code_editor.textCursor()
  3066. cursor.beginEditBlock()
  3067. flags = QtGui.QTextDocument.FindCaseSensitively
  3068. # self.ui.editor is the QPlainTextEdit
  3069. r = self.ui.code_editor.find(str(old), flags)
  3070. if r:
  3071. qc = self.ui.code_editor.textCursor()
  3072. if qc.hasSelection():
  3073. qc.insertText(new)
  3074. else:
  3075. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  3076. break
  3077. # Mark end of undo block
  3078. cursor.endEditBlock()
  3079. else:
  3080. cursor = self.ui.code_editor.textCursor()
  3081. cursor.beginEditBlock()
  3082. qc = self.ui.code_editor.textCursor()
  3083. if qc.hasSelection():
  3084. qc.insertText(new)
  3085. # Mark end of undo block
  3086. cursor.endEditBlock()
  3087. def on_tool_add_keypress(self):
  3088. ## Current application units in Upper Case
  3089. self.units = self.ui.general_options_form.general_app_group.units_radio.get_value().upper()
  3090. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3091. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3092. if notebook_widget_name == 'selected_tab':
  3093. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  3094. # Tool add works for Geometry only if Advanced is True in Preferences
  3095. if self.defaults["global_advanced"] is True:
  3096. tool_add_popup = FCInputDialog(title="New Tool ...",
  3097. text='Enter a Tool Diameter:',
  3098. min=0.0000, max=99.9999, decimals=4)
  3099. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  3100. val, ok = tool_add_popup.get_value()
  3101. if ok:
  3102. if float(val) == 0:
  3103. self.inform.emit(
  3104. "[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format.")
  3105. return
  3106. self.collection.get_active().on_tool_add(dia=float(val))
  3107. else:
  3108. self.inform.emit(
  3109. "[WARNING_NOTCL] Adding Tool cancelled ...")
  3110. else:
  3111. msgbox = QtWidgets.QMessageBox()
  3112. msgbox.setText("Adding Tool works only when Advanced is checked.\n"
  3113. "Go to Preferences -> General - Show Advanced Options.")
  3114. msgbox.setWindowTitle("Tool adding ...")
  3115. msgbox.setWindowIcon(QtGui.QIcon('share/warning.png'))
  3116. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  3117. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  3118. msgbox.exec_()
  3119. # work only if the notebook tab on focus is the Tools_Tab
  3120. if notebook_widget_name == 'tool_tab':
  3121. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3122. tool_add_popup = FCInputDialog(title="New Tool ...",
  3123. text='Enter a Tool Diameter:',
  3124. min=0.0000, max=99.9999, decimals=4)
  3125. tool_add_popup.setWindowIcon(QtGui.QIcon('share/letter_t_32.png'))
  3126. val, ok = tool_add_popup.get_value()
  3127. # and only if the tool is NCC Tool
  3128. if tool_widget == self.ncclear_tool.toolName:
  3129. if ok:
  3130. if float(val) == 0:
  3131. self.inform.emit(
  3132. "[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format.")
  3133. return
  3134. self.ncclear_tool.on_tool_add(dia=float(val))
  3135. else:
  3136. self.inform.emit(
  3137. "[WARNING_NOTCL] Adding Tool cancelled ...")
  3138. # and only if the tool is Paint Area Tool
  3139. elif tool_widget == self.paint_tool.toolName:
  3140. if ok:
  3141. if float(val) == 0:
  3142. self.inform.emit(
  3143. "[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format.")
  3144. return
  3145. self.paint_tool.on_tool_add(dia=float(val))
  3146. else:
  3147. self.inform.emit(
  3148. "[WARNING_NOTCL] Adding Tool cancelled ...")
  3149. # and only if the tool is Solder Paste Dispensing Tool
  3150. elif tool_widget == self.paste_tool.toolName:
  3151. if ok:
  3152. if float(val) == 0:
  3153. self.inform.emit(
  3154. "[WARNING_NOTCL] Please enter a tool diameter with non-zero value, in Float format.")
  3155. return
  3156. self.paste_tool.on_tool_add(dia=float(val))
  3157. else:
  3158. self.inform.emit(
  3159. "[WARNING_NOTCL] Adding Tool cancelled ...")
  3160. # It's meant to delete tools in tool tables via a 'Delete' shortcut key but only if certain conditions are met
  3161. # See description bellow.
  3162. def on_delete_keypress(self):
  3163. notebook_widget_name = self.ui.notebook.currentWidget().objectName()
  3164. # work only if the notebook tab on focus is the Selected_Tab and only if the object is Geometry
  3165. if notebook_widget_name == 'selected_tab':
  3166. if str(type(self.collection.get_active())) == "<class 'FlatCAMObj.FlatCAMGeometry'>":
  3167. self.collection.get_active().on_tool_delete()
  3168. # work only if the notebook tab on focus is the Tools_Tab
  3169. elif notebook_widget_name == 'tool_tab':
  3170. tool_widget = self.ui.tool_scroll_area.widget().objectName()
  3171. # and only if the tool is NCC Tool
  3172. if tool_widget == self.ncclear_tool.toolName:
  3173. self.ncclear_tool.on_tool_delete()
  3174. # and only if the tool is Paint Tool
  3175. elif tool_widget == self.paint_tool.toolName:
  3176. self.paint_tool.on_tool_delete()
  3177. # and only if the tool is Solder Paste Dispensing Tool
  3178. elif tool_widget == self.paste_tool.toolName:
  3179. self.paste_tool.on_tool_delete()
  3180. else:
  3181. self.on_delete()
  3182. # It's meant to delete selected objects. It work also activated by a shortcut key 'Delete' same as above so in
  3183. # some screens you have to be careful where you hover with your mouse.
  3184. # Hovering over Selected tab, if the selected tab is a Geometry it will delete tools in tool table. But even if
  3185. # there is a Selected tab in focus with a Geometry inside, if you hover over canvas it will delete an object.
  3186. # Complicated, I know :)
  3187. def on_delete(self):
  3188. """
  3189. Delete the currently selected FlatCAMObjs.
  3190. :return: None
  3191. """
  3192. self.report_usage("on_delete()")
  3193. # Make sure that the deletion will happen only after the Editor is no longer active otherwise we might delete
  3194. # a geometry object before we update it.
  3195. if self.geo_editor.editor_active is False and self.exc_editor.editor_active is False:
  3196. if self.collection.get_active():
  3197. self.log.debug("on_delete()")
  3198. self.report_usage("on_delete")
  3199. while (self.collection.get_active()):
  3200. self.delete_first_selected()
  3201. self.inform.emit("Object(s) deleted ...")
  3202. # make sure that the selection shape is deleted, too
  3203. self.delete_selection_shape()
  3204. else:
  3205. self.inform.emit("Failed. No object(s) selected...")
  3206. else:
  3207. self.inform.emit("Save the work in Editor and try again ...")
  3208. def on_set_origin(self):
  3209. """
  3210. Set the origin to the left mouse click position
  3211. :return: None
  3212. """
  3213. #display the message for the user
  3214. #and ask him to click on the desired position
  3215. self.report_usage("on_set_origin()")
  3216. self.inform.emit('Click to set the origin ...')
  3217. self.plotcanvas.vis_connect('mouse_press', self.on_set_zero_click)
  3218. def on_jump_to(self):
  3219. """
  3220. Jump to a location by setting the mouse cursor location
  3221. :return:
  3222. """
  3223. self.report_usage("on_jump_to()")
  3224. dia_box = Dialog_box(title="Jump to ...",
  3225. label="Enter the coordinates in format X,Y:",
  3226. icon=QtGui.QIcon('share/jump_to16.png'))
  3227. if dia_box.ok is True:
  3228. try:
  3229. location = eval(dia_box.location)
  3230. if not isinstance(location, tuple):
  3231. self.inform.emit("Wrong coordinates. Enter coordinates in format: X,Y")
  3232. return
  3233. except:
  3234. return
  3235. else:
  3236. return
  3237. self.plotcanvas.fit_center(loc=location)
  3238. cursor = QtGui.QCursor()
  3239. canvas_origin = self.plotcanvas.vispy_canvas.native.mapToGlobal(QtCore.QPoint(0, 0))
  3240. jump_loc = self.plotcanvas.vispy_canvas.translate_coords_2((location[0], location[1]))
  3241. cursor.setPos(canvas_origin.x() + jump_loc[0], (canvas_origin.y() + jump_loc[1]))
  3242. self.inform.emit("Done.")
  3243. def on_copy_object(self):
  3244. self.report_usage("on_copy_object()")
  3245. def initialize(obj_init, app):
  3246. obj_init.solid_geometry = obj.solid_geometry
  3247. try:
  3248. if obj.tools:
  3249. obj_init.tools = obj.tools
  3250. except Exception as e:
  3251. log.debug("on_copy_object() --> %s" % str(e))
  3252. def initialize_excellon(obj_init, app):
  3253. obj_init.tools = obj.tools
  3254. # drills are offset, so they need to be deep copied
  3255. obj_init.drills = deepcopy(obj.drills)
  3256. # slots are offset, so they need to be deep copied
  3257. obj_init.slots = deepcopy(obj.slots)
  3258. obj_init.create_geometry()
  3259. for obj in self.collection.get_selected():
  3260. obj_name = obj.options["name"]
  3261. try:
  3262. if isinstance(obj, FlatCAMExcellon):
  3263. self.new_object("excellon", str(obj_name) + "_copy", initialize_excellon)
  3264. elif isinstance(obj,FlatCAMGerber):
  3265. self.new_object("gerber", str(obj_name) + "_copy", initialize)
  3266. elif isinstance(obj,FlatCAMGeometry):
  3267. self.new_object("geometry", str(obj_name) + "_copy", initialize)
  3268. except Exception as e:
  3269. return "Operation failed: %s" % str(e)
  3270. def on_copy_object2(self, custom_name):
  3271. def initialize_geometry(obj_init, app):
  3272. obj_init.solid_geometry = obj.solid_geometry
  3273. try:
  3274. if obj.tools:
  3275. obj_init.tools = obj.tools
  3276. except Exception as e:
  3277. log.debug("on_copy_object2() --> %s" % str(e))
  3278. def initialize_gerber(obj_init, app):
  3279. obj_init.solid_geometry = obj.solid_geometry
  3280. obj_init.apertures = deepcopy(obj.apertures)
  3281. obj_init.aperture_macros = deepcopy(obj.aperture_macros)
  3282. def initialize_excellon(obj_init, app):
  3283. obj_init.tools = obj.tools
  3284. # drills are offset, so they need to be deep copied
  3285. obj_init.drills = deepcopy(obj.drills)
  3286. # slots are offset, so they need to be deep copied
  3287. obj_init.slots = deepcopy(obj.slots)
  3288. obj_init.create_geometry()
  3289. for obj in self.collection.get_selected():
  3290. obj_name = obj.options["name"]
  3291. try:
  3292. if isinstance(obj, FlatCAMExcellon):
  3293. self.new_object("excellon", str(obj_name) + custom_name, initialize_excellon)
  3294. elif isinstance(obj,FlatCAMGerber):
  3295. self.new_object("gerber", str(obj_name) + custom_name, initialize_gerber)
  3296. elif isinstance(obj,FlatCAMGeometry):
  3297. self.new_object("geometry", str(obj_name) + custom_name, initialize_geometry)
  3298. except Exception as e:
  3299. return "Operation failed: %s" % str(e)
  3300. def on_rename_object(self, text):
  3301. self.report_usage("on_rename_object()")
  3302. named_obj = self.collection.get_active()
  3303. for obj in named_obj:
  3304. if obj is list:
  3305. self.on_rename_object(text)
  3306. else:
  3307. try:
  3308. obj.options['name'] = text
  3309. except:
  3310. log.warning("Could not rename the object in the list")
  3311. def on_copy_object_as_geometry(self):
  3312. self.report_usage("on_copy_object_as_geometry()")
  3313. def initialize(obj_init, app):
  3314. obj_init.solid_geometry = obj.solid_geometry
  3315. if obj.tools:
  3316. obj_init.tools = obj.tools
  3317. def initialize_excellon(obj, app):
  3318. objs = self.collection.get_selected()
  3319. FlatCAMGeometry.merge(objs, obj)
  3320. for obj in self.collection.get_selected():
  3321. obj_name = obj.options["name"]
  3322. try:
  3323. if isinstance(obj, FlatCAMExcellon):
  3324. self.new_object("geometry", str(obj_name) + "_gcopy", initialize_excellon)
  3325. else:
  3326. self.new_object("geometry", str(obj_name) + "_gcopy", initialize)
  3327. except Exception as e:
  3328. return "Operation failed: %s" % str(e)
  3329. def on_set_zero_click(self, event):
  3330. #this function will be available only for mouse left click
  3331. pos =[]
  3332. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3333. if event.button == 1:
  3334. if self.grid_status() == True:
  3335. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3336. else:
  3337. pos = pos_canvas
  3338. x = 0 - pos[0]
  3339. y = 0 - pos[1]
  3340. for obj in self.collection.get_list():
  3341. obj.offset((x,y))
  3342. self.object_changed.emit(obj)
  3343. # obj.plot()
  3344. self.plot_all(zoom=False)
  3345. self.inform.emit('[success] Origin set ...')
  3346. self.plotcanvas.vis_disconnect('mouse_press', self.on_set_zero_click)
  3347. self.should_we_save = True
  3348. def on_selectall(self):
  3349. self.report_usage("on_selectall()")
  3350. # delete the possible selection box around a possible selected object
  3351. self.delete_selection_shape()
  3352. for name in self.collection.get_names():
  3353. self.collection.set_active(name)
  3354. curr_sel_obj = self.collection.get_by_name(name)
  3355. # create the selection box around the selected object
  3356. self.draw_selection_shape(curr_sel_obj)
  3357. def on_preferences(self):
  3358. # add the tab if it was closed
  3359. self.ui.plot_tab_area.addTab(self.ui.preferences_tab, "Preferences")
  3360. # delete the absolute and relative position and messages in the infobar
  3361. self.ui.position_label.setText("")
  3362. self.ui.rel_position_label.setText("")
  3363. # Switch plot_area to preferences page
  3364. self.ui.plot_tab_area.setCurrentWidget(self.ui.preferences_tab)
  3365. self.ui.show()
  3366. def on_flipy(self):
  3367. self.report_usage("on_flipy()")
  3368. obj_list = self.collection.get_selected()
  3369. xminlist = []
  3370. yminlist = []
  3371. xmaxlist = []
  3372. ymaxlist = []
  3373. if not obj_list:
  3374. self.inform.emit("[WARNING_NOTCL] No object selected to Flip on Y axis.")
  3375. else:
  3376. try:
  3377. # first get a bounding box to fit all
  3378. for obj in obj_list:
  3379. xmin, ymin, xmax, ymax = obj.bounds()
  3380. xminlist.append(xmin)
  3381. yminlist.append(ymin)
  3382. xmaxlist.append(xmax)
  3383. ymaxlist.append(ymax)
  3384. # get the minimum x,y and maximum x,y for all objects selected
  3385. xminimal = min(xminlist)
  3386. yminimal = min(yminlist)
  3387. xmaximal = max(xmaxlist)
  3388. ymaximal = max(ymaxlist)
  3389. px = 0.5 * (xminimal + xmaximal)
  3390. py = 0.5 * (yminimal + ymaximal)
  3391. # execute mirroring
  3392. for obj in obj_list:
  3393. obj.mirror('X', [px, py])
  3394. obj.plot()
  3395. self.object_changed.emit(obj)
  3396. self.inform.emit("[success] Flip on Y axis done.")
  3397. except Exception as e:
  3398. self.inform.emit("[ERROR_NOTCL] Due of %s, Flip action was not executed." % str(e))
  3399. return
  3400. def on_flipx(self):
  3401. self.report_usage("on_flipx()")
  3402. obj_list = self.collection.get_selected()
  3403. xminlist = []
  3404. yminlist = []
  3405. xmaxlist = []
  3406. ymaxlist = []
  3407. if not obj_list:
  3408. self.inform.emit("[WARNING_NOTCL] No object selected to Flip on X axis.")
  3409. else:
  3410. try:
  3411. # first get a bounding box to fit all
  3412. for obj in obj_list:
  3413. xmin, ymin, xmax, ymax = obj.bounds()
  3414. xminlist.append(xmin)
  3415. yminlist.append(ymin)
  3416. xmaxlist.append(xmax)
  3417. ymaxlist.append(ymax)
  3418. # get the minimum x,y and maximum x,y for all objects selected
  3419. xminimal = min(xminlist)
  3420. yminimal = min(yminlist)
  3421. xmaximal = max(xmaxlist)
  3422. ymaximal = max(ymaxlist)
  3423. px = 0.5 * (xminimal + xmaximal)
  3424. py = 0.5 * (yminimal + ymaximal)
  3425. # execute mirroring
  3426. for obj in obj_list:
  3427. obj.mirror('Y', [px, py])
  3428. obj.plot()
  3429. self.object_changed.emit(obj)
  3430. self.inform.emit("[success] Flip on X axis done.")
  3431. except Exception as e:
  3432. self.inform.emit("[ERROR_NOTCL] Due of %s, Flip action was not executed." % str(e))
  3433. return
  3434. def on_rotate(self, silent=False, preset=None):
  3435. self.report_usage("on_rotate()")
  3436. obj_list = self.collection.get_selected()
  3437. xminlist = []
  3438. yminlist = []
  3439. xmaxlist = []
  3440. ymaxlist = []
  3441. if not obj_list:
  3442. self.inform.emit("[WARNING_NOTCL] No object selected to Rotate.")
  3443. else:
  3444. if silent is False:
  3445. rotatebox = FCInputDialog(title="Transform", text="Enter the Angle value:",
  3446. min=-360, max=360, decimals=4,
  3447. init_val=float(self.defaults['tools_transform_rotate']))
  3448. num, ok = rotatebox.get_value()
  3449. else:
  3450. num = preset
  3451. ok = True
  3452. if ok:
  3453. try:
  3454. # first get a bounding box to fit all
  3455. for obj in obj_list:
  3456. xmin, ymin, xmax, ymax = obj.bounds()
  3457. xminlist.append(xmin)
  3458. yminlist.append(ymin)
  3459. xmaxlist.append(xmax)
  3460. ymaxlist.append(ymax)
  3461. # get the minimum x,y and maximum x,y for all objects selected
  3462. xminimal = min(xminlist)
  3463. yminimal = min(yminlist)
  3464. xmaximal = max(xmaxlist)
  3465. ymaximal = max(ymaxlist)
  3466. px = 0.5 * (xminimal + xmaximal)
  3467. py = 0.5 * (yminimal + ymaximal)
  3468. for sel_obj in obj_list:
  3469. sel_obj.rotate(-float(num), point=(px, py))
  3470. sel_obj.plot()
  3471. self.object_changed.emit(sel_obj)
  3472. self.inform.emit("[success] Rotation done.")
  3473. except Exception as e:
  3474. self.inform.emit("[ERROR_NOTCL] Due of %s, rotation movement was not executed." % str(e))
  3475. return
  3476. def on_skewx(self):
  3477. self.report_usage("on_skewx()")
  3478. obj_list = self.collection.get_selected()
  3479. xminlist = []
  3480. yminlist = []
  3481. if not obj_list:
  3482. self.inform.emit("[WARNING_NOTCL] No object selected to Skew/Shear on X axis.")
  3483. else:
  3484. skewxbox = FCInputDialog(title="Transform", text="Enter the Angle value:",
  3485. min=-360, max=360, decimals=4,
  3486. init_val=float(self.defaults['tools_transform_skew_x']))
  3487. num, ok = skewxbox.get_value()
  3488. if ok:
  3489. # first get a bounding box to fit all
  3490. for obj in obj_list:
  3491. xmin, ymin, xmax, ymax = obj.bounds()
  3492. xminlist.append(xmin)
  3493. yminlist.append(ymin)
  3494. # get the minimum x,y and maximum x,y for all objects selected
  3495. xminimal = min(xminlist)
  3496. yminimal = min(yminlist)
  3497. for obj in obj_list:
  3498. obj.skew(num, 0, point=(xminimal, yminimal))
  3499. obj.plot()
  3500. self.object_changed.emit(obj)
  3501. self.inform.emit("[success] Skew on X axis done.")
  3502. def on_skewy(self):
  3503. self.report_usage("on_skewy()")
  3504. obj_list = self.collection.get_selected()
  3505. xminlist = []
  3506. yminlist = []
  3507. if not obj_list:
  3508. self.inform.emit("[WARNING_NOTCL] No object selected to Skew/Shear on Y axis.")
  3509. else:
  3510. skewybox = FCInputDialog(title="Transform", text="Enter the Angle value:",
  3511. min=-360, max=360, decimals=4,
  3512. init_val=float(self.defaults['tools_transform_skew_y']))
  3513. num, ok = skewybox.get_value()
  3514. if ok:
  3515. # first get a bounding box to fit all
  3516. for obj in obj_list:
  3517. xmin, ymin, xmax, ymax = obj.bounds()
  3518. xminlist.append(xmin)
  3519. yminlist.append(ymin)
  3520. # get the minimum x,y and maximum x,y for all objects selected
  3521. xminimal = min(xminlist)
  3522. yminimal = min(yminlist)
  3523. for obj in obj_list:
  3524. obj.skew(0, num, point=(xminimal, yminimal))
  3525. obj.plot()
  3526. self.object_changed.emit(obj)
  3527. self.inform.emit("[success] Skew on Y axis done.")
  3528. def delete_first_selected(self):
  3529. # Keep this for later
  3530. try:
  3531. name = self.collection.get_active().options["name"]
  3532. except AttributeError:
  3533. self.log.debug("Nothing selected for deletion")
  3534. return
  3535. # Remove plot
  3536. # self.plotcanvas.figure.delaxes(self.collection.get_active().axes)
  3537. # self.plotcanvas.auto_adjust_axes()
  3538. # Clear form
  3539. self.setup_component_editor()
  3540. # Remove from dictionary
  3541. self.collection.delete_active()
  3542. self.inform.emit("Object deleted: %s" % name)
  3543. def on_plots_updated(self):
  3544. """
  3545. Callback used to report when the plots have changed.
  3546. Adjust axes and zooms to fit.
  3547. :return: None
  3548. """
  3549. # self.plotcanvas.auto_adjust_axes()
  3550. self.plotcanvas.vispy_canvas.update() # TODO: Need update canvas?
  3551. self.on_zoom_fit(None)
  3552. # TODO: Rework toolbar 'clear', 'replot' functions
  3553. def on_toolbar_replot(self):
  3554. """
  3555. Callback for toolbar button. Re-plots all objects.
  3556. :return: None
  3557. """
  3558. self.report_usage("on_toolbar_replot")
  3559. self.log.debug("on_toolbar_replot()")
  3560. try:
  3561. self.collection.get_active().read_form()
  3562. except AttributeError:
  3563. self.log.debug("on_toolbar_replot(): AttributeError")
  3564. pass
  3565. self.plot_all()
  3566. def on_row_activated(self, index):
  3567. if index.isValid():
  3568. if index.internalPointer().parent_item != self.collection.root_item:
  3569. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  3570. def grid_status(self):
  3571. if self.ui.grid_snap_btn.isChecked():
  3572. return 1
  3573. else:
  3574. return 0
  3575. def populate_cmenu_grids(self):
  3576. units = self.ui.general_options_form.general_app_group.units_radio.get_value().lower()
  3577. self.ui.cmenu_gridmenu.clear()
  3578. sorted_list = sorted(self.defaults["global_grid_context_menu"][str(units)])
  3579. for grid in sorted_list:
  3580. action = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/grid32_menu.png'), "%s" % str(grid))
  3581. action.triggered.connect(self.set_grid)
  3582. self.ui.cmenu_gridmenu.addSeparator()
  3583. grid_add = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/plus32.png'), "Add")
  3584. grid_add.triggered.connect(self.on_grid_add)
  3585. grid_delete = self.ui.cmenu_gridmenu.addAction(QtGui.QIcon('share/delete32.png'), "Delete")
  3586. grid_delete.triggered.connect(self.on_grid_delete)
  3587. def set_grid(self):
  3588. self.ui.grid_gap_x_entry.setText(self.sender().text())
  3589. self.ui.grid_gap_y_entry.setText(self.sender().text())
  3590. def on_grid_add(self):
  3591. ## Current application units in lower Case
  3592. units = self.ui.general_options_form.general_app_group.units_radio.get_value().lower()
  3593. grid_add_popup = FCInputDialog(title="New Grid ...",
  3594. text='Enter a Grid VAlue:',
  3595. min=0.0000, max=99.9999, decimals=4)
  3596. grid_add_popup.setWindowIcon(QtGui.QIcon('share/plus32.png'))
  3597. val, ok = grid_add_popup.get_value()
  3598. if ok:
  3599. if float(val) == 0:
  3600. self.inform.emit(
  3601. "[WARNING_NOTCL] Please enter a grid value with non-zero value, in Float format.")
  3602. return
  3603. else:
  3604. if val not in self.defaults["global_grid_context_menu"][str(units)]:
  3605. self.defaults["global_grid_context_menu"][str(units)].append(val)
  3606. self.inform.emit(
  3607. "[success] New Grid added ...")
  3608. else:
  3609. self.inform.emit(
  3610. "[WARNING_NOTCL] Grid already exists ...")
  3611. else:
  3612. self.inform.emit(
  3613. "[WARNING_NOTCL] Adding New Grid cancelled ...")
  3614. def on_grid_delete(self):
  3615. ## Current application units in lower Case
  3616. units = self.ui.general_options_form.general_app_group.units_radio.get_value().lower()
  3617. grid_del_popup = FCInputDialog(title="Delete Grid ...",
  3618. text='Enter a Grid Value:',
  3619. min=0.0000, max=99.9999, decimals=4)
  3620. grid_del_popup.setWindowIcon(QtGui.QIcon('share/delete32.png'))
  3621. val, ok = grid_del_popup.get_value()
  3622. if ok:
  3623. if float(val) == 0:
  3624. self.inform.emit(
  3625. "[WARNING_NOTCL] Please enter a grid value with non-zero value, in Float format.")
  3626. return
  3627. else:
  3628. try:
  3629. self.defaults["global_grid_context_menu"][str(units)].remove(val)
  3630. except ValueError:
  3631. self.inform.emit(
  3632. "[ERROR_NOTCL] Grid Value does not exist ...")
  3633. return
  3634. self.inform.emit(
  3635. "[success] Grid Value deleted ...")
  3636. else:
  3637. self.inform.emit(
  3638. "[WARNING_NOTCL] Delete Grid value cancelled ...")
  3639. def on_shortcut_list(self):
  3640. self.report_usage("on_shortcut_list()")
  3641. # add the tab if it was closed
  3642. self.ui.plot_tab_area.addTab(self.ui.shortcuts_tab, "Key Shortcut List")
  3643. # delete the absolute and relative position and messages in the infobar
  3644. self.ui.position_label.setText("")
  3645. self.ui.rel_position_label.setText("")
  3646. # Switch plot_area to preferences page
  3647. self.ui.plot_tab_area.setCurrentWidget(self.ui.shortcuts_tab)
  3648. self.ui.show()
  3649. def on_select_tab(self, name):
  3650. if name == 'project':
  3651. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  3652. elif name == 'selected':
  3653. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  3654. elif name == 'tool':
  3655. self.ui.notebook.setCurrentWidget(self.ui.tool_tab)
  3656. # if the splitter us hidden, display it
  3657. if self.ui.splitter.sizes()[0] == 0:
  3658. self.ui.splitter.setSizes([1, 1])
  3659. def on_copy_name(self):
  3660. self.report_usage("on_copy_name()")
  3661. obj = self.collection.get_active()
  3662. try:
  3663. name = obj.options["name"]
  3664. except AttributeError:
  3665. log.debug("on_copy_name() --> No object selected to copy it's name")
  3666. self.inform.emit("[WARNING_NOTCL]No object selected to copy it's name")
  3667. return
  3668. self.clipboard.setText(name)
  3669. self.inform.emit("Name copied on clipboard ...")
  3670. def on_mouse_click_over_plot(self, event):
  3671. """
  3672. Callback for the mouse click event over the plot. This event is generated
  3673. by the Matplotlib backend and has been registered in ``self.__init__()``.
  3674. For details, see: http://matplotlib.org/users/event_handling.html
  3675. Default actions are:
  3676. * Copy coordinates to clipboard. Ex.: (65.5473, -13.2679)
  3677. :param event: Contains information about the event, like which button
  3678. was clicked, the pixel coordinates and the axes coordinates.
  3679. :return: None
  3680. """
  3681. self.pos = []
  3682. # So it can receive key presses
  3683. self.plotcanvas.vispy_canvas.native.setFocus()
  3684. # Set the mouse button for panning
  3685. self.plotcanvas.vispy_canvas.view.camera.pan_button_setting = self.defaults['global_pan_button']
  3686. self.pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3687. if self.grid_status() == True:
  3688. self.pos = self.geo_editor.snap(self.pos_canvas[0], self.pos_canvas[1])
  3689. self.app_cursor.enabled = True
  3690. else:
  3691. self.pos = (self.pos_canvas[0], self.pos_canvas[1])
  3692. self.app_cursor.enabled = False
  3693. try:
  3694. # App.log.debug('button=%d, x=%d, y=%d, xdata=%f, ydata=%f' % (
  3695. # event.button, event.pos[0], event.pos[1], self.pos[0], self.pos[1]))
  3696. modifiers = QtWidgets.QApplication.keyboardModifiers()
  3697. if event.button == 1:
  3698. # Reset here the relative coordinates so there is a new reference on the click position
  3699. if self.rel_point1 is None:
  3700. self.rel_point1 = self.pos
  3701. else:
  3702. self.rel_point2 = copy(self.rel_point1)
  3703. self.rel_point1 = self.pos
  3704. # If the SHIFT key is pressed when LMB is clicked then the coordinates are copied to clipboard
  3705. if modifiers == QtCore.Qt.ShiftModifier:
  3706. self.clipboard.setText(self.defaults["global_point_clipboard_format"] % (self.pos[0], self.pos[1]))
  3707. return
  3708. # If the CTRL key is pressed when the LMB is clicked then if the object is selected it will deselect,
  3709. # and if it's not selected then it will be selected
  3710. if modifiers == QtCore.Qt.ControlModifier:
  3711. # If there is no active command (self.command_active is None) then we check if we clicked on
  3712. # a object by checking the bounding limits against mouse click position
  3713. if self.command_active is None:
  3714. self.select_objects(key='CTRL')
  3715. else:
  3716. # If there is no active command (self.command_active is None) then we check if we clicked on a object by
  3717. # checking the bounding limits against mouse click position
  3718. if self.command_active is None:
  3719. self.select_objects()
  3720. self.on_mouse_move_over_plot(event, origin_click=True)
  3721. except Exception as e:
  3722. App.log.debug("App.on_mouse_click_over_plot() --> Outside plot? --> %s" % str(e))
  3723. def on_double_click_over_plot(self, event):
  3724. # make double click work only for the LMB
  3725. if event.button == 1:
  3726. if self.collection.get_selected():
  3727. self.ui.notebook.setCurrentWidget(self.ui.selected_tab)
  3728. # delete the selection shape(S) as it may be in the way
  3729. self.delete_selection_shape()
  3730. def on_mouse_move_over_plot(self, event, origin_click=None):
  3731. """
  3732. Callback for the mouse motion event over the plot. This event is generated
  3733. by the Matplotlib backend and has been registered in ``self.__init__()``.
  3734. For details, see: http://matplotlib.org/users/event_handling.html
  3735. :param event: Contains information about the event.
  3736. :param origin_click
  3737. :return: None
  3738. """
  3739. # So it can receive key presses
  3740. self.plotcanvas.vispy_canvas.native.setFocus()
  3741. self.pos_jump = event.pos
  3742. if origin_click is True:
  3743. pass
  3744. else:
  3745. # if the RMB is clicked and mouse is moving over plot then 'panning_action' is True
  3746. if event.button == 2:
  3747. self.panning_action = True
  3748. return
  3749. else:
  3750. self.panning_action = False
  3751. if self.rel_point1 is not None:
  3752. try: # May fail in case mouse not within axes
  3753. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3754. if self.grid_status():
  3755. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3756. self.app_cursor.enabled = True
  3757. # Update cursor
  3758. self.app_cursor.set_data(np.asarray([(pos[0], pos[1])]), symbol='++', edge_color='black', size=20)
  3759. else:
  3760. pos = (pos_canvas[0], pos_canvas[1])
  3761. self.app_cursor.enabled = False
  3762. self.ui.position_label.setText("&nbsp;&nbsp;&nbsp;&nbsp;<b>X</b>: %.4f&nbsp;&nbsp; "
  3763. "<b>Y</b>: %.4f" % (pos[0], pos[1]))
  3764. dx = pos[0] - self.rel_point1[0]
  3765. dy = pos[1] - self.rel_point1[1]
  3766. self.ui.rel_position_label.setText("<b>Dx</b>: %.4f&nbsp;&nbsp; <b>Dy</b>: "
  3767. "%.4f&nbsp;&nbsp;&nbsp;&nbsp;" % (dx, dy))
  3768. self.mouse = [pos[0], pos[1]]
  3769. # if the mouse is moved and the LMB is clicked then the action is a selection
  3770. if event.is_dragging == 1 and event.button == 1:
  3771. self.delete_selection_shape()
  3772. if dx < 0:
  3773. self.draw_moving_selection_shape(self.pos, pos, color=self.defaults['global_alt_sel_line'],
  3774. face_color=self.defaults['global_alt_sel_fill'])
  3775. self.selection_type = False
  3776. else:
  3777. self.draw_moving_selection_shape(self.pos, pos)
  3778. self.selection_type = True
  3779. # delete the status message on mouse move
  3780. # self.inform.emit("")
  3781. except:
  3782. self.ui.position_label.setText("")
  3783. self.ui.rel_position_label.setText("")
  3784. self.mouse = None
  3785. def on_mouse_click_release_over_plot(self, event):
  3786. """
  3787. Callback for the mouse click release over plot. This event is generated by the Matplotlib backend
  3788. and has been registered in ''self.__init__()''.
  3789. :param event: contains information about the event.
  3790. :return:
  3791. """
  3792. pos_canvas = self.plotcanvas.vispy_canvas.translate_coords(event.pos)
  3793. if self.grid_status():
  3794. pos = self.geo_editor.snap(pos_canvas[0], pos_canvas[1])
  3795. else:
  3796. pos = (pos_canvas[0], pos_canvas[1])
  3797. # if the released mouse button was RMB then test if it was a panning motion or not, if not it was a context
  3798. # canvas menu
  3799. try:
  3800. if event.button == 2: # right click
  3801. if self.panning_action is True:
  3802. self.panning_action = False
  3803. else:
  3804. self.cursor = QtGui.QCursor()
  3805. self.populate_cmenu_grids()
  3806. self.ui.popMenu.popup(self.cursor.pos())
  3807. except Exception as e:
  3808. log.warning("Error: %s" % str(e))
  3809. return
  3810. # if the released mouse button was LMB then test if we had a right-to-left selection or a left-to-right
  3811. # selection and then select a type of selection ("enclosing" or "touching")
  3812. try:
  3813. if event.button == 1: # left click
  3814. if self.selection_type is not None:
  3815. self.selection_area_handler(self.pos, pos, self.selection_type)
  3816. self.selection_type = None
  3817. except Exception as e:
  3818. log.warning("Error: %s" % str(e))
  3819. return
  3820. def selection_area_handler(self, start_pos, end_pos, sel_type):
  3821. """
  3822. :param start_pos: mouse position when the selection LMB click was done
  3823. :param end_pos: mouse position when the left mouse button is released
  3824. :param sel_type: if True it's a left to right selection (enclosure), if False it's a 'touch' selection
  3825. :return:
  3826. """
  3827. poly_selection = Polygon([start_pos, (end_pos[0], start_pos[1]), end_pos, (start_pos[0], end_pos[1])])
  3828. self.delete_selection_shape()
  3829. for obj in self.collection.get_list():
  3830. try:
  3831. # select the object(s) only if it is enabled (plotted)
  3832. if obj.options['plot']:
  3833. poly_obj = Polygon([(obj.options['xmin'], obj.options['ymin']), (obj.options['xmax'], obj.options['ymin']),
  3834. (obj.options['xmax'], obj.options['ymax']), (obj.options['xmin'], obj.options['ymax'])])
  3835. if sel_type is True:
  3836. if poly_obj.within(poly_selection):
  3837. # create the selection box around the selected object
  3838. self.draw_selection_shape(obj)
  3839. self.collection.set_active(obj.options['name'])
  3840. else:
  3841. if poly_selection.intersects(poly_obj):
  3842. # create the selection box around the selected object
  3843. self.draw_selection_shape(obj)
  3844. self.collection.set_active(obj.options['name'])
  3845. except:
  3846. # the Exception here will happen if we try to select on screen and we have an newly (and empty)
  3847. # just created Geometry or Excellon object that do not have the xmin, xmax, ymin, ymax options.
  3848. # In this case poly_obj creation (see above) will fail
  3849. pass
  3850. def select_objects(self, key=None):
  3851. # list where we store the overlapped objects under our mouse left click position
  3852. objects_under_the_click_list = []
  3853. # Populate the list with the overlapped objects on the click position
  3854. curr_x, curr_y = self.pos
  3855. for obj in self.all_objects_list:
  3856. if (curr_x >= obj.options['xmin']) and (curr_x <= obj.options['xmax']) and \
  3857. (curr_y >= obj.options['ymin']) and (curr_y <= obj.options['ymax']):
  3858. if obj.options['name'] not in objects_under_the_click_list:
  3859. if obj.options['plot']:
  3860. # add objects to the objects_under_the_click list only if the object is plotted
  3861. # (active and not disabled)
  3862. objects_under_the_click_list.append(obj.options['name'])
  3863. try:
  3864. # If there is no element in the overlapped objects list then make everyone inactive
  3865. # because we selected "nothing"
  3866. if not objects_under_the_click_list:
  3867. self.collection.set_all_inactive()
  3868. # delete the possible selection box around a possible selected object
  3869. self.delete_selection_shape()
  3870. # and as a convenience move the focus to the Project tab because Selected tab is now empty
  3871. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  3872. # delete any text in the status bar, implicitly the last object name that was selected
  3873. self.inform.emit("")
  3874. else:
  3875. # case when there is only an object under the click and we toggle it
  3876. if len(objects_under_the_click_list) == 1:
  3877. if self.collection.get_active() is None :
  3878. self.collection.set_active(objects_under_the_click_list[0])
  3879. # create the selection box around the selected object
  3880. curr_sel_obj = self.collection.get_active()
  3881. self.draw_selection_shape(curr_sel_obj)
  3882. # self.inform.emit('[selected] %s: %s selected' %
  3883. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  3884. if curr_sel_obj.kind == 'gerber':
  3885. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3886. ('green', str(curr_sel_obj.options['name'])))
  3887. elif curr_sel_obj.kind == 'excellon':
  3888. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3889. ('brown', str(curr_sel_obj.options['name'])))
  3890. elif curr_sel_obj.kind == 'cncjob':
  3891. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3892. ('blue', str(curr_sel_obj.options['name'])))
  3893. elif curr_sel_obj.kind == 'geometry':
  3894. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3895. ('red', str(curr_sel_obj.options['name'])))
  3896. elif self.collection.get_active().options['name'] not in objects_under_the_click_list:
  3897. self.collection.set_all_inactive()
  3898. self.delete_selection_shape()
  3899. self.collection.set_active(objects_under_the_click_list[0])
  3900. # create the selection box around the selected object
  3901. curr_sel_obj = self.collection.get_active()
  3902. self.draw_selection_shape(curr_sel_obj)
  3903. # self.inform.emit('[selected] %s: %s selected' %
  3904. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  3905. if curr_sel_obj.kind == 'gerber':
  3906. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3907. ('green', str(curr_sel_obj.options['name'])))
  3908. elif curr_sel_obj.kind == 'excellon':
  3909. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3910. ('brown', str(curr_sel_obj.options['name'])))
  3911. elif curr_sel_obj.kind == 'cncjob':
  3912. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3913. ('blue', str(curr_sel_obj.options['name'])))
  3914. elif curr_sel_obj.kind == 'geometry':
  3915. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3916. ('red', str(curr_sel_obj.options['name'])))
  3917. else:
  3918. self.collection.set_all_inactive()
  3919. self.delete_selection_shape()
  3920. self.inform.emit("")
  3921. else:
  3922. # If there is no selected object
  3923. # make active the first element of the overlapped objects list
  3924. if self.collection.get_active() is None:
  3925. self.collection.set_active(objects_under_the_click_list[0])
  3926. name_sel_obj = self.collection.get_active().options['name']
  3927. # In case that there is a selected object but it is not in the overlapped object list
  3928. # make that object inactive and activate the first element in the overlapped object list
  3929. if name_sel_obj not in objects_under_the_click_list:
  3930. self.collection.set_inactive(name_sel_obj)
  3931. name_sel_obj = objects_under_the_click_list[0]
  3932. self.collection.set_active(name_sel_obj)
  3933. else:
  3934. name_sel_obj_idx = objects_under_the_click_list.index(name_sel_obj)
  3935. self.collection.set_all_inactive()
  3936. self.collection.set_active(objects_under_the_click_list[(name_sel_obj_idx + 1) %
  3937. len(objects_under_the_click_list)])
  3938. curr_sel_obj = self.collection.get_active()
  3939. # delete the possible selection box around a possible selected object
  3940. self.delete_selection_shape()
  3941. # create the selection box around the selected object
  3942. self.draw_selection_shape(curr_sel_obj)
  3943. # self.inform.emit('[selected] %s: %s selected' %
  3944. # (str(curr_sel_obj.kind).capitalize(), str(curr_sel_obj.options['name'])))
  3945. if curr_sel_obj.kind == 'gerber':
  3946. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3947. ('green', str(curr_sel_obj.options['name'])))
  3948. elif curr_sel_obj.kind == 'excellon':
  3949. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3950. ('brown', str(curr_sel_obj.options['name'])))
  3951. elif curr_sel_obj.kind == 'cncjob':
  3952. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3953. ('blue', str(curr_sel_obj.options['name'])))
  3954. elif curr_sel_obj.kind == 'geometry':
  3955. self.inform.emit('[selected]<span style="color:%s;">%s</span> selected' %
  3956. ('red', str(curr_sel_obj.options['name'])))
  3957. # for obj in self.collection.get_list():
  3958. # obj.plot()
  3959. # curr_sel_obj.plot(color=self.FC_dark_blue, face_color=self.FC_light_blue)
  3960. # TODO: on selected objects change the object colors and do not draw the selection box
  3961. # self.plotcanvas.vispy_canvas.update() # this updates the canvas
  3962. except Exception as e:
  3963. log.error("[ERROR] Something went bad. %s" % str(e))
  3964. return
  3965. def delete_selection_shape(self):
  3966. self.move_tool.sel_shapes.clear()
  3967. self.move_tool.sel_shapes.redraw()
  3968. def draw_selection_shape(self, sel_obj):
  3969. """
  3970. :param sel_obj: the object for which the selection shape must be drawn
  3971. :return:
  3972. """
  3973. pt1 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymin']))
  3974. pt2 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymin']))
  3975. pt3 = (float(sel_obj.options['xmax']), float(sel_obj.options['ymax']))
  3976. pt4 = (float(sel_obj.options['xmin']), float(sel_obj.options['ymax']))
  3977. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  3978. #blue_t = Color('blue')
  3979. blue_t = Color(self.defaults['global_sel_fill'])
  3980. blue_t.alpha = 0.3
  3981. self.sel_objects_list.append(self.move_tool.sel_shapes.add(sel_rect, color=self.defaults['global_sel_line'],
  3982. face_color=blue_t, update=True, layer=0, tolerance=None))
  3983. def draw_moving_selection_shape(self, old_coords, coords, **kwargs):
  3984. """
  3985. :param old_coords: old coordinates
  3986. :param coords: new coordinates
  3987. :return:
  3988. """
  3989. if 'color' in kwargs:
  3990. color = kwargs['color']
  3991. else:
  3992. color = self.defaults['global_sel_line']
  3993. if 'face_color' in kwargs:
  3994. face_color = kwargs['face_color']
  3995. else:
  3996. face_color = self.defaults['global_sel_fill']
  3997. x0, y0 = old_coords
  3998. x1, y1 = coords
  3999. pt1 = (x0, y0)
  4000. pt2 = (x1, y0)
  4001. pt3 = (x1, y1)
  4002. pt4 = (x0, y1)
  4003. sel_rect = Polygon([pt1, pt2, pt3, pt4])
  4004. color_t = Color(face_color)
  4005. color_t.alpha = 0.3
  4006. self.move_tool.sel_shapes.add(sel_rect, color=color, face_color=color_t, update=True,
  4007. layer=0, tolerance=None)
  4008. def on_file_new_click(self):
  4009. if self.collection.get_list() and self.should_we_save:
  4010. msgbox = QtWidgets.QMessageBox()
  4011. # msgbox.setText("<B>Save changes ...</B>")
  4012. msgbox.setText("There are files/objects opened in FlatCAM.\n"
  4013. "Creating a New project will delete them.\n"
  4014. "Do you want to Save the project?")
  4015. msgbox.setWindowTitle("Save changes")
  4016. msgbox.setWindowIcon(QtGui.QIcon('share/save_as.png'))
  4017. msgbox.setStandardButtons(QtWidgets.QMessageBox.Cancel | QtWidgets.QMessageBox.Yes |
  4018. QtWidgets.QMessageBox.No)
  4019. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4020. response = msgbox.exec_()
  4021. if response == QtWidgets.QMessageBox.Yes:
  4022. self.on_file_saveprojectas()
  4023. elif response == QtWidgets.QMessageBox.Cancel:
  4024. return
  4025. self.on_file_new()
  4026. else:
  4027. self.on_file_new()
  4028. self.inform.emit("[success] New Project created...")
  4029. def on_file_new(self):
  4030. """
  4031. Callback for menu item File->New. Returns the application to its
  4032. startup state. This method is thread-safe.
  4033. :return: None
  4034. """
  4035. self.report_usage("on_file_new")
  4036. # Remove everything from memory
  4037. App.log.debug("on_file_new()")
  4038. # Clear pool
  4039. self.clear_pool()
  4040. # tcl needs to be reinitialized, otherwise old shell variables etc remains
  4041. self.init_tcl()
  4042. self.delete_selection_shape()
  4043. self.collection.delete_all()
  4044. self.setup_component_editor()
  4045. # Clear project filename
  4046. self.project_filename = None
  4047. # Load the application defaults
  4048. self.load_defaults(filename='current_defaults')
  4049. # Re-fresh project options
  4050. self.on_options_app2project()
  4051. # Init Tools
  4052. self.init_tools()
  4053. # Close any Tabs opened in the Plot Tab Area section
  4054. for index in range(self.ui.plot_tab_area.count()):
  4055. self.ui.plot_tab_area.closeTab(index)
  4056. # for whatever reason previous command does not close the last tab so I do it manually
  4057. self.ui.plot_tab_area.closeTab(0)
  4058. # # And then add again the Plot Area
  4059. self.ui.plot_tab_area.addTab(self.ui.plot_tab, "Plot Area")
  4060. self.ui.plot_tab_area.protectTab(0)
  4061. # take the focus of the Notebook on Project Tab.
  4062. self.ui.notebook.setCurrentWidget(self.ui.project_tab)
  4063. def obj_properties(self):
  4064. self.report_usage("obj_properties()")
  4065. self.properties_tool.run()
  4066. def on_project_context_save(self):
  4067. obj = self.collection.get_active()
  4068. if type(obj) == FlatCAMGeometry:
  4069. self.on_file_exportdxf()
  4070. elif type(obj) == FlatCAMExcellon:
  4071. self.on_file_exportexcellon()
  4072. elif type(obj) == FlatCAMCNCjob:
  4073. obj.on_exportgcode_button_click()
  4074. elif type(obj) == FlatCAMGerber:
  4075. self.on_file_exportgerber()
  4076. def on_view_source(self):
  4077. try:
  4078. obj = self.collection.get_active()
  4079. except:
  4080. self.inform.emit("[WARNING_NOTCL] Select an Gerber or Excellon file to view it's source.")
  4081. # add the tab if it was closed
  4082. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, "Code Editor")
  4083. # first clear previous text in text editor (if any)
  4084. self.ui.code_editor.clear()
  4085. # Switch plot_area to CNCJob tab
  4086. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  4087. # then append the text from GCode to the text editor
  4088. file = StringIO(obj.source_file)
  4089. try:
  4090. for line in file:
  4091. proc_line = str(line).strip('\n')
  4092. self.ui.code_editor.append(proc_line)
  4093. except Exception as e:
  4094. log.debug('App.on_view_source() -->%s' % str(e))
  4095. self.inform.emit('[ERROR]App.on_view_source() -->%s' % str(e))
  4096. return
  4097. self.ui.code_editor.moveCursor(QtGui.QTextCursor.Start)
  4098. self.handleTextChanged()
  4099. self.ui.show()
  4100. # if type(obj) == FlatCAMGerber:
  4101. # self.on_file_exportdxf()
  4102. # elif type(obj) == FlatCAMExcellon:
  4103. # self.on_file_exportexcellon()
  4104. def obj_move(self):
  4105. self.report_usage("obj_move()")
  4106. self.move_tool.run()
  4107. def on_fileopengerber(self):
  4108. """
  4109. File menu callback for opening a Gerber.
  4110. :return: None
  4111. """
  4112. self.report_usage("on_fileopengerber")
  4113. App.log.debug("on_fileopengerber()")
  4114. _filter_ = "Gerber Files (*.gbr *.ger *.gtl *.gbl *.gts *.gbs *.gtp *.gbp *.gto *.gbo *.gm1 *.gml *.gm3 *.gko " \
  4115. "*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil *.grb" \
  4116. "*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb *.pho *.gdo *.art *.gbd);;" \
  4117. "Protel Files (*.gtl *.gbl *.gts *.gbs *.gto *.gbo *.gtp *.gbp *.gml *.gm1 *.gm3 *.gko);;" \
  4118. "Eagle Files (*.cmp *.sol *.stc *.sts *.plc *.pls *.crc *.crs *.tsm *.bsm *.ly2 *.ly15 *.dim *.mil);;" \
  4119. "OrCAD Files (*.top *.bot *.smt *.smb *.sst *.ssb *.spt *.spb);;" \
  4120. "Allegro Files (*.art);;" \
  4121. "Mentor Files (*.pho *.gdo);;" \
  4122. "All Files (*.*)"
  4123. try:
  4124. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open Gerber",
  4125. directory=self.get_last_folder(), filter=_filter_)
  4126. except TypeError:
  4127. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open Gerber", filter=_filter_)
  4128. filenames = [str(filename) for filename in filenames]
  4129. if len(filenames) == 0:
  4130. self.inform.emit("[WARNING_NOTCL]Open Gerber cancelled.")
  4131. else:
  4132. for filename in filenames:
  4133. if filename != '':
  4134. self.worker_task.emit({'fcn': self.open_gerber,
  4135. 'params': [filename]})
  4136. def on_fileopenexcellon(self):
  4137. """
  4138. File menu callback for opening an Excellon file.
  4139. :return: None
  4140. """
  4141. self.report_usage("on_fileopenexcellon")
  4142. App.log.debug("on_fileopenexcellon()")
  4143. _filter_ = "Excellon Files (*.drl *.txt *.xln *.drd *.tap *.exc);;" \
  4144. "All Files (*.*)"
  4145. try:
  4146. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open Excellon",
  4147. directory=self.get_last_folder(), filter=_filter_)
  4148. except TypeError:
  4149. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open Excellon", filter=_filter_)
  4150. filenames = [str(filename) for filename in filenames]
  4151. if len(filenames) == 0:
  4152. self.inform.emit("[WARNING_NOTCL]Open Excellon cancelled.")
  4153. else:
  4154. for filename in filenames:
  4155. if filename != '':
  4156. self.worker_task.emit({'fcn': self.open_excellon,
  4157. 'params': [filename]})
  4158. def on_fileopengcode(self):
  4159. """
  4160. File menu call back for opening gcode.
  4161. :return: None
  4162. """
  4163. self.report_usage("on_fileopengcode")
  4164. App.log.debug("on_fileopengcode()")
  4165. # https://bobcadsupport.com/helpdesk/index.php?/Knowledgebase/Article/View/13/5/known-g-code-file-extensions
  4166. _filter_ = "G-Code Files (*.txt *.nc *.ncc *.tap *.gcode *.cnc *.ecs *.fnc *.dnc *.ncg *.gc *.fan *.fgc" \
  4167. " *.din *.xpi *.hnc *.h *.i *.ncp *.min *.gcd *.rol *.mpr *.ply *.out *.eia *.plt *.sbp *.mpf);;" \
  4168. "All Files (*.*)"
  4169. try:
  4170. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open G-Code",
  4171. directory=self.get_last_folder(), filter=_filter_)
  4172. except TypeError:
  4173. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Open G-Code", filter=_filter_)
  4174. filenames = [str(filename) for filename in filenames]
  4175. if len(filenames) == 0:
  4176. self.inform.emit("[WARNING_NOTCL]Open G-Code cancelled.")
  4177. else:
  4178. for filename in filenames:
  4179. if filename != '':
  4180. self.worker_task.emit({'fcn': self.open_gcode,
  4181. 'params': [filename]})
  4182. def on_file_openproject(self):
  4183. """
  4184. File menu callback for opening a project.
  4185. :return: None
  4186. """
  4187. self.report_usage("on_file_openproject")
  4188. App.log.debug("on_file_openproject()")
  4189. _filter_ = "FlatCAM Project (*.FlatPrj);;All Files (*.*)"
  4190. try:
  4191. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Project",
  4192. directory=self.get_last_folder(), filter=_filter_)
  4193. except TypeError:
  4194. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Project", filter = _filter_)
  4195. # The Qt methods above will return a QString which can cause problems later.
  4196. # So far json.dump() will fail to serialize it.
  4197. # TODO: Improve the serialization methods and remove this fix.
  4198. filename = str(filename)
  4199. if filename == "":
  4200. self.inform.emit("[WARNING_NOTCL]Open Project cancelled.")
  4201. else:
  4202. # self.worker_task.emit({'fcn': self.open_project,
  4203. # 'params': [filename]})
  4204. # The above was failing because open_project() is not
  4205. # thread safe. The new_project()
  4206. self.open_project(filename)
  4207. def on_file_openconfig(self):
  4208. """
  4209. File menu callback for opening a config file.
  4210. :return: None
  4211. """
  4212. self.report_usage("on_file_openconfig")
  4213. App.log.debug("on_file_openconfig()")
  4214. _filter_ = "FlatCAM Config (*.FlatConfig);;FlatCAM Config (*.json);;All Files (*.*)"
  4215. try:
  4216. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Configuration File",
  4217. directory=self.data_path, filter=_filter_)
  4218. except TypeError:
  4219. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open Configuration File", filter = _filter_)
  4220. if filename == "":
  4221. self.inform.emit("[WARNING_NOTCL]Open COnfig cancelled.")
  4222. else:
  4223. self.open_config_file(filename)
  4224. def on_file_exportsvg(self):
  4225. """
  4226. Callback for menu item File->Export SVG.
  4227. :return: None
  4228. """
  4229. self.report_usage("on_file_exportsvg")
  4230. App.log.debug("on_file_exportsvg()")
  4231. obj = self.collection.get_active()
  4232. if obj is None:
  4233. self.inform.emit("WARNING: No object selected.")
  4234. msg = "Please Select a Geometry object to export"
  4235. msgbox = QtWidgets.QMessageBox()
  4236. msgbox.setInformativeText(msg)
  4237. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  4238. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4239. msgbox.exec_()
  4240. return
  4241. # Check for more compatible types and add as required
  4242. if (not isinstance(obj, FlatCAMGeometry) and not isinstance(obj, FlatCAMGerber) and not isinstance(obj, FlatCAMCNCjob)
  4243. and not isinstance(obj, FlatCAMExcellon)):
  4244. msg = "[ERROR_NOTCL] Only Geometry, Gerber and CNCJob objects can be used."
  4245. msgbox = QtWidgets.QMessageBox()
  4246. msgbox.setInformativeText(msg)
  4247. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  4248. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4249. msgbox.exec_()
  4250. return
  4251. name = self.collection.get_active().options["name"]
  4252. filter = "SVG File (*.svg);;All Files (*.*)"
  4253. try:
  4254. filename, _ = QtWidgets.QFileDialog.getSaveFileName(
  4255. caption="Export SVG",
  4256. directory=self.get_last_save_folder() + '/' + str(name),
  4257. filter=filter)
  4258. except TypeError:
  4259. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export SVG", filter=filter)
  4260. filename = str(filename)
  4261. if filename == "":
  4262. self.inform.emit("[WARNING_NOTCL]Export SVG cancelled.")
  4263. return
  4264. else:
  4265. self.export_svg(name, filename)
  4266. self.file_saved.emit("SVG", filename)
  4267. def on_file_exportpng(self):
  4268. self.report_usage("on_file_exportpng")
  4269. App.log.debug("on_file_exportpng()")
  4270. image = _screenshot()
  4271. data = np.asarray(image)
  4272. if not data.ndim == 3 and data.shape[-1] in (3, 4):
  4273. self.inform.emit('[[WARNING_NOTCL]] Data must be a 3D array with last dimension 3 or 4')
  4274. return
  4275. filter_ = "PNG File (*.png);;All Files (*.*)"
  4276. try:
  4277. filename, _ = QtWidgets.QFileDialog.getSaveFileName(
  4278. caption="Export PNG Image",
  4279. directory=self.get_last_save_folder() + '/png_' + str(self.date).replace('-', ''),
  4280. filter=filter_)
  4281. except TypeError:
  4282. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export PNG Image", filter=filter_)
  4283. filename = str(filename)
  4284. if filename == "":
  4285. self.inform.emit("Export PNG cancelled.")
  4286. return
  4287. else:
  4288. write_png(filename, data)
  4289. self.file_saved.emit("png", filename)
  4290. def on_file_exportgerber(self):
  4291. """
  4292. Callback for menu item File->Export SVG.
  4293. :return: None
  4294. """
  4295. self.report_usage("on_file_exportgerber")
  4296. App.log.debug("on_file_exportgerber()")
  4297. obj = self.collection.get_active()
  4298. if obj is None:
  4299. self.inform.emit("[WARNING_NOTCL] No object selected. Please Select an Gerber object to export.")
  4300. return
  4301. # Check for more compatible types and add as required
  4302. if not isinstance(obj, FlatCAMGerber):
  4303. self.inform.emit("[ERROR_NOTCL] Failed. Only Gerber objects can be saved as Gerber files...")
  4304. return
  4305. name = self.collection.get_active().options["name"]
  4306. filter = "Gerber File (*.GBR);;Gerber File (*.GRB);;All Files (*.*)"
  4307. try:
  4308. filename, _ = QtWidgets.QFileDialog.getSaveFileName(
  4309. caption="Export Gerber",
  4310. directory=self.get_last_save_folder() + '/' + name,
  4311. filter=filter)
  4312. except TypeError:
  4313. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export Gerber", filter=filter)
  4314. filename = str(filename)
  4315. if filename == "":
  4316. self.inform.emit("[WARNING_NOTCL]Export Gerber cancelled.")
  4317. return
  4318. else:
  4319. self.export_gerber(name, filename)
  4320. self.file_saved.emit("Gerber", filename)
  4321. def on_file_exportexcellon(self):
  4322. """
  4323. Callback for menu item File->Export SVG.
  4324. :return: None
  4325. """
  4326. self.report_usage("on_file_exportexcellon")
  4327. App.log.debug("on_file_exportexcellon()")
  4328. obj = self.collection.get_active()
  4329. if obj is None:
  4330. self.inform.emit("[WARNING_NOTCL] No object selected. Please Select an Excellon object to export.")
  4331. return
  4332. # Check for more compatible types and add as required
  4333. if not isinstance(obj, FlatCAMExcellon):
  4334. self.inform.emit("[ERROR_NOTCL] Failed. Only Excellon objects can be saved as Excellon files...")
  4335. return
  4336. name = self.collection.get_active().options["name"]
  4337. filter = "Excellon File (*.DRL);;Excellon File (*.TXT);;All Files (*.*)"
  4338. try:
  4339. filename, _ = QtWidgets.QFileDialog.getSaveFileName(
  4340. caption="Export Excellon",
  4341. directory=self.get_last_save_folder() + '/' + name,
  4342. filter=filter)
  4343. except TypeError:
  4344. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export Excellon", filter=filter)
  4345. filename = str(filename)
  4346. if filename == "":
  4347. self.inform.emit("[WARNING_NOTCL]Export Excellon cancelled.")
  4348. return
  4349. else:
  4350. self.export_excellon(name, filename)
  4351. self.file_saved.emit("Excellon", filename)
  4352. def on_file_exportdxf(self):
  4353. """
  4354. Callback for menu item File->Export DXF.
  4355. :return: None
  4356. """
  4357. self.report_usage("on_file_exportdxf")
  4358. App.log.debug("on_file_exportdxf()")
  4359. obj = self.collection.get_active()
  4360. if obj is None:
  4361. self.inform.emit("W[WARNING_NOTCL] No object selected.")
  4362. msg = "Please Select a Geometry object to export"
  4363. msgbox = QtWidgets.QMessageBox()
  4364. msgbox.setInformativeText(msg)
  4365. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  4366. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4367. msgbox.exec_()
  4368. return
  4369. # Check for more compatible types and add as required
  4370. if not isinstance(obj, FlatCAMGeometry):
  4371. msg = "[ERROR_NOTCL] Only Geometry objects can be used."
  4372. msgbox = QtWidgets.QMessageBox()
  4373. msgbox.setInformativeText(msg)
  4374. msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok)
  4375. msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok)
  4376. msgbox.exec_()
  4377. return
  4378. name = self.collection.get_active().options["name"]
  4379. filter = "DXF File (*.DXF);;All Files (*.*)"
  4380. try:
  4381. filename, _ = QtWidgets.QFileDialog.getSaveFileName(
  4382. caption="Export DXF",
  4383. directory=self.get_last_save_folder() + '/' + name,
  4384. filter=filter)
  4385. except TypeError:
  4386. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Export DXF", filter=filter)
  4387. filename = str(filename)
  4388. if filename == "":
  4389. self.inform.emit("[WARNING_NOTCL]Export DXF cancelled.")
  4390. return
  4391. else:
  4392. self.export_dxf(name, filename)
  4393. self.file_saved.emit("DXF", filename)
  4394. def on_file_importsvg(self, type_of_obj):
  4395. """
  4396. Callback for menu item File->Import SVG.
  4397. :param type_of_obj: to import the SVG as Geometry or as Gerber
  4398. :type type_of_obj: str
  4399. :return: None
  4400. """
  4401. self.report_usage("on_file_importsvg")
  4402. App.log.debug("on_file_importsvg()")
  4403. filter = "SVG File (*.svg);;All Files (*.*)"
  4404. try:
  4405. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Import SVG",
  4406. directory=self.get_last_folder(), filter=filter)
  4407. except TypeError:
  4408. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Import SVG", filter=filter)
  4409. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  4410. type_of_obj = "geometry"
  4411. filenames = [str(filename) for filename in filenames]
  4412. if len(filenames) == 0:
  4413. self.inform.emit("[WARNING_NOTCL]Open SVG cancelled.")
  4414. else:
  4415. for filename in filenames:
  4416. if filename != '':
  4417. self.worker_task.emit({'fcn': self.import_svg,
  4418. 'params': [filename, type_of_obj]})
  4419. def on_file_importdxf(self, type_of_obj):
  4420. """
  4421. Callback for menu item File->Import DXF.
  4422. :param type_of_obj: to import the DXF as Geometry or as Gerber
  4423. :type type_of_obj: str
  4424. :return: None
  4425. """
  4426. self.report_usage("on_file_importdxf")
  4427. App.log.debug("on_file_importdxf()")
  4428. filter = "DXF File (*.DXF);;All Files (*.*)"
  4429. try:
  4430. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Import DXF",
  4431. directory=self.get_last_folder(), filter=filter)
  4432. except TypeError:
  4433. filenames, _ = QtWidgets.QFileDialog.getOpenFileNames(caption="Import DXF", filter=filter)
  4434. if type_of_obj is not "geometry" and type_of_obj is not "gerber":
  4435. type_of_obj = "geometry"
  4436. filenames = [str(filename) for filename in filenames]
  4437. if len(filenames) == 0:
  4438. self.inform.emit("[WARNING_NOTCL]Open DXF cancelled.")
  4439. else:
  4440. for filename in filenames:
  4441. if filename != '':
  4442. self.worker_task.emit({'fcn': self.import_dxf,
  4443. 'params': [filename, type_of_obj]})
  4444. def on_filerunscript(self):
  4445. """
  4446. File menu callback for loading and running a TCL script.
  4447. :return: None
  4448. """
  4449. self.report_usage("on_filerunscript")
  4450. App.log.debug("on_file_runscript()")
  4451. _filter_ = "TCL script (*.TCL);;TCL script (*.TXT);;All Files (*.*)"
  4452. try:
  4453. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open TCL script",
  4454. directory=self.get_last_folder(), filter=_filter_)
  4455. except TypeError:
  4456. filename, _ = QtWidgets.QFileDialog.getOpenFileName(caption="Open TCL script", filter=_filter_)
  4457. # The Qt methods above will return a QString which can cause problems later.
  4458. # So far json.dump() will fail to serialize it.
  4459. # TODO: Improve the serialization methods and remove this fix.
  4460. filename = str(filename)
  4461. if filename == "":
  4462. self.inform.emit("[WARNING_NOTCL]Open TCL script cancelled.")
  4463. else:
  4464. try:
  4465. with open(filename, "r") as tcl_script:
  4466. cmd_line_shellfile_content = tcl_script.read()
  4467. self.shell._sysShell.exec_command(cmd_line_shellfile_content)
  4468. except Exception as ext:
  4469. print("ERROR: ", ext)
  4470. sys.exit(2)
  4471. def on_file_saveproject(self):
  4472. """
  4473. Callback for menu item File->Save Project. Saves the project to
  4474. ``self.project_filename`` or calls ``self.on_file_saveprojectas()``
  4475. if set to None. The project is saved by calling ``self.save_project()``.
  4476. :return: None
  4477. """
  4478. self.report_usage("on_file_saveproject")
  4479. if self.project_filename is None:
  4480. self.on_file_saveprojectas()
  4481. else:
  4482. self.worker_task.emit({'fcn': self.save_project,
  4483. 'params': [self.project_filename]})
  4484. # self.save_project(self.project_filename)
  4485. self.file_opened.emit("project", self.project_filename)
  4486. self.file_saved.emit("project", self.project_filename)
  4487. self.should_we_save = False
  4488. def on_file_saveprojectas(self, make_copy=False, thread=True):
  4489. """
  4490. Callback for menu item File->Save Project As... Opens a file
  4491. chooser and saves the project to the given file via
  4492. ``self.save_project()``.
  4493. :return: None
  4494. """
  4495. self.report_usage("on_file_saveprojectas")
  4496. filter_ = "FlatCAM Project (*.FlatPrj);; All Files (*.*)"
  4497. try:
  4498. filename, _ = QtWidgets.QFileDialog.getSaveFileName(
  4499. caption="Save Project As ...",
  4500. directory=self.get_last_save_folder() + '/Project_' + self.date.replace('-', ''),
  4501. filter=filter_)
  4502. except TypeError:
  4503. filename, _ = QtWidgets.QFileDialog.getSaveFileName(caption="Save Project As ...", filter=filter_)
  4504. filename = str(filename)
  4505. if filename == '':
  4506. self.inform.emit("[WARNING_NOTCL]Save Project cancelled.")
  4507. return
  4508. try:
  4509. f = open(filename, 'r')
  4510. f.close()
  4511. exists = True
  4512. except IOError:
  4513. exists = False
  4514. # msg = "Project file exists. Overwrite?"
  4515. # if exists:
  4516. # msgbox = QtWidgets.QMessageBox()
  4517. # msgbox.setInformativeText(msg)
  4518. # msgbox.setStandardButtons(QtWidgets.QMessageBox.Cancel |QtWidgets.QMessageBox.Ok)
  4519. # msgbox.setDefaultButton(QtWidgets.QMessageBox.Cancel)
  4520. # result = msgbox.exec_()
  4521. # if result ==QtWidgets.QMessageBox.Cancel:
  4522. # return
  4523. if thread is True:
  4524. self.worker_task.emit({'fcn': self.save_project,
  4525. 'params': [filename]})
  4526. else:
  4527. self.save_project(filename)
  4528. # self.save_project(filename)
  4529. self.file_opened.emit("project", filename)
  4530. self.file_saved.emit("project", filename)
  4531. if not make_copy:
  4532. self.project_filename = filename
  4533. self.should_we_save = False
  4534. def export_svg(self, obj_name, filename, scale_factor=0.00):
  4535. """
  4536. Exports a Geometry Object to an SVG file.
  4537. :param filename: Path to the SVG file to save to.
  4538. :return:
  4539. """
  4540. self.report_usage("export_svg()")
  4541. if filename is None:
  4542. filename = self.defaults["global_last_save_folder"]
  4543. self.log.debug("export_svg()")
  4544. try:
  4545. obj = self.collection.get_by_name(str(obj_name))
  4546. except:
  4547. # TODO: The return behavior has not been established... should raise exception?
  4548. return "Could not retrieve object: %s" % obj_name
  4549. with self.proc_container.new("Exporting SVG") as proc:
  4550. exported_svg = obj.export_svg(scale_factor=scale_factor)
  4551. # Determine bounding area for svg export
  4552. bounds = obj.bounds()
  4553. size = obj.size()
  4554. # Convert everything to strings for use in the xml doc
  4555. svgwidth = str(size[0])
  4556. svgheight = str(size[1])
  4557. minx = str(bounds[0])
  4558. miny = str(bounds[1] - size[1])
  4559. uom = obj.units.lower()
  4560. # Add a SVG Header and footer to the svg output from shapely
  4561. # The transform flips the Y Axis so that everything renders
  4562. # properly within svg apps such as inkscape
  4563. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  4564. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  4565. svg_header += 'width="' + svgwidth + uom + '" '
  4566. svg_header += 'height="' + svgheight + uom + '" '
  4567. svg_header += 'viewBox="' + minx + ' ' + miny + ' ' + svgwidth + ' ' + svgheight + '">'
  4568. svg_header += '<g transform="scale(1,-1)">'
  4569. svg_footer = '</g> </svg>'
  4570. svg_elem = svg_header + exported_svg + svg_footer
  4571. # Parse the xml through a xml parser just to add line feeds
  4572. # and to make it look more pretty for the output
  4573. svgcode = parse_xml_string(svg_elem)
  4574. with open(filename, 'w') as fp:
  4575. fp.write(svgcode.toprettyxml())
  4576. self.file_saved.emit("SVG", filename)
  4577. self.inform.emit("[success] SVG file exported to " + filename)
  4578. def export_svg_negative(self, obj_name, box_name, filename, boundary, scale_factor=0.00, use_thread=True):
  4579. """
  4580. Exports a Geometry Object to an SVG file in negative.
  4581. :param filename: Path to the SVG file to save to.
  4582. :param: use_thread: If True use threads
  4583. :type: Bool
  4584. :return:
  4585. """
  4586. self.report_usage("export_negative()")
  4587. if filename is None:
  4588. filename = self.defaults["global_last_save_folder"]
  4589. self.log.debug("export_svg() negative")
  4590. try:
  4591. obj = self.collection.get_by_name(str(obj_name))
  4592. except:
  4593. # TODO: The return behavior has not been established... should raise exception?
  4594. return "Could not retrieve object: %s" % obj_name
  4595. try:
  4596. box = self.collection.get_by_name(str(box_name))
  4597. except:
  4598. # TODO: The return behavior has not been established... should raise exception?
  4599. return "Could not retrieve object: %s" % box_name
  4600. if box is None:
  4601. self.inform.emit("[WARNING_NOTCL]No object Box. Using instead %s" % obj)
  4602. box = obj
  4603. def make_negative_film():
  4604. exported_svg = obj.export_svg(scale_factor=scale_factor)
  4605. self.progress.emit(40)
  4606. # Determine bounding area for svg export
  4607. bounds = box.bounds()
  4608. size = box.size()
  4609. uom = obj.units.lower()
  4610. # Convert everything to strings for use in the xml doc
  4611. svgwidth = str(size[0] + (2 * boundary))
  4612. svgheight = str(size[1] + (2 * boundary))
  4613. minx = str(bounds[0] - boundary)
  4614. miny = str(bounds[1] + boundary + size[1])
  4615. miny_rect = str(bounds[1] - boundary)
  4616. # Add a SVG Header and footer to the svg output from shapely
  4617. # The transform flips the Y Axis so that everything renders
  4618. # properly within svg apps such as inkscape
  4619. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  4620. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  4621. svg_header += 'width="' + svgwidth + uom + '" '
  4622. svg_header += 'height="' + svgheight + uom + '" '
  4623. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  4624. svg_header += '>'
  4625. svg_header += '<g transform="scale(1,-1)">'
  4626. svg_footer = '</g> </svg>'
  4627. self.progress.emit(60)
  4628. # Change the attributes of the exported SVG
  4629. # We don't need stroke-width - wrong, we do when we have lines with certain width
  4630. # We set opacity to maximum
  4631. # We set the color to WHITE
  4632. root = ET.fromstring(exported_svg)
  4633. for child in root:
  4634. child.set('fill', '#FFFFFF')
  4635. child.set('opacity', '1.0')
  4636. child.set('stroke', '#FFFFFF')
  4637. # first_svg_elem = 'rect x="' + minx + '" ' + 'y="' + miny_rect + '" '
  4638. # first_svg_elem += 'width="' + svgwidth + '" ' + 'height="' + svgheight + '" '
  4639. # first_svg_elem += 'fill="#000000" opacity="1.0" stroke-width="0.0"'
  4640. first_svg_elem_tag = 'rect'
  4641. first_svg_elem_attribs = {
  4642. 'x': minx,
  4643. 'y': miny_rect,
  4644. 'width': svgwidth,
  4645. 'height': svgheight,
  4646. 'id': 'neg_rect',
  4647. 'style': 'fill:#000000;opacity:1.0;stroke-width:0.0'
  4648. }
  4649. root.insert(0, ET.Element(first_svg_elem_tag, first_svg_elem_attribs))
  4650. exported_svg = ET.tostring(root)
  4651. svg_elem = svg_header + str(exported_svg) + svg_footer
  4652. self.progress.emit(80)
  4653. # Parse the xml through a xml parser just to add line feeds
  4654. # and to make it look more pretty for the output
  4655. doc = parse_xml_string(svg_elem)
  4656. with open(filename, 'w') as fp:
  4657. fp.write(doc.toprettyxml())
  4658. self.progress.emit(100)
  4659. self.file_saved.emit("SVG", filename)
  4660. self.inform.emit("[success] SVG file exported to " + filename)
  4661. if use_thread is True:
  4662. proc = self.proc_container.new("Generating Film ... Please wait.")
  4663. def job_thread_film(app_obj):
  4664. try:
  4665. make_negative_film()
  4666. except Exception as e:
  4667. proc.done()
  4668. return
  4669. proc.done()
  4670. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  4671. else:
  4672. make_negative_film()
  4673. def export_svg_black(self, obj_name, box_name, filename, scale_factor=0.00, use_thread=True):
  4674. """
  4675. Exports a Geometry Object to an SVG file in negative.
  4676. :param filename: Path to the SVG file to save to.
  4677. :param: use_thread: If True use threads
  4678. :type: Bool
  4679. :return:
  4680. """
  4681. self.report_usage("export_svg_black()")
  4682. if filename is None:
  4683. filename = self.defaults["global_last_save_folder"]
  4684. self.log.debug("export_svg() black")
  4685. try:
  4686. obj = self.collection.get_by_name(str(obj_name))
  4687. except:
  4688. # TODO: The return behavior has not been established... should raise exception?
  4689. return "Could not retrieve object: %s" % obj_name
  4690. try:
  4691. box = self.collection.get_by_name(str(box_name))
  4692. except:
  4693. # TODO: The return behavior has not been established... should raise exception?
  4694. return "Could not retrieve object: %s" % box_name
  4695. if box is None:
  4696. self.inform.emit("[WARNING_NOTCL]No object Box. Using instead %s" % obj)
  4697. box = obj
  4698. def make_black_film():
  4699. exported_svg = obj.export_svg(scale_factor=scale_factor)
  4700. self.progress.emit(40)
  4701. # Change the attributes of the exported SVG
  4702. # We don't need stroke-width
  4703. # We set opacity to maximum
  4704. # We set the colour to WHITE
  4705. root = ET.fromstring(exported_svg)
  4706. for child in root:
  4707. child.set('fill', '#000000')
  4708. child.set('opacity', '1.0')
  4709. child.set('stroke', '#000000')
  4710. exported_svg = ET.tostring(root)
  4711. # Determine bounding area for svg export
  4712. bounds = box.bounds()
  4713. size = box.size()
  4714. # This contain the measure units
  4715. uom = obj.units.lower()
  4716. # Define a boundary around SVG of about 1.0mm (~39mils)
  4717. if uom in "mm":
  4718. boundary = 1.0
  4719. else:
  4720. boundary = 0.0393701
  4721. self.progress.emit(80)
  4722. # Convert everything to strings for use in the xml doc
  4723. svgwidth = str(size[0] + (2 * boundary))
  4724. svgheight = str(size[1] + (2 * boundary))
  4725. minx = str(bounds[0] - boundary)
  4726. miny = str(bounds[1] + boundary + size[1])
  4727. self.log.debug(minx)
  4728. self.log.debug(miny)
  4729. # Add a SVG Header and footer to the svg output from shapely
  4730. # The transform flips the Y Axis so that everything renders
  4731. # properly within svg apps such as inkscape
  4732. svg_header = '<svg xmlns="http://www.w3.org/2000/svg" ' \
  4733. 'version="1.1" xmlns:xlink="http://www.w3.org/1999/xlink" '
  4734. svg_header += 'width="' + svgwidth + uom + '" '
  4735. svg_header += 'height="' + svgheight + uom + '" '
  4736. svg_header += 'viewBox="' + minx + ' -' + miny + ' ' + svgwidth + ' ' + svgheight + '" '
  4737. svg_header += '>'
  4738. svg_header += '<g transform="scale(1,-1)">'
  4739. svg_footer = '</g> </svg>'
  4740. svg_elem = str(svg_header) + str(exported_svg) + str(svg_footer)
  4741. self.progress.emit(90)
  4742. # Parse the xml through a xml parser just to add line feeds
  4743. # and to make it look more pretty for the output
  4744. doc = parse_xml_string(svg_elem)
  4745. with open(filename, 'w') as fp:
  4746. fp.write(doc.toprettyxml())
  4747. self.progress.emit(100)
  4748. self.file_saved.emit("SVG", filename)
  4749. self.inform.emit("[success] SVG file exported to " + filename)
  4750. if use_thread is True:
  4751. proc = self.proc_container.new("Generating Film ... Please wait.")
  4752. def job_thread_film(app_obj):
  4753. try:
  4754. make_black_film()
  4755. except Exception as e:
  4756. proc.done()
  4757. return
  4758. proc.done()
  4759. self.worker_task.emit({'fcn': job_thread_film, 'params': [self]})
  4760. else:
  4761. make_black_film()
  4762. def export_gerber(self, obj_name, filename, use_thread=True):
  4763. """
  4764. Exports a Gerber Object to an Gerber file.
  4765. :param filename: Path to the Gerber file to save to.
  4766. :return:
  4767. """
  4768. self.report_usage("export_gerber()")
  4769. if filename is None:
  4770. filename = self.defaults["global_last_save_folder"]
  4771. self.log.debug("export_gerber()")
  4772. obj = self.collection.get_by_name(obj_name)
  4773. file_string = StringIO(obj.source_file)
  4774. time_string = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  4775. with open(filename, 'w') as file:
  4776. file.writelines('G04*\n')
  4777. file.writelines('G04 GERBER (RE)GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s*\n' %
  4778. (str(self.version), str(self.version_date)))
  4779. file.writelines('G04 Filename: %s*\n' % str(obj_name))
  4780. file.writelines('G04 Created on : %s*\n' % time_string)
  4781. for line in file_string:
  4782. file.writelines(line)
  4783. def export_excellon(self, obj_name, filename, use_thread=True):
  4784. """
  4785. Exports a Excellon Object to an Excellon file.
  4786. :param filename: Path to the Excellon file to save to.
  4787. :return:
  4788. """
  4789. self.report_usage("export_excellon()")
  4790. if filename is None:
  4791. filename = self.defaults["global_last_save_folder"]
  4792. self.log.debug("export_excellon()")
  4793. format_exc = ';FILE_FORMAT=%d:%d\n' % (self.defaults["excellon_exp_integer"],
  4794. self.defaults["excellon_exp_decimals"]
  4795. )
  4796. units = ''
  4797. try:
  4798. obj = self.collection.get_by_name(str(obj_name))
  4799. except:
  4800. # TODO: The return behavior has not been established... should raise exception?
  4801. return "Could not retrieve object: %s" % obj_name
  4802. # updated units
  4803. eunits = self.defaults["excellon_exp_units"]
  4804. ewhole = self.defaults["excellon_exp_integer"]
  4805. efract = self.defaults["excellon_exp_decimals"]
  4806. ezeros = self.defaults["excellon_exp_zeros"]
  4807. eformat = self.defaults[ "excellon_exp_format"]
  4808. fc_units = self.ui.general_options_form.general_app_group.units_radio.get_value().upper()
  4809. if fc_units == 'MM':
  4810. factor = 1 if eunits == 'METRIC' else 0.03937
  4811. else:
  4812. factor = 25.4 if eunits == 'METRIC' else 1
  4813. def make_excellon():
  4814. try:
  4815. time_str = "{:%A, %d %B %Y at %H:%M}".format(datetime.now())
  4816. header = 'M48\n'
  4817. header += ';EXCELLON GENERATED BY FLATCAM v%s - www.flatcam.org - Version Date: %s\n' % \
  4818. (str(self.version), str(self.version_date))
  4819. header += ';Filename: %s' % str(obj_name) + '\n'
  4820. header += ';Created on : %s' % time_str + '\n'
  4821. if eformat == 'dec':
  4822. has_slots, excellon_code = obj.export_excellon(ewhole, efract, factor=factor)
  4823. header += eunits + '\n'
  4824. for tool in obj.tools:
  4825. if eunits == 'METRIC':
  4826. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  4827. tool=str(tool),
  4828. dec=2)
  4829. else:
  4830. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  4831. tool=str(tool),
  4832. dec=4)
  4833. else:
  4834. if ezeros == 'LZ':
  4835. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  4836. form='ndec', e_zeros='LZ', factor=factor)
  4837. header += '%s,%s\n' % (eunits, 'LZ')
  4838. header += format_exc
  4839. for tool in obj.tools:
  4840. if eunits == 'METRIC':
  4841. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  4842. tool=str(tool),
  4843. dec=2)
  4844. else:
  4845. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  4846. tool=str(tool),
  4847. dec=4)
  4848. else:
  4849. has_slots, excellon_code = obj.export_excellon(ewhole, efract,
  4850. form='ndec', e_zeros='TZ', factor=factor)
  4851. header += '%s,%s\n' % (eunits, 'TZ')
  4852. header += format_exc
  4853. for tool in obj.tools:
  4854. if eunits == 'METRIC':
  4855. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  4856. tool=str(tool),
  4857. dec=2)
  4858. else:
  4859. header += "T{tool}F00S00C{:.{dec}f}\n".format(float(obj.tools[tool]['C']) * factor,
  4860. tool=str(tool),
  4861. dec=4)
  4862. header += '%\n'
  4863. footer = 'M30\n'
  4864. exported_excellon = header
  4865. exported_excellon += excellon_code
  4866. exported_excellon += footer
  4867. with open(filename, 'w') as fp:
  4868. fp.write(exported_excellon)
  4869. self.file_saved.emit("Excellon", filename)
  4870. self.inform.emit("[success] Excellon file exported to " + filename)
  4871. except Exception as e:
  4872. log.debug("App.export_excellon.make_excellon() --> %s" % str(e))
  4873. return 'fail'
  4874. if use_thread is True:
  4875. with self.proc_container.new("Exporting Excellon") as proc:
  4876. def job_thread_exc(app_obj):
  4877. ret = make_excellon()
  4878. if ret == 'fail':
  4879. self.inform.emit('[ERROR_NOTCL] Could not export Excellon file.')
  4880. return
  4881. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  4882. else:
  4883. ret = make_excellon()
  4884. if ret == 'fail':
  4885. self.inform.emit('[ERROR_NOTCL] Could not export Excellon file.')
  4886. return
  4887. def export_dxf(self, obj_name, filename, use_thread=True):
  4888. """
  4889. Exports a Geometry Object to an DXF file.
  4890. :param filename: Path to the DXF file to save to.
  4891. :return:
  4892. """
  4893. self.report_usage("export_dxf()")
  4894. if filename is None:
  4895. filename = self.defaults["global_last_save_folder"]
  4896. self.log.debug("export_dxf()")
  4897. format_exc = ''
  4898. units = ''
  4899. try:
  4900. obj = self.collection.get_by_name(str(obj_name))
  4901. except:
  4902. # TODO: The return behavior has not been established... should raise exception?
  4903. return "Could not retrieve object: %s" % obj_name
  4904. # updated units
  4905. units = self.ui.general_options_form.general_app_group.units_radio.get_value().upper()
  4906. if units == 'IN' or units == 'INCH':
  4907. units = 'INCH'
  4908. elif units == 'MM' or units == 'METIRC':
  4909. units ='METRIC'
  4910. def make_dxf():
  4911. try:
  4912. dxf_code = obj.export_dxf()
  4913. dxf_code.saveas(filename)
  4914. self.file_saved.emit("DXF", filename)
  4915. self.inform.emit("[success] DXF file exported to " + filename)
  4916. except:
  4917. return 'fail'
  4918. if use_thread is True:
  4919. with self.proc_container.new("Exporting DXF") as proc:
  4920. def job_thread_exc(app_obj):
  4921. ret = make_dxf()
  4922. if ret == 'fail':
  4923. self.inform.emit('[[WARNING_NOTCL]] Could not export DXF file.')
  4924. return
  4925. self.worker_task.emit({'fcn': job_thread_exc, 'params': [self]})
  4926. else:
  4927. ret = make_dxf()
  4928. if ret == 'fail':
  4929. self.inform.emit('[[WARNING_NOTCL]] Could not export DXF file.')
  4930. return
  4931. def import_svg(self, filename, geo_type='geometry', outname=None):
  4932. """
  4933. Adds a new Geometry Object to the projects and populates
  4934. it with shapes extracted from the SVG file.
  4935. :param filename: Path to the SVG file.
  4936. :param outname:
  4937. :return:
  4938. """
  4939. self.report_usage("import_svg()")
  4940. obj_type = ""
  4941. if geo_type is None or geo_type == "geometry":
  4942. obj_type = "geometry"
  4943. elif geo_type == "gerber":
  4944. obj_type = geo_type
  4945. else:
  4946. self.inform.emit("[ERROR_NOTCL] Not supported type was choosed as parameter. "
  4947. "Only Geometry and Gerber are supported")
  4948. return
  4949. units = self.ui.general_options_form.general_app_group.units_radio.get_value().upper()
  4950. def obj_init(geo_obj, app_obj):
  4951. geo_obj.import_svg(filename, obj_type, units=units)
  4952. geo_obj.multigeo = False
  4953. with self.proc_container.new("Importing SVG") as proc:
  4954. # Object name
  4955. name = outname or filename.split('/')[-1].split('\\')[-1]
  4956. self.new_object(obj_type, name, obj_init, autoselected=False)
  4957. self.progress.emit(20)
  4958. # Register recent file
  4959. self.file_opened.emit("svg", filename)
  4960. # GUI feedback
  4961. self.inform.emit("[success] Opened: " + filename)
  4962. self.progress.emit(100)
  4963. def import_dxf(self, filename, geo_type='geometry', outname=None):
  4964. """
  4965. Adds a new Geometry Object to the projects and populates
  4966. it with shapes extracted from the DXF file.
  4967. :param filename: Path to the DXF file.
  4968. :param outname:
  4969. :type putname: str
  4970. :return:
  4971. """
  4972. self.report_usage("import_dxf()")
  4973. obj_type = ""
  4974. if geo_type is None or geo_type == "geometry":
  4975. obj_type = "geometry"
  4976. elif geo_type == "gerber":
  4977. obj_type = geo_type
  4978. else:
  4979. self.inform.emit("[ERROR_NOTCL] Not supported type was choosed as parameter. "
  4980. "Only Geometry and Gerber are supported")
  4981. return
  4982. units = self.ui.general_options_form.general_app_group.units_radio.get_value().upper()
  4983. def obj_init(geo_obj, app_obj):
  4984. geo_obj.import_dxf(filename, obj_type, units=units)
  4985. geo_obj.multigeo = False
  4986. with self.proc_container.new("Importing DXF") as proc:
  4987. # Object name
  4988. name = outname or filename.split('/')[-1].split('\\')[-1]
  4989. self.new_object(obj_type, name, obj_init, autoselected=False)
  4990. self.progress.emit(20)
  4991. # Register recent file
  4992. self.file_opened.emit("dxf", filename)
  4993. # GUI feedback
  4994. self.inform.emit("[success] Opened: " + filename)
  4995. self.progress.emit(100)
  4996. def import_image(self, filename, type='gerber', dpi=96, mode='black', mask=[250, 250, 250, 250], outname=None):
  4997. """
  4998. Adds a new Geometry Object to the projects and populates
  4999. it with shapes extracted from the SVG file.
  5000. :param filename: Path to the SVG file.
  5001. :param outname:
  5002. :return:
  5003. """
  5004. self.report_usage("import_image()")
  5005. obj_type = ""
  5006. if type is None or type == "geometry":
  5007. obj_type = "geometry"
  5008. elif type == "gerber":
  5009. obj_type = type
  5010. else:
  5011. self.inform.emit("[ERROR_NOTCL] Not supported type was picked as parameter. "
  5012. "Only Geometry and Gerber are supported")
  5013. return
  5014. def obj_init(geo_obj, app_obj):
  5015. geo_obj.import_image(filename, units=units, dpi=dpi, mode=mode, mask=mask)
  5016. geo_obj.multigeo = False
  5017. with self.proc_container.new("Importing Image") as proc:
  5018. # Object name
  5019. name = outname or filename.split('/')[-1].split('\\')[-1]
  5020. units = self.ui.general_options_form.general_app_group.units_radio.get_value()
  5021. self.new_object(obj_type, name, obj_init)
  5022. self.progress.emit(20)
  5023. # Register recent file
  5024. self.file_opened.emit("image", filename)
  5025. # GUI feedback
  5026. self.inform.emit("[success] Opened: " + filename)
  5027. self.progress.emit(100)
  5028. def open_gerber(self, filename, outname=None):
  5029. """
  5030. Opens a Gerber file, parses it and creates a new object for
  5031. it in the program. Thread-safe.
  5032. :param outname: Name of the resulting object. None causes the
  5033. name to be that of the file.
  5034. :param filename: Gerber file filename
  5035. :type filename: str
  5036. :param follow: If true, the parser will not create polygons, just lines
  5037. following the gerber path.
  5038. :type follow: bool
  5039. :return: None
  5040. """
  5041. # How the object should be initialized
  5042. def obj_init(gerber_obj, app_obj):
  5043. assert isinstance(gerber_obj, FlatCAMGerber), \
  5044. "Expected to initialize a FlatCAMGerber but got %s" % type(gerber_obj)
  5045. # Opening the file happens here
  5046. self.progress.emit(30)
  5047. try:
  5048. gerber_obj.parse_file(filename)
  5049. except IOError:
  5050. app_obj.inform.emit("[ERROR_NOTCL] Failed to open file: " + filename)
  5051. app_obj.progress.emit(0)
  5052. self.inform.emit('[ERROR_NOTCL] Failed to open file: ' + filename)
  5053. return "fail"
  5054. except ParseError as err:
  5055. app_obj.inform.emit("[ERROR_NOTCL] Failed to parse file: " + filename + ". " + str(err))
  5056. app_obj.progress.emit(0)
  5057. self.log.error(str(err))
  5058. return "fail"
  5059. except:
  5060. msg = "[ERROR] An internal error has ocurred. See shell.\n"
  5061. msg += traceback.format_exc()
  5062. app_obj.inform.emit(msg)
  5063. return "fail"
  5064. if gerber_obj.is_empty():
  5065. # app_obj.inform.emit("[ERROR] No geometry found in file: " + filename)
  5066. # self.collection.set_active(gerber_obj.options["name"])
  5067. # self.collection.delete_active()
  5068. self.inform.emit("[ERROR_NOTCL] Object is not Gerber file or empty. Aborting object creation.")
  5069. return "fail"
  5070. # Further parsing
  5071. self.progress.emit(70) # TODO: Note the mixture of self and app_obj used here
  5072. App.log.debug("open_gerber()")
  5073. with self.proc_container.new("Opening Gerber") as proc:
  5074. self.progress.emit(10)
  5075. # Object name
  5076. name = outname or filename.split('/')[-1].split('\\')[-1]
  5077. ### Object creation ###
  5078. ret = self.new_object("gerber", name, obj_init, autoselected=False)
  5079. if ret == 'fail':
  5080. self.inform.emit('[ERROR_NOTCL] Open Gerber failed. Probable not a Gerber file.')
  5081. return
  5082. # Register recent file
  5083. self.file_opened.emit("gerber", filename)
  5084. self.progress.emit(100)
  5085. # GUI feedback
  5086. self.inform.emit("[success] Opened: " + filename)
  5087. def open_excellon(self, filename, outname=None):
  5088. """
  5089. Opens an Excellon file, parses it and creates a new object for
  5090. it in the program. Thread-safe.
  5091. :param outname: Name of the resulting object. None causes the
  5092. name to be that of the file.
  5093. :param filename: Excellon file filename
  5094. :type filename: str
  5095. :return: None
  5096. """
  5097. App.log.debug("open_excellon()")
  5098. #self.progress.emit(10)
  5099. # How the object should be initialized
  5100. def obj_init(excellon_obj, app_obj):
  5101. # self.progress.emit(20)
  5102. try:
  5103. ret = excellon_obj.parse_file(filename)
  5104. if ret == "fail":
  5105. log.debug("Excellon parsing failed.")
  5106. self.inform.emit("[ERROR_NOTCL] This is not Excellon file.")
  5107. return "fail"
  5108. except IOError:
  5109. app_obj.inform.emit("[ERROR_NOTCL] Cannot open file: " + filename)
  5110. log.debug("Could not open Excellon object.")
  5111. self.progress.emit(0) # TODO: self and app_bjj mixed
  5112. return "fail"
  5113. except:
  5114. msg = "[ERROR_NOTCL] An internal error has occurred. See shell.\n"
  5115. msg += traceback.format_exc()
  5116. app_obj.inform.emit(msg)
  5117. return "fail"
  5118. ret = excellon_obj.create_geometry()
  5119. if ret == 'fail':
  5120. log.debug("Could not create geometry for Excellon object.")
  5121. return "fail"
  5122. # if excellon_obj.is_empty():
  5123. # app_obj.inform.emit("[ERROR_NOTCL] No geometry found in file: " + filename)
  5124. # return "fail"
  5125. for tool in excellon_obj.tools:
  5126. if excellon_obj.tools[tool]['solid_geometry']:
  5127. return
  5128. app_obj.inform.emit("[ERROR_NOTCL] No geometry found in file: " + filename)
  5129. return "fail"
  5130. with self.proc_container.new("Opening Excellon."):
  5131. # Object name
  5132. name = outname or filename.split('/')[-1].split('\\')[-1]
  5133. ret = self.new_object("excellon", name, obj_init, autoselected=False)
  5134. if ret == 'fail':
  5135. self.inform.emit('[ERROR_NOTCL] Open Excellon file failed. Probable not an Excellon file.')
  5136. return
  5137. # Register recent file
  5138. self.file_opened.emit("excellon", filename)
  5139. # GUI feedback
  5140. self.inform.emit("[success] Opened: " + filename)
  5141. # self.progress.emit(100)
  5142. def open_gcode(self, filename, outname=None):
  5143. """
  5144. Opens a G-gcode file, parses it and creates a new object for
  5145. it in the program. Thread-safe.
  5146. :param outname: Name of the resulting object. None causes the
  5147. name to be that of the file.
  5148. :param filename: G-code file filename
  5149. :type filename: str
  5150. :return: None
  5151. """
  5152. App.log.debug("open_gcode()")
  5153. # How the object should be initialized
  5154. def obj_init(job_obj, app_obj_):
  5155. """
  5156. :type app_obj_: App
  5157. """
  5158. assert isinstance(app_obj_, App), \
  5159. "Initializer expected App, got %s" % type(app_obj_)
  5160. self.progress.emit(10)
  5161. try:
  5162. f = open(filename)
  5163. gcode = f.read()
  5164. f.close()
  5165. except IOError:
  5166. app_obj_.inform.emit("[ERROR_NOTCL] Failed to open " + filename)
  5167. self.progress.emit(0)
  5168. return "fail"
  5169. job_obj.gcode = gcode
  5170. self.progress.emit(20)
  5171. ret = job_obj.gcode_parse()
  5172. if ret == "fail":
  5173. self.inform.emit("[ERROR_NOTCL] This is not GCODE")
  5174. return "fail"
  5175. self.progress.emit(60)
  5176. job_obj.create_geometry()
  5177. with self.proc_container.new("Opening G-Code."):
  5178. # Object name
  5179. name = outname or filename.split('/')[-1].split('\\')[-1]
  5180. # New object creation and file processing
  5181. ret = self.new_object("cncjob", name, obj_init, autoselected=False)
  5182. if ret == 'fail':
  5183. self.inform.emit("[ERROR_NOTCL] Failed to create CNCJob Object. Probable not a GCode file.\n "
  5184. "Attempting to create a FlatCAM CNCJob Object from "
  5185. "G-Code file failed during processing")
  5186. return "fail"
  5187. # Register recent file
  5188. self.file_opened.emit("cncjob", filename)
  5189. # GUI feedback
  5190. self.inform.emit("[success] Opened: " + filename)
  5191. self.progress.emit(100)
  5192. def open_config_file(self, filename, run_from_arg=None):
  5193. """
  5194. Loads a config file from the specified file.
  5195. :param filename: Name of the file from which to load.
  5196. :type filename: str
  5197. :return: None
  5198. """
  5199. App.log.debug("Opening config file: " + filename)
  5200. # add the tab if it was closed
  5201. self.ui.plot_tab_area.addTab(self.ui.cncjob_tab, "Code Editor")
  5202. # first clear previous text in text editor (if any)
  5203. self.ui.code_editor.clear()
  5204. # Switch plot_area to CNCJob tab
  5205. self.ui.plot_tab_area.setCurrentWidget(self.ui.cncjob_tab)
  5206. try:
  5207. if filename:
  5208. f = QtCore.QFile(filename)
  5209. if f.open(QtCore.QIODevice.ReadOnly):
  5210. stream = QtCore.QTextStream(f)
  5211. gcode_edited = stream.readAll()
  5212. self.ui.code_editor.setPlainText(gcode_edited)
  5213. f.close()
  5214. except IOError:
  5215. App.log.error("Failed to open config file: %s" % filename)
  5216. self.inform.emit("[ERROR_NOTCL] Failed to open config file: %s" % filename)
  5217. return
  5218. def open_project(self, filename, run_from_arg=None):
  5219. """
  5220. Loads a project from the specified file.
  5221. 1) Loads and parses file
  5222. 2) Registers the file as recently opened.
  5223. 3) Calls on_file_new()
  5224. 4) Updates options
  5225. 5) Calls new_object() with the object's from_dict() as init method.
  5226. 6) Calls plot_all()
  5227. :param filename: Name of the file from which to load.
  5228. :type filename: str
  5229. :return: None
  5230. """
  5231. App.log.debug("Opening project: " + filename)
  5232. # Open and parse an uncompressed Project file
  5233. try:
  5234. f = open(filename, 'r')
  5235. except IOError:
  5236. App.log.error("Failed to open project file: %s" % filename)
  5237. self.inform.emit("[ERROR_NOTCL] Failed to open project file: %s" % filename)
  5238. return
  5239. try:
  5240. d = json.load(f, object_hook=dict2obj)
  5241. except:
  5242. App.log.error("Failed to parse project file: %s" % filename)
  5243. self.inform.emit("[ERROR_NOTCL] Failed to parse project file: %s" % filename)
  5244. f.close()
  5245. # Open and parse a compressed Project file
  5246. try:
  5247. with lzma.open(filename) as f:
  5248. file_content = f.read().decode('utf-8')
  5249. d = json.loads(file_content, object_hook=dict2obj)
  5250. except IOError:
  5251. App.log.error("Failed to open project file: %s" % filename)
  5252. self.inform.emit("[ERROR_NOTCL] Failed to open project file: %s" % filename)
  5253. return
  5254. self.file_opened.emit("project", filename)
  5255. # Clear the current project
  5256. ## NOT THREAD SAFE ##
  5257. if run_from_arg is True:
  5258. pass
  5259. else:
  5260. self.on_file_new()
  5261. #Project options
  5262. self.options.update(d['options'])
  5263. self.project_filename = filename
  5264. # self.ui.units_label.setText("[" + self.options["units"] + "]")
  5265. self.set_screen_units(self.options["units"])
  5266. # Re create objects
  5267. App.log.debug("Re-creating objects...")
  5268. for obj in d['objs']:
  5269. def obj_init(obj_inst, app_inst):
  5270. obj_inst.from_dict(obj)
  5271. App.log.debug(obj['kind'] + ": " + obj['options']['name'])
  5272. self.new_object(obj['kind'], obj['options']['name'], obj_init, active=False, fit=False, plot=True)
  5273. self.plot_all()
  5274. self.inform.emit("[success] Project loaded from: " + filename)
  5275. self.should_we_save = False
  5276. App.log.debug("Project loaded")
  5277. def propagate_defaults(self, silent=False):
  5278. """
  5279. This method is used to set default values in classes. It's
  5280. an alternative to project options but allows the use
  5281. of values invisible to the user.
  5282. :return: None
  5283. """
  5284. if silent is False:
  5285. self.log.debug("propagate_defaults()")
  5286. # Which objects to update the given parameters.
  5287. routes = {
  5288. "global_zdownrate": CNCjob,
  5289. "excellon_zeros": Excellon,
  5290. "excellon_format_upper_in": Excellon,
  5291. "excellon_format_lower_in": Excellon,
  5292. "excellon_format_upper_mm": Excellon,
  5293. "excellon_format_lower_mm": Excellon,
  5294. "excellon_units": Excellon,
  5295. "gerber_use_buffer_for_union": Gerber,
  5296. "geometry_multidepth": Geometry
  5297. }
  5298. for param in routes:
  5299. if param in routes[param].defaults:
  5300. try:
  5301. routes[param].defaults[param] = self.defaults[param]
  5302. if silent is False:
  5303. self.log.debug(" " + param + " OK")
  5304. except KeyError:
  5305. if silent is False:
  5306. self.log.debug(" ERROR: " + param + " not in defaults.")
  5307. else:
  5308. # Try extracting the name:
  5309. # classname_param here is param in the object
  5310. if param.find(routes[param].__name__.lower() + "_") == 0:
  5311. p = param[len(routes[param].__name__) + 1:]
  5312. if p in routes[param].defaults:
  5313. routes[param].defaults[p] = self.defaults[param]
  5314. if silent is False:
  5315. self.log.debug(" " + param + " OK!")
  5316. def restore_main_win_geom(self):
  5317. try:
  5318. self.ui.setGeometry(self.defaults["global_def_win_x"],
  5319. self.defaults["global_def_win_y"],
  5320. self.defaults["global_def_win_w"],
  5321. self.defaults["global_def_win_h"])
  5322. self.ui.splitter.setSizes([self.defaults["def_notebook_width"], 0])
  5323. settings = QSettings("Open Source", "FlatCAM")
  5324. if settings.contains("maximized_gui"):
  5325. maximized_ui = settings.value('maximized_gui', type=bool)
  5326. if maximized_ui is True:
  5327. self.ui.showMaximized()
  5328. except KeyError:
  5329. pass
  5330. def plot_all(self, zoom=True):
  5331. """
  5332. Re-generates all plots from all objects.
  5333. :return: None
  5334. """
  5335. self.log.debug("Plot_all()")
  5336. for obj in self.collection.get_list():
  5337. def worker_task(obj):
  5338. with self.proc_container.new("Plotting"):
  5339. obj.plot(kind=self.defaults["cncjob_plot_kind"])
  5340. if zoom:
  5341. self.object_plotted.emit(obj)
  5342. # Send to worker
  5343. self.worker_task.emit({'fcn': worker_task, 'params': [obj]})
  5344. # self.progress.emit(10)
  5345. #
  5346. # def worker_task(app_obj):
  5347. # print "worker task"
  5348. # percentage = 0.1
  5349. # try:
  5350. # delta = 0.9 / len(self.collection.get_list())
  5351. # except ZeroDivisionError:
  5352. # self.progress.emit(0)
  5353. # return
  5354. # for obj in self.collection.get_list():
  5355. # with self.proc_container.new("Plotting"):
  5356. # obj.plot()
  5357. # app_obj.object_plotted.emit(obj)
  5358. #
  5359. # percentage += delta
  5360. # self.progress.emit(int(percentage*100))
  5361. #
  5362. # self.progress.emit(0)
  5363. # self.plots_updated.emit()
  5364. #
  5365. # # Send to worker
  5366. # #self.worker.add_task(worker_task, [self])
  5367. # self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  5368. def register_folder(self, filename):
  5369. self.defaults["global_last_folder"] = os.path.split(str(filename))[0]
  5370. def register_save_folder(self, filename):
  5371. self.defaults["global_last_save_folder"] = os.path.split(str(filename))[0]
  5372. def set_progress_bar(self, percentage, text=""):
  5373. self.ui.progress_bar.setValue(int(percentage))
  5374. def setup_shell(self):
  5375. """
  5376. Creates shell functions. Runs once at startup.
  5377. :return: None
  5378. """
  5379. self.log.debug("setup_shell()")
  5380. def shelp(p=None):
  5381. if not p:
  5382. return "Available commands:\n" + \
  5383. '\n'.join([' ' + cmd for cmd in sorted(commands)]) + \
  5384. "\n\nType help <command_name> for usage.\n Example: help open_gerber"
  5385. if p not in commands:
  5386. return "Unknown command: %s" % p
  5387. return commands[p]["help"]
  5388. # --- Migrated to new architecture ---
  5389. # def options(name):
  5390. # ops = self.collection.get_by_name(str(name)).options
  5391. # return '\n'.join(["%s: %s" % (o, ops[o]) for o in ops])
  5392. def h(*args):
  5393. """
  5394. Pre-processes arguments to detect '-keyword value' pairs into dictionary
  5395. and standalone parameters into list.
  5396. """
  5397. kwa = {}
  5398. a = []
  5399. n = len(args)
  5400. name = None
  5401. for i in range(n):
  5402. match = re.search(r'^-([a-zA-Z].*)', args[i])
  5403. if match:
  5404. assert name is None
  5405. name = match.group(1)
  5406. continue
  5407. if name is None:
  5408. a.append(args[i])
  5409. else:
  5410. kwa[name] = args[i]
  5411. name = None
  5412. return a, kwa
  5413. @contextmanager
  5414. def wait_signal(signal, timeout=10000):
  5415. """
  5416. Block loop until signal emitted, timeout (ms) elapses
  5417. or unhandled exception happens in a thread.
  5418. :param signal: Signal to wait for.
  5419. """
  5420. loop = QtCore.QEventLoop()
  5421. # Normal termination
  5422. signal.connect(loop.quit)
  5423. # Termination by exception in thread
  5424. self.thread_exception.connect(loop.quit)
  5425. status = {'timed_out': False}
  5426. def report_quit():
  5427. status['timed_out'] = True
  5428. loop.quit()
  5429. yield
  5430. # Temporarily change how exceptions are managed.
  5431. oeh = sys.excepthook
  5432. ex = []
  5433. def except_hook(type_, value, traceback_):
  5434. ex.append(value)
  5435. oeh(type_, value, traceback_)
  5436. sys.excepthook = except_hook
  5437. # Terminate on timeout
  5438. if timeout is not None:
  5439. QtCore.QTimer.singleShot(timeout, report_quit)
  5440. #### Block ####
  5441. loop.exec_()
  5442. # Restore exception management
  5443. sys.excepthook = oeh
  5444. if ex:
  5445. self.raiseTclError(str(ex[0]))
  5446. if status['timed_out']:
  5447. raise Exception('Timed out!')
  5448. def make_docs():
  5449. output = ''
  5450. import collections
  5451. od = collections.OrderedDict(sorted(commands.items()))
  5452. for cmd_, val in od.items():
  5453. output += cmd_ + ' \n' + ''.join(['~'] * len(cmd_)) + '\n'
  5454. t = val['help']
  5455. usage_i = t.find('>')
  5456. if usage_i < 0:
  5457. expl = t
  5458. output += expl + '\n\n'
  5459. continue
  5460. expl = t[:usage_i - 1]
  5461. output += expl + '\n\n'
  5462. end_usage_i = t[usage_i:].find('\n')
  5463. if end_usage_i < 0:
  5464. end_usage_i = len(t[usage_i:])
  5465. output += ' ' + t[usage_i:] + '\n No parameters.\n'
  5466. else:
  5467. extras = t[usage_i+end_usage_i+1:]
  5468. parts = [s.strip() for s in extras.split('\n')]
  5469. output += ' ' + t[usage_i:usage_i+end_usage_i] + '\n'
  5470. for p in parts:
  5471. output += ' ' + p + '\n\n'
  5472. return output
  5473. '''
  5474. Howto implement TCL shell commands:
  5475. All parameters passed to command should be possible to set as None and test it afterwards.
  5476. This is because we need to see error caused in tcl,
  5477. if None value as default parameter is not allowed TCL will return empty error.
  5478. Use:
  5479. def mycommand(name=None,...):
  5480. Test it like this:
  5481. if name is None:
  5482. self.raise_tcl_error('Argument name is missing.')
  5483. When error ocurre, always use raise_tcl_error, never return "sometext" on error,
  5484. otherwise we will miss it and processing will silently continue.
  5485. Method raise_tcl_error pass error into TCL interpreter, then raise python exception,
  5486. which is catched in exec_command and displayed in TCL shell console with red background.
  5487. Error in console is displayed with TCL trace.
  5488. This behavior works only within main thread,
  5489. errors with promissed tasks can be catched and detected only with log.
  5490. TODO: this problem have to be addressed somehow, maybe rewrite promissing to be blocking somehow for TCL shell.
  5491. Kamil's comment: I will rewrite existing TCL commands from time to time to follow this rules.
  5492. '''
  5493. commands = {
  5494. 'help': {
  5495. 'fcn': shelp,
  5496. 'help': "Shows list of commands."
  5497. },
  5498. }
  5499. # Import/overwrite tcl commands as objects of TclCommand descendants
  5500. # This modifies the variable 'commands'.
  5501. tclCommands.register_all_commands(self, commands)
  5502. # Add commands to the tcl interpreter
  5503. for cmd in commands:
  5504. self.tcl.createcommand(cmd, commands[cmd]['fcn'])
  5505. # Make the tcl puts function return instead of print to stdout
  5506. self.tcl.eval('''
  5507. rename puts original_puts
  5508. proc puts {args} {
  5509. if {[llength $args] == 1} {
  5510. return "[lindex $args 0]"
  5511. } else {
  5512. eval original_puts $args
  5513. }
  5514. }
  5515. ''')
  5516. def setup_recent_items(self):
  5517. # TODO: Move this to constructor
  5518. icons = {
  5519. "gerber": "share/flatcam_icon16.png",
  5520. "excellon": "share/drill16.png",
  5521. "cncjob": "share/cnc16.png",
  5522. "project": "share/project16.png",
  5523. "svg": "share/geometry16.png",
  5524. "dxf": "share/dxf16.png",
  5525. "image": "share/image16.png"
  5526. }
  5527. openers = {
  5528. 'gerber': lambda fname: self.worker_task.emit({'fcn': self.open_gerber, 'params': [fname]}),
  5529. 'excellon': lambda fname: self.worker_task.emit({'fcn': self.open_excellon, 'params': [fname]}),
  5530. 'cncjob': lambda fname: self.worker_task.emit({'fcn': self.open_gcode, 'params': [fname]}),
  5531. 'project': self.open_project,
  5532. 'svg': self.import_svg,
  5533. 'dxf': self.import_dxf,
  5534. 'image': self.import_image
  5535. }
  5536. # Open file
  5537. try:
  5538. f = open(self.data_path + '/recent.json')
  5539. except IOError:
  5540. App.log.error("Failed to load recent item list.")
  5541. self.inform.emit("[ERROR_NOTCL] Failed to load recent item list.")
  5542. return
  5543. try:
  5544. self.recent = json.load(f)
  5545. except json.scanner.JSONDecodeError:
  5546. App.log.error("Failed to parse recent item list.")
  5547. self.inform.emit("[ERROR_NOTCL] Failed to parse recent item list.")
  5548. f.close()
  5549. return
  5550. f.close()
  5551. # Closure needed to create callbacks in a loop.
  5552. # Otherwise late binding occurs.
  5553. def make_callback(func, fname):
  5554. def opener():
  5555. func(fname)
  5556. return opener
  5557. def reset_recent():
  5558. # Reset menu
  5559. self.ui.recent.clear()
  5560. self.recent = []
  5561. try:
  5562. f = open(self.data_path + '/recent.json', 'w')
  5563. except IOError:
  5564. App.log.error("Failed to open recent items file for writing.")
  5565. return
  5566. json.dump(self.recent, f)
  5567. # Reset menu
  5568. self.ui.recent.clear()
  5569. # Create menu items
  5570. for recent in self.recent:
  5571. filename = recent['filename'].split('/')[-1].split('\\')[-1]
  5572. try:
  5573. action = QtWidgets.QAction(QtGui.QIcon(icons[recent["kind"]]), filename, self)
  5574. # Attach callback
  5575. o = make_callback(openers[recent["kind"]], recent['filename'])
  5576. action.triggered.connect(o)
  5577. self.ui.recent.addAction(action)
  5578. except KeyError:
  5579. App.log.error("Unsupported file type: %s" % recent["kind"])
  5580. # Last action in Recent Files menu is one that Clear the content
  5581. clear_action = QtWidgets.QAction(QtGui.QIcon('share/trash32.png'), "Clear Recent files", self)
  5582. clear_action.triggered.connect(reset_recent)
  5583. self.ui.recent.addSeparator()
  5584. self.ui.recent.addAction(clear_action)
  5585. # self.builder.get_object('open_recent').set_submenu(recent_menu)
  5586. # self.ui.menufilerecent.set_submenu(recent_menu)
  5587. # recent_menu.show_all()
  5588. # self.ui.recent.show()
  5589. self.log.debug("Recent items list has been populated.")
  5590. def setup_component_editor(self):
  5591. # label = QtWidgets.QLabel("Choose an item from Project")
  5592. # label.setAlignment(QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)
  5593. sel_title = QtWidgets.QTextEdit(
  5594. '<b>Shortcut Key List</b>')
  5595. sel_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  5596. sel_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  5597. # font = self.sel_title.font()
  5598. # font.setPointSize(12)
  5599. # self.sel_title.setFont(font)
  5600. selected_text = '''
  5601. <p><span style="font-size:14px"><strong>Selected Tab - Choose an Item from Project Tab</strong></span></p>
  5602. <p><span style="font-size:10px"><strong>Details</strong>:<br />
  5603. The normal flow when working in FlatCAM is the following:</span></p>
  5604. <ol>
  5605. <li><span style="font-size:10px">Loat/Import a Gerber, Excellon, Gcode, DXF, Raster Image or SVG file into FlatCAM using either the menu&#39;s, toolbars, key shortcuts or even dragging and dropping the files on the GUI.<br />
  5606. <br />
  5607. You can also load a <strong>FlatCAM project</strong> by double clicking on the project file, drag &amp; drop of the file into the FLATCAM GUI or through the menu/toolbar links offered within the app.</span><br />
  5608. &nbsp;</li>
  5609. <li><span style="font-size:10px">Once an object is available in the Project Tab, by selecting it and then focusing on <strong>SELECTED TAB </strong>(more simpler is to double click the object name in the Project Tab), <strong>SELECTED TAB </strong>will be updated with the object properties according to it&#39;s kind: Gerber, Excellon, Geometry or CNCJob object.<br />
  5610. <br />
  5611. If the selection of the object is done on the canvas by single click instead, and the <strong>SELECTED TAB</strong> is in focus, again the object properties will be displayed into the Selected Tab. Alternatively, double clicking on the object on the canvas will bring the <strong>SELECTED TAB</strong> and populate it even if it was out of focus.<br />
  5612. <br />
  5613. You can change the parameters in this screen and the flow direction is like this:<br />
  5614. <br />
  5615. <strong>Gerber/Excellon Object</strong> -&gt; Change Param -&gt; Generate Geometry -&gt;<strong> Geometry Object </strong>-&gt; Add tools (change param in Selected Tab) -&gt; Generate CNCJob -&gt;<strong> CNCJob Object </strong>-&gt; Verify GCode (through Edit CNC Code) and/or append/prepend to GCode (again, done in <strong>SELECTED TAB)&nbsp;</strong>-&gt; Save GCode</span></li>
  5616. </ol>
  5617. <p><span style="font-size:10px">A list of key shortcuts is available through an menu entry in <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut: <strng>F3</strong>.</span></p>
  5618. '''
  5619. sel_title.setText(selected_text)
  5620. sel_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  5621. self.ui.selected_scroll_area.setWidget(sel_title)
  5622. # tool_title = QtWidgets.QTextEdit(
  5623. # '<b>Shortcut Key List</b>')
  5624. # tool_title.setTextInteractionFlags(QtCore.Qt.NoTextInteraction)
  5625. # tool_title.setFrameStyle(QtWidgets.QFrame.NoFrame)
  5626. # # font = self.sel_title.font()
  5627. # # font.setPointSize(12)
  5628. # # self.sel_title.setFont(font)
  5629. #
  5630. # tool_text = '''
  5631. # <p><span style="font-size:14px"><strong>Tool Tab - Choose an Item in Tools Menu</strong></span></p>
  5632. #
  5633. # <p><span style="font-size:10px"><strong>Details</strong>:<br />
  5634. # Some of the functionality of FlatCAM have been implemented as tools (a sort of plugins). </span></p>
  5635. #
  5636. # <p><span style="font-size:10px">Most of the tools are accessible through&nbsp;the Tools menu or by using the associated shortcut keys.<br />
  5637. # Each such a tool, if it needs an object to be used as a source it will provide the way to select this object(s) through a series of comboboxes. The result of using a tool is either a Geometry, an information that can be used in the app or it can be a file that can be saved.</span></p>
  5638. #
  5639. # <ol>
  5640. # </ol>
  5641. #
  5642. # <p><span style="font-size:10px">A list of key shortcuts is available through an menu entry in <strong>Help -&gt; Shortcuts List</strong>&nbsp;or through it&#39;s own key shortcut: &#39;`&#39; (key left to 1).</span></p>
  5643. #
  5644. # '''
  5645. #
  5646. # tool_title.setText(tool_text)
  5647. # tool_title.setSizePolicy(QtWidgets.QSizePolicy.Expanding, QtWidgets.QSizePolicy.Expanding)
  5648. #
  5649. # self.ui.tool_scroll_area.setWidget(tool_title)
  5650. def setup_obj_classes(self):
  5651. """
  5652. Sets up application specifics on the FlatCAMObj class.
  5653. :return: None
  5654. """
  5655. FlatCAMObj.app = self
  5656. ObjectCollection.app = self
  5657. FCProcess.app = self
  5658. FCProcessContainer.app = self
  5659. def version_check(self):
  5660. """
  5661. Checks for the latest version of the program. Alerts the
  5662. user if theirs is outdated. This method is meant to be run
  5663. in a separate thread.
  5664. :return: None
  5665. """
  5666. self.log.debug("version_check()")
  5667. if self.ui.general_defaults_form.general_gui_group.send_stats_cb.get_value() is True:
  5668. full_url = App.version_url + \
  5669. "?s=" + str(self.defaults['global_serial']) + \
  5670. "&v=" + str(self.version) + \
  5671. "&os=" + str(self.os) + \
  5672. "&" + urllib.parse.urlencode(self.defaults["global_stats"])
  5673. else:
  5674. # no_stats dict; just so it won't break things on website
  5675. no_ststs_dict = {}
  5676. no_ststs_dict["global_ststs"] = {}
  5677. full_url = App.version_url + \
  5678. "?s=" + str(self.defaults['global_serial']) + \
  5679. "&v=" + str(self.version) + \
  5680. "&os=" + str(self.os) + \
  5681. "&" + urllib.parse.urlencode(no_ststs_dict["global_ststs"])
  5682. App.log.debug("Checking for updates @ %s" % full_url)
  5683. ### Get the data
  5684. try:
  5685. f = urllib.request.urlopen(full_url)
  5686. except:
  5687. # App.log.warning("Failed checking for latest version. Could not connect.")
  5688. self.log.warning("Failed checking for latest version. Could not connect.")
  5689. self.inform.emit("[WARNING_NOTCL] Failed checking for latest version. Could not connect.")
  5690. return
  5691. try:
  5692. data = json.load(f)
  5693. except Exception as e:
  5694. App.log.error("Could not parse information about latest version.")
  5695. self.inform.emit("[ERROR_NOTCL] Could not parse information about latest version.")
  5696. App.log.debug("json.load(): %s" % str(e))
  5697. f.close()
  5698. return
  5699. f.close()
  5700. ### Latest version?
  5701. if self.version >= data["version"]:
  5702. App.log.debug("FlatCAM is up to date!")
  5703. self.inform.emit("[success] FlatCAM is up to date!")
  5704. return
  5705. App.log.debug("Newer version available.")
  5706. self.message.emit(
  5707. "Newer Version Available",
  5708. str("There is a newer version of FlatCAM " +
  5709. "available for download:<br><br>" +
  5710. "<B>" + data["name"] + "</b><br>" +
  5711. data["message"].replace("\n", "<br>")),
  5712. "info"
  5713. )
  5714. def on_zoom_fit(self, event):
  5715. """
  5716. Callback for zoom-out request. This can be either from the corresponding
  5717. toolbar button or the '1' key when the canvas is focused. Calls ``self.adjust_axes()``
  5718. with axes limits from the geometry bounds of all objects.
  5719. :param event: Ignored.
  5720. :return: None
  5721. """
  5722. self.plotcanvas.fit_view()
  5723. def disable_all_plots(self):
  5724. self.report_usage("disable_all_plots()")
  5725. self.disable_plots(self.collection.get_list())
  5726. self.inform.emit("[success]All plots disabled.")
  5727. def disable_other_plots(self):
  5728. self.report_usage("disable_other_plots()")
  5729. self.disable_plots(self.collection.get_non_selected())
  5730. self.inform.emit("[success]All non selected plots disabled.")
  5731. def enable_all_plots(self):
  5732. self.report_usage("enable_all_plots()")
  5733. self.enable_plots(self.collection.get_list())
  5734. self.inform.emit("[success]All plots enabled.")
  5735. # TODO: FIX THIS
  5736. '''
  5737. By default this is not threaded
  5738. If threaded the app give warnings like this:
  5739. QObject::connect: Cannot queue arguments of type 'QVector<int>'
  5740. (Make sure 'QVector<int>' is registered using qRegisterMetaType().
  5741. '''
  5742. def enable_plots(self, objects, threaded=False):
  5743. if threaded is True:
  5744. def worker_task(app_obj):
  5745. percentage = 0.1
  5746. try:
  5747. delta = 0.9 / len(objects)
  5748. except ZeroDivisionError:
  5749. self.progress.emit(0)
  5750. return
  5751. for obj in objects:
  5752. obj.options['plot'] = True
  5753. percentage += delta
  5754. self.progress.emit(int(percentage*100))
  5755. self.progress.emit(0)
  5756. self.plots_updated.emit()
  5757. self.collection.update_view()
  5758. # Send to worker
  5759. # self.worker.add_task(worker_task, [self])
  5760. self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  5761. else:
  5762. for obj in objects:
  5763. obj.options['plot'] = True
  5764. self.progress.emit(0)
  5765. self.plots_updated.emit()
  5766. self.collection.update_view()
  5767. # TODO: FIX THIS
  5768. '''
  5769. By default this is not threaded
  5770. If threaded the app give warnings like this:
  5771. QObject::connect: Cannot queue arguments of type 'QVector<int>'
  5772. (Make sure 'QVector<int>' is registered using qRegisterMetaType().
  5773. '''
  5774. def disable_plots(self, objects, threaded=False):
  5775. # TODO: This method is very similar to replot_all. Try to merge.
  5776. """
  5777. Disables plots
  5778. :param objects: list
  5779. Objects to be disabled
  5780. :return:
  5781. """
  5782. if threaded is True:
  5783. self.progress.emit(10)
  5784. def worker_task(app_obj):
  5785. percentage = 0.1
  5786. try:
  5787. delta = 0.9 / len(objects)
  5788. except ZeroDivisionError:
  5789. self.progress.emit(0)
  5790. return
  5791. for obj in objects:
  5792. obj.options['plot'] = False
  5793. percentage += delta
  5794. self.progress.emit(int(percentage*100))
  5795. self.progress.emit(0)
  5796. self.plots_updated.emit()
  5797. self.collection.update_view()
  5798. # Send to worker
  5799. self.worker_task.emit({'fcn': worker_task, 'params': [self]})
  5800. else:
  5801. for obj in objects:
  5802. obj.options['plot'] = False
  5803. self.plots_updated.emit()
  5804. self.collection.update_view()
  5805. def clear_plots(self):
  5806. objects = self.collection.get_list()
  5807. for obj in objects:
  5808. obj.clear(obj == objects[-1])
  5809. # Clear pool to free memory
  5810. self.clear_pool()
  5811. def generate_cnc_job(self, objects):
  5812. self.report_usage("generate_cnc_job()")
  5813. # for obj in objects:
  5814. # obj.generatecncjob()
  5815. for obj in objects:
  5816. obj.on_generatecnc_button_click()
  5817. def save_project(self, filename):
  5818. """
  5819. Saves the current project to the specified file.
  5820. :param filename: Name of the file in which to save.
  5821. :type filename: str
  5822. :return: None
  5823. """
  5824. self.log.debug("save_project()")
  5825. with self.proc_container.new("Saving FlatCAM Project") as proc:
  5826. ## Capture the latest changes
  5827. # Current object
  5828. try:
  5829. self.collection.get_active().read_form()
  5830. except:
  5831. self.log.debug("[WARNING] There was no active object")
  5832. pass
  5833. # Project options
  5834. self.options_read_form()
  5835. # Serialize the whole project
  5836. d = {"objs": [obj.to_dict() for obj in self.collection.get_list()],
  5837. "options": self.options,
  5838. "version": self.version}
  5839. if self.defaults["global_save_compressed"] is True:
  5840. with lzma.open(filename, "w", preset=int(self.defaults['global_compression_level'])) as f:
  5841. g = json.dumps(d, default=to_dict, indent=2, sort_keys=True).encode('utf-8')
  5842. # # Write
  5843. f.write(g)
  5844. self.inform.emit("[success] Project saved to: %s" % filename)
  5845. else:
  5846. # Open file
  5847. try:
  5848. f = open(filename, 'w')
  5849. except IOError:
  5850. App.log.error("[ERROR] Failed to open file for saving: %s", filename)
  5851. return
  5852. # Write
  5853. json.dump(d, f, default=to_dict, indent=2, sort_keys=True)
  5854. f.close()
  5855. # verification of the saved project
  5856. # Open and parse
  5857. try:
  5858. saved_f = open(filename, 'r')
  5859. except IOError:
  5860. self.inform.emit("[ERROR_NOTCL] Failed to verify project file: %s. Retry to save it." % filename)
  5861. return
  5862. try:
  5863. saved_d = json.load(saved_f, object_hook=dict2obj)
  5864. except:
  5865. self.inform.emit(
  5866. "[ERROR_NOTCL] Failed to parse saved project file: %s. Retry to save it." % filename)
  5867. f.close()
  5868. return
  5869. saved_f.close()
  5870. if 'version' in saved_d:
  5871. self.inform.emit("[success] Project saved to: %s" % filename)
  5872. else:
  5873. self.inform.emit("[ERROR_NOTCL] Failed to save project file: %s. Retry to save it." % filename)
  5874. def on_options_app2project(self):
  5875. """
  5876. Callback for Options->Transfer Options->App=>Project. Copies options
  5877. from application defaults to project defaults.
  5878. :return: None
  5879. """
  5880. self.report_usage("on_options_app2project")
  5881. self.defaults_read_form()
  5882. self.options.update(self.defaults)
  5883. self.options_write_form()
  5884. def on_options_project2app(self):
  5885. """
  5886. Callback for Options->Transfer Options->Project=>App. Copies options
  5887. from project defaults to application defaults.
  5888. :return: None
  5889. """
  5890. self.report_usage("on_options_project2app")
  5891. self.options_read_form()
  5892. self.defaults.update(self.options)
  5893. self.defaults_write_form()
  5894. def on_options_project2object(self):
  5895. """
  5896. Callback for Options->Transfer Options->Project=>Object. Copies options
  5897. from project defaults to the currently selected object.
  5898. :return: None
  5899. """
  5900. self.report_usage("on_options_project2object")
  5901. self.options_read_form()
  5902. obj = self.collection.get_active()
  5903. if obj is None:
  5904. self.inform.emit("WARNING: No object selected.")
  5905. return
  5906. for option in self.options:
  5907. if option.find(obj.kind + "_") == 0:
  5908. oname = option[len(obj.kind) + 1:]
  5909. obj.options[oname] = self.options[option]
  5910. obj.to_form() # Update UI
  5911. def on_options_object2project(self):
  5912. """
  5913. Callback for Options->Transfer Options->Object=>Project. Copies options
  5914. from the currently selected object to project defaults.
  5915. :return: None
  5916. """
  5917. self.report_usage("on_options_object2project")
  5918. obj = self.collection.get_active()
  5919. if obj is None:
  5920. self.inform.emit("WARNING: No object selected.")
  5921. return
  5922. obj.read_form()
  5923. for option in obj.options:
  5924. if option in ['name']: # TODO: Handle this better...
  5925. continue
  5926. self.options[obj.kind + "_" + option] = obj.options[option]
  5927. self.options_write_form()
  5928. def on_options_object2app(self):
  5929. """
  5930. Callback for Options->Transfer Options->Object=>App. Copies options
  5931. from the currently selected object to application defaults.
  5932. :return: None
  5933. """
  5934. self.report_usage("on_options_object2app")
  5935. obj = self.collection.get_active()
  5936. if obj is None:
  5937. self.inform.emit("WARNING: No object selected.")
  5938. return
  5939. obj.read_form()
  5940. for option in obj.options:
  5941. if option in ['name']: # TODO: Handle this better...
  5942. continue
  5943. self.defaults[obj.kind + "_" + option] = obj.options[option]
  5944. self.defaults_write_form()
  5945. def on_options_app2object(self):
  5946. """
  5947. Callback for Options->Transfer Options->App=>Object. Copies options
  5948. from application defaults to the currently selected object.
  5949. :return: None
  5950. """
  5951. self.report_usage("on_options_app2object")
  5952. self.defaults_read_form()
  5953. obj = self.collection.get_active()
  5954. if obj is None:
  5955. self.inform.emit("WARNING: No object selected.")
  5956. return
  5957. for option in self.defaults:
  5958. if option.find(obj.kind + "_") == 0:
  5959. oname = option[len(obj.kind) + 1:]
  5960. obj.options[oname] = self.defaults[option]
  5961. obj.to_form() # Update UI
  5962. # end of file